From 6002a983c3d96faa9f2030425b195309a67e05a2 Mon Sep 17 00:00:00 2001 From: Wolfgang Berger Date: Fri, 12 Feb 2016 16:01:39 +0100 Subject: [PATCH 001/210] 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/210] 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 java.util.Set; 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 class ObjcsessionmanagerGenerator extends DefaultCodegen implements Codeg 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" +@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 { - _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/210] 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/210] 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 fb68c6c93d4bc42234b3e7c53cfe8ca3b44d65f8 Mon Sep 17 00:00:00 2001 From: Wolfgang Berger Date: Thu, 14 Jul 2016 15:38:05 +0200 Subject: [PATCH 005/210] update naming --- ...enerator.java => ObjcSessionManagerClientCodegen.java} | 8 ++++---- .../META-INF/services/io.swagger.codegen.CodegenConfig | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) rename output/objcSessionManager/src/main/java/io/swagger/codegen/languages/{ObjcSessionManagerGenerator.java => ObjcSessionManagerClientCodegen.java} (98%) diff --git a/output/objcSessionManager/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerGenerator.java b/output/objcSessionManager/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java similarity index 98% rename from output/objcSessionManager/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerGenerator.java rename to output/objcSessionManager/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java index 385f4c23b4c..b340a39cb19 100644 --- a/output/objcSessionManager/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerGenerator.java +++ b/output/objcSessionManager/src/main/java/io/swagger/codegen/languages/ObjcSessionManagerClientCodegen.java @@ -17,7 +17,7 @@ import java.util.Set; import org.apache.commons.lang.StringUtils; -public class ObjcSessionManagerGenerator extends DefaultCodegen implements CodegenConfig { +public class ObjcSessionManagerClientCodegen 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 ObjcSessionManagerClientCodegen() { super(); - outputFolder = "generated-code" + File.separator + "ObjcSessionManager"; + outputFolder = "generated-code" + File.separator + "objcSessionManager"; modelTemplateFiles.put("model-header.mustache", ".h"); modelTemplateFiles.put("model-body.mustache", ".m"); @@ -49,7 +49,7 @@ public class ObjcSessionManagerGenerator extends DefaultCodegen implements Codeg apiTemplateFiles.put("api-header.mustache", ".h"); apiTemplateFiles.put("api-body.mustache", ".m"); - embeddedTemplateDir = templateDir = "ObjcSessionManager"; + 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 c52d64bdbbf..e3cfa53811b 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 @@ -io.swagger.codegen.languages.ObjcSessionManagerGenerator \ No newline at end of file +io.swagger.codegen.languages.ObjcSessionManagerClientCodegen \ No newline at end of file From d120902e4b47e80e24819b1588a6b0881f793daf Mon Sep 17 00:00:00 2001 From: Wolfgang Berger Date: Fri, 15 Jul 2016 15:36:24 +0200 Subject: [PATCH 006/210] integrate latest objc changes into objc-sessionmanager --- .../objc/Configuration-body.mustache | 2 +- output/objcSessionManager/README.md | 18 +- output/objcSessionManager/pom.xml | 6 +- .../ObjcSessionManagerClientCodegen.java | 1134 ++++++++++------- .../ApiSessionManager-body.mustache | 760 +++++------ .../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 | 40 +- .../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, 7955 insertions(+), 1144 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 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"; - 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 = 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 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"}; + protected boolean generateCoreData = false; + protected Set advancedMapingTypes = new HashSet(); - - public ObjcSessionManagerClientCodegen() { - super(); + public ObjcSessionManagerClientCodegen() { + super(); - outputFolder = "generated-code" + File.separator + "objcSessionManager"; + 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"); - modelTemplateFiles.put("model-header.mustache", ".h"); - modelTemplateFiles.put("model-body.mustache", ".m"); + 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"); - apiTemplateFiles.put("api-header.mustache", ".h"); - apiTemplateFiles.put("api-body.mustache", ".m"); + 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"); - embeddedTemplateDir = templateDir = "objcSessionManager"; + 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"); - 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("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"); - 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( + // 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", "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" - )); + // 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(); + importMapping = new HashMap(); - foundationClasses = new HashSet( - Arrays.asList( - "NSNumber", - "NSObject", - "NSString", - "NSDate", - "NSURL", - "NSDictionary") - ); + foundationClasses = new HashSet( + Arrays.asList( + "NSNumber", + "NSObject", + "NSString", + "NSDate", + "NSData", + "NSURL", + "NSDictionary") + ); - instantiationTypes.put("array", "NSMutableArray"); - instantiationTypes.put("map", "NSMutableDictionary"); + 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")); + 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 CodegenType getTag() { - return CodegenType.CLIENT; - } + @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 getName() { - return "objc-SessionManager"; - } + @Override + public String getTypeDeclaration(String name) { + if (languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) { + return name; + } else { + return name + "*"; + } + } - @Override - public String getHelp() { - return "Generates an Objective-C client library."; - } + @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 void processOpts() { - super.processOpts(); + @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(); - if (additionalProperties.containsKey(POD_NAME)) { - setPodName((String) additionalProperties.get(POD_NAME)); - } + 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 + "*"; + } + } + } - if (additionalProperties.containsKey(CodegenConstants.POD_VERSION)) { - setPodVersion((String) additionalProperties.get(CodegenConstants.POD_VERSION)); - } + @Override + public boolean isDataTypeBinary(String dataType) { + return dataType.toLowerCase().startsWith("nsdata"); + } - 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)); - } + @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) + } - 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); + // 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) + } + */ - String swaggerFolder = podName; + return toModelNameWithoutReservedWordCheck(type); + } - modelPackage = swaggerFolder; - apiPackage = swaggerFolder; + /* + * 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'. - 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")); - } + // 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; + } - @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; - } - } + if (!StringUtils.isEmpty(modelNamePrefix)) { // set model prefix + type = modelNamePrefix + "_" + type; + } - @Override - public String getTypeDeclaration(String name) { - if (languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) { - return name; - } else { - return name + "*"; - } - } + return classPrefix + camelize(type); // add class prefix + } + } - @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 toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } - @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - String innerType = getSwaggerType(inner); + @Override + protected void setNonArrayMapProperty(CodegenProperty property, String type) { + super.setNonArrayMapProperty(property, type); + if ("NSDictionary".equals(type)) { + property.setter = "initWithDictionary"; + } else { + property.setter = "initWithValues"; + } + } - String innerTypeDeclaration = getTypeDeclaration(inner); + @Override + public String toModelImport(String name) { + return name; + } - if (innerTypeDeclaration.endsWith("*")) { - innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); - } + @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); + } - // 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(); + @Override + public String apiFileFolder() { + return (outputFolder + "/"+ apiPackage() + "/" + apiFilesPath).replace("/", File.separator); + } - String innerTypeDeclaration = getTypeDeclaration(inner); + @Override + public String modelFileFolder() { + return (outputFolder + "/"+ modelPackage() + "/" + modelFilesPath).replace("/", File.separator); + } - if (innerTypeDeclaration.endsWith("*")) { - innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); - } - return getSwaggerType(p) + "* /* NSString, " + innerTypeDeclaration + " */"; - } else { - String swaggerType = getSwaggerType(p); + public String coreFileFolder() { + return (apiPackage() + "/" + coreFilesPath).replace("/", File.separator); + } - // 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 toApiName(String name) { + return classPrefix + camelize(name) + "Api"; + } - @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'. + @Override + public String toApiFilename(String name) { + return classPrefix + camelize(name) + "Api"; + } - // 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 toVarName(String name) { + // sanitize name + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - @Override - public String toModelFilename(String name) { - // should be the same as the model name - return toModelName(name); - } + // if it's all upper case, do noting + if (name.matches("^[A-Z_]$")) { + return name; + } - @Override - protected void setNonArrayMapProperty(CodegenProperty property, String type) { - super.setNonArrayMapProperty(property, type); - if ("NSDictionary".equals(type)) { - property.setter = "initWithDictionary"; - } else { - property.setter = "initWithValues"; - } - } + // 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); + } - @Override - public String toModelImport(String name) { - return name; - } + // camelize (lower first character) the variable name + // e.g. `pet_id` to `petId` + name = camelize(name, true); - @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); - } + // for reserved word or word starting with number, prepend `_` + if (isReservedWord(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } - return name; - } + return name; + } - @Override - public String toParamName(String name) { - // should be the same as variable name - return toVarName(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; - } + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } - @SuppressWarnings("static-method") - public String escapeSpecialWord(String name) { - return "var_" + 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"); - } + @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"); - } + // 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); - } + return camelize(sanitizeName(operationId), true); + } - public void setClassPrefix(String classPrefix) { - this.classPrefix = classPrefix; - } + public void setClassPrefix(String classPrefix) { + this.classPrefix = classPrefix; + } - public void setPodName(String podName) { - this.podName = podName; - } + 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; - } + public void setPodVersion(String podVersion) { + this.podVersion = podVersion; + } - /** - * 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(); - } - } + public void setAuthorEmail(String authorEmail) { + this.authorEmail = authorEmail; + } - return null; - } -} \ No newline at end of file + 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 +// Added for easier override to modify request +- (void)postProcessRequest:(NSMutableURLRequest *)request { + // Always disable cookies! + [request setHTTPShouldHandleCookies:NO]; +} -- (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; +#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; } - NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - - completionBlock(nil, augmentedError); + NSString * separatorStyle = separatorStyles[format]; + NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([values componentsJoinedByString:separatorStyle]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; } else { - completionBlock(responseObject, nil); + NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([NSString stringWithFormat:@"%@",queryParam]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; } - }]; - - return task; + counter += 1; + } + return requestUrl; } -- (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 - +/** + * Update header and query params based on authentication settings + */ - (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers queryParams:(NSDictionary *__autoreleasing *)querys WithAuthSettings:(NSArray *)authSettings { @@ -279,16 +439,19 @@ 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"]]; - } + + 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; } } @@ -296,338 +459,25 @@ NSString * const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}Respon *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; } -- (id)sanitizeForSerialization:(id)object { +- (AFSecurityPolicy *) customSecurityPolicy { + AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; - if (object == nil) { - return nil; + id<{{classPrefix}}Configuration> config = self.configuration; + + if (config.sslCaCert) { + NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert]; + [securityPolicy setPinnedCertificates:[NSSet setWithObject:certData]]; } - 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]; + + if (config.verifySSL) { + [securityPolicy setAllowInvalidCertificates:NO]; } else { - NSException *e = [NSException - exceptionWithName:@"InvalidObjectArgumentException" - reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", object] - userInfo:nil]; - @throw e; + [securityPolicy setAllowInvalidCertificates:YES]; + [securityPolicy setValidatesDomainName:NO]; } -} -- (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); + 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 + * Custom security policy * - * @param accepts NSArray of header - * - * @return The Accept header + * @return AFSecurityPolicy */ -+ (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; +- (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; -@property (nonatomic, readonly) NSString *host; -@property (nonatomic, readonly) NSString *username; -@property (nonatomic, readonly) NSString *password; +/** + * 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 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; -@property (nonatomic, assign) BOOL cacheEnabled; -@property (nonatomic, assign) BOOL offlineState; +/** + * Default base url + */ +@property (nonatomic) NSString *host; -@property (nonatomic, strong) NSString *host; -@property (nonatomic, strong) NSString *username; -@property (nonatomic, strong) NSString *password; +/** + * Api key values for Api Key type Authentication + * + * To add or remove api key, use `setApiKey:forApiKeyIdentifier:`. + */ +@property (readonly, nonatomic, strong) NSDictionary *apiKey; -@property (nonatomic, strong) NSString *tempFolderPath; +/** + * 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 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}} + + +@interface {{classname}}: NSObject <{{classPrefix}}Api> + +extern NSString* k{{classname}}ErrorDomain; +extern NSInteger k{{classname}}MissingParamErrorCode; {{#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}} +/// {{#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 -{ ++ (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]; + 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 e077e80dcb27d60c161116683fbf6decf15b6505 Mon Sep 17 00:00:00 2001 From: Wolfgang Berger Date: Mon, 18 Jul 2016 10:45:22 +0200 Subject: [PATCH 007/210] 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 008/210] 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 749a17d292e3cc9c8e764b86b31596bc98cac809 Mon Sep 17 00:00:00 2001 From: Wolfgang Berger Date: Mon, 18 Jul 2016 12:00:22 +0200 Subject: [PATCH 009/210] 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 class ObjcSessionManagerClientCodegen extends DefaultCodegen implements C 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 010/210] 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} | 196 ++++++++---------- ...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, 315 insertions(+), 278 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 class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { 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 class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { 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 +#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 { --(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 { // 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 011/210] 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 52cfd0f86f6f989e52af130e1e8d7b96d2ddb67e Mon Sep 17 00:00:00 2001 From: Jim Schubert Date: Sun, 24 Jul 2016 11:21:06 -0400 Subject: [PATCH 012/210] [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 013/210] 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 014/210] [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 class NancyFXServerCodegen extends AbstractCSharpCodegen { } 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 class NancyFXServerCodegen extends AbstractCSharpCodegen { } 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 class NancyFXServerCodegen extends AbstractCSharpCodegen { } 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 class NancyFXServerCodegen extends AbstractCSharpCodegen { } 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 @@ namespace IO.Swagger.Client /// 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 @@ namespace IO.Swagger.Client /// 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 @@ namespace IO.Swagger.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/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 @@ namespace IO.Swagger.v2.Models 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 @@ using NodaTime; 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 @@ namespace IO.Swagger.v2.Modules 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 @@ namespace IO.Swagger.v2.Modules 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 @@ namespace IO.Swagger.v2.Modules 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 @@ namespace IO.Swagger.v2.Modules 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 @@ namespace IO.Swagger.v2.Modules /// /// /// 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 @@ namespace IO.Swagger.v2.Modules 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 @@ namespace IO.Swagger.v2.Modules /// /// /// 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 @@ namespace IO.Swagger.v2.Modules /// 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 @@ namespace IO.Swagger.v2.Modules /// 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 @@ namespace IO.Swagger.v2.Modules 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 @@ namespace IO.Swagger.v2.Modules 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 @@ namespace IO.Swagger.v2.Modules 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 @@ namespace IO.Swagger.v2.Modules 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 @@ namespace IO.Swagger.v2.Modules 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 @@ namespace IO.Swagger.v2.Modules 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 @@ namespace IO.Swagger.v2.Modules /// 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 @@ namespace IO.Swagger.v2.Modules 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 @@ namespace IO.Swagger.v2.Modules 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 @@ namespace IO.Swagger.v2.Modules 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 @@ namespace IO.Swagger.v2.Modules 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 @@ namespace IO.Swagger.v2.Modules { 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 @@ namespace IO.Swagger.v2.Modules { service.LogoutUser(Context); - return new Response { ContentType = "application/json"}; + return new Response { ContentType = "application/xml"}; }; Put["/user/{username}"] = parameters => @@ -79,8 +89,10 @@ namespace IO.Swagger.v2.Modules 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 @@ namespace IO.Swagger.v2.Modules /// 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 @@ namespace IO.Swagger.v2.Modules /// /// /// Context of request - /// List of user object (optional) + /// List of user object /// void CreateUsersWithArrayInput(NancyContext context, List body); @@ -110,7 +122,7 @@ namespace IO.Swagger.v2.Modules /// /// /// Context of request - /// List of user object (optional) + /// List of user object /// void CreateUsersWithListInput(NancyContext context, List body); @@ -134,8 +146,8 @@ namespace IO.Swagger.v2.Modules /// /// /// 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 @@ namespace IO.Swagger.v2.Modules /// /// 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 015/210] 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 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { 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 @@ class FakeApi 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 @@ class ObjectSerializer } 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_of_number_only import ArrayOfNumberOnly 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 @@ class FakeApi(object): 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_of_number_only import ArrayOfNumberOnly 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_class' 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 016/210] 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 017/210] [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 018/210] 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 019/210] #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 020/210] #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 021/210] [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 022/210] 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 class HaskellServantCodegen extends DefaultCodegen implements CodegenConf // 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 023/210] 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 024/210] 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 025/210] 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 class AdditionalPropertiesClass { 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 class AdditionalPropertiesClass { return this; } + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, 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 class ArrayOfArrayOfNumberOnly { 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 class ArrayOfNumberOnly { 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 class ArrayTest { return this; } + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + /** * Get arrayOfString * @return arrayOfString @@ -71,6 +76,11 @@ public class ArrayTest { return this; } + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + /** * Get arrayArrayOfInteger * @return arrayArrayOfInteger @@ -89,6 +99,11 @@ public class ArrayTest { 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 class MapTest { 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 class MapTest { 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 class MixedPropertiesAndAdditionalPropertiesClass { 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 class Pet { return this; } + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + /** * Get photoUrls * @return photoUrls @@ -157,6 +162,11 @@ public class Pet { 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 class AdditionalPropertiesClass { 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 class AdditionalPropertiesClass { return this; } + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, 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 class ArrayOfArrayOfNumberOnly { 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 class ArrayOfNumberOnly { 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 class ArrayTest { return this; } + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + /** * Get arrayOfString * @return arrayOfString @@ -71,6 +76,11 @@ public class ArrayTest { return this; } + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + /** * Get arrayArrayOfInteger * @return arrayArrayOfInteger @@ -89,6 +99,11 @@ public class ArrayTest { 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 class MapTest { 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 class MapTest { 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 class MixedPropertiesAndAdditionalPropertiesClass { 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 class Pet { return this; } + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + /** * Get photoUrls * @return photoUrls @@ -157,6 +162,11 @@ public class Pet { 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 class AdditionalPropertiesClass { 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 class AdditionalPropertiesClass { return this; } + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, 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 class ArrayOfArrayOfNumberOnly { 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 class ArrayOfNumberOnly { 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 class ArrayTest { return this; } + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + /** * Get arrayOfString * @return arrayOfString @@ -71,6 +76,11 @@ public class ArrayTest { return this; } + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + /** * Get arrayArrayOfInteger * @return arrayArrayOfInteger @@ -89,6 +99,11 @@ public class ArrayTest { 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 class MapTest { 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 class MapTest { 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 class MixedPropertiesAndAdditionalPropertiesClass { 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 class Pet { return this; } + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + /** * Get photoUrls * @return photoUrls @@ -157,6 +162,11 @@ public class Pet { 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 class AdditionalPropertiesClass { 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 class AdditionalPropertiesClass { return this; } + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, 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 class ArrayOfArrayOfNumberOnly { 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 class ArrayOfNumberOnly { 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 class ArrayTest { return this; } + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + /** * Get arrayOfString * @return arrayOfString @@ -71,6 +76,11 @@ public class ArrayTest { return this; } + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + /** * Get arrayArrayOfInteger * @return arrayArrayOfInteger @@ -89,6 +99,11 @@ public class ArrayTest { 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 class MapTest { 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 class MapTest { 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 class MixedPropertiesAndAdditionalPropertiesClass { 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 class Pet { return this; } + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + /** * Get photoUrls * @return photoUrls @@ -157,6 +162,11 @@ public class Pet { 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 class AdditionalPropertiesClass { 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 class AdditionalPropertiesClass { return this; } + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, 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 class ArrayOfArrayOfNumberOnly { 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 class ArrayOfNumberOnly { 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 class ArrayTest { return this; } + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + /** * Get arrayOfString * @return arrayOfString @@ -71,6 +76,11 @@ public class ArrayTest { return this; } + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + /** * Get arrayArrayOfInteger * @return arrayArrayOfInteger @@ -89,6 +99,11 @@ public class ArrayTest { 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 class MapTest { 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 class MapTest { 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 class MixedPropertiesAndAdditionalPropertiesClass { 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 class Pet { return this; } + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + /** * Get photoUrls * @return photoUrls @@ -160,6 +165,11 @@ public class Pet { 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 class AdditionalPropertiesClass { 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 class AdditionalPropertiesClass { return this; } + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, 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 class ArrayOfArrayOfNumberOnly { 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 class ArrayOfNumberOnly { 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 class ArrayTest { return this; } + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + /** * Get arrayOfString * @return arrayOfString @@ -71,6 +76,11 @@ public class ArrayTest { return this; } + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + /** * Get arrayArrayOfInteger * @return arrayArrayOfInteger @@ -89,6 +99,11 @@ public class ArrayTest { 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 class MapTest { 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 class MapTest { 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 class MixedPropertiesAndAdditionalPropertiesClass { 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 class Pet { return this; } + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + /** * Get photoUrls * @return photoUrls @@ -160,6 +165,11 @@ public class Pet { 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 class AdditionalPropertiesClass { 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 class AdditionalPropertiesClass { return this; } + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, 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 class ArrayOfArrayOfNumberOnly { 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 class ArrayOfNumberOnly { 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 class ArrayTest { return this; } + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + /** * Get arrayOfString * @return arrayOfString @@ -71,6 +76,11 @@ public class ArrayTest { return this; } + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + /** * Get arrayArrayOfInteger * @return arrayArrayOfInteger @@ -89,6 +99,11 @@ public class ArrayTest { 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 class MapTest { 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 class MapTest { 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 class MixedPropertiesAndAdditionalPropertiesClass { 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 class Pet { return this; } + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + /** * Get photoUrls * @return photoUrls @@ -160,6 +165,11 @@ public class Pet { 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 class AdditionalPropertiesClass { 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 class AdditionalPropertiesClass { return this; } + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, 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 class ArrayOfArrayOfNumberOnly { 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 class ArrayOfNumberOnly { 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 class ArrayTest { return this; } + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + /** * Get arrayOfString * @return arrayOfString @@ -71,6 +76,11 @@ public class ArrayTest { return this; } + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + /** * Get arrayArrayOfInteger * @return arrayArrayOfInteger @@ -89,6 +99,11 @@ public class ArrayTest { 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 class MapTest { 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 class MapTest { 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 class MixedPropertiesAndAdditionalPropertiesClass { 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 class Pet { return this; } + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + /** * Get photoUrls * @return photoUrls @@ -160,6 +165,11 @@ public class Pet { 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 026/210] 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 027/210] 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 028/210] 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 029/210] 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 class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig { //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 class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig { 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 030/210] 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 031/210] 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 032/210] 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 033/210] [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 034/210] [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 | 40 +- .../Swaggers/AlamofireImplementations.swift | 2 +- .../SwaggerClientTests/Pods/Alamofire/LICENSE | 2 +- .../Pods/Alamofire/README.md | 298 ++++-- .../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 | 124 ++- .../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 | 410 ++++---- .../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 | 298 ++++-- .../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 | 124 ++- .../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 | 898 +++++++++--------- .../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, 3381 insertions(+), 1718 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", - "lastName" : "aeiou", - "password" : "aeiou", - "userStatus" : 123, - "phone" : "aeiou", + - examples: [{example={ "id" : 123456789, + "lastName" : "aeiou", + "phone" : "aeiou", + "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", - "lastName" : "aeiou", - "password" : "aeiou", - "userStatus" : 123, - "phone" : "aeiou", +, contentType=application/xml}] + - examples: [{example={ "id" : 123456789, + "lastName" : "aeiou", + "phone" : "aeiou", + "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 +### Timeline -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. +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 + +The `NetworkReachabilityManager` listens for reachability changes of hosts and addresses for both WWAN and WiFi network interfaces. + +```swift +let manager = NetworkReachabilityManager(host: "www.apple.com") + +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. + --- -## 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 +* [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 /** @@ -148,18 +171,22 @@ public class Request { // MARK: - State + /** + Resumes the request. + */ + public func resume() { + if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } + + task.resume() + NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidResume, object: task) + } + /** Suspends the request. */ public func suspend() { task.suspend() - } - - /** - Resumes the request. - */ - public func resume() { - task.resume() + 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,14 +404,6 @@ /* End PBXGroup section */ /* Begin PBXHeadersBuildPhase section */ - 5F7B61281F714E2A64A51E80A2C9C062 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 2C5450AC69398958CF6F7539EF7D99E5 /* Alamofire-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; 6C794A7763C2F85750D66CDD002E271F /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; @@ -419,6 +420,14 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + EFDF3B631BBB965A372347705CA14854 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 9469DF81ECB494E84675969B5E13374C /* Alamofire-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; FF84DA06E91FBBAA756A7832375803CE /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; @@ -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,6 +569,31 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + 95CC2C7E06DC188A05DAAEE9CAA555A3 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 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; + }; C2AD20E62D6A15C7CE3E20F8A811548F /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; @@ -568,41 +602,19 @@ ); 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 */ 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,6 +978,15 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; + 3CFB42910790CF0BDBCCEBAACD6B9367 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 75218111E718FACE36F771E8ABECDB62 /* Debug */, + 32AD5F8918CA8B349E4671410FA624C9 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; 75D763A79F74FE2B1D1C066F125F118E /* Build configuration list for PBXNativeTarget "PetstoreClient" */ = { isa = XCConfigurationList; buildConfigurations = ( @@ -975,15 +996,6 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 8B2B2DA2F7F80D41B1FDB5FACFA4B3DE /* Build configuration list for PBXNativeTarget "Alamofire" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - BE1BF3E5FC53BAFA505AB342C35E1F50 /* Debug */, - 9B26D3A39011247999C097562A550399 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; A255A180370C09C28653A0EC123D2678 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClient" */ = { isa = XCConfigurationList; buildConfigurations = ( 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() - completion(response: nil, error: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) + 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"])) + } } } 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 +### Timeline -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. +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 + +The `NetworkReachabilityManager` listens for reachability changes of hosts and addresses for both WWAN and WiFi network interfaces. + +```swift +let manager = NetworkReachabilityManager(host: "www.apple.com") + +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. + --- -## 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 +* [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 /** @@ -148,18 +171,22 @@ public class Request { // MARK: - State + /** + Resumes the request. + */ + public func resume() { + if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } + + task.resume() + NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidResume, object: task) + } + /** Suspends the request. */ public func suspend() { task.suspend() - } - - /** - Resumes the request. - */ - public func resume() { - task.resume() + 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 @@ static inline NSMutableURLRequest *OMGMutableURLRequest() { [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 @@ static inline NSMutableURLRequest *OMGMutableURLRequest() { @implementation OMGHTTPURLRQ + (NSMutableURLRequest *)GET:(NSString *)urlString :(NSDictionary *)params error:(NSError **)error { - id queryString = OMGFormURLEncode(params); - if (queryString) urlString = [urlString stringByAppendingFormat:@"?%@", queryString]; + NSString *queryString = OMGFormURLEncode(params); + if (queryString.length) urlString = [urlString stringByAppendingFormat:@"?%@", queryString]; id url = [NSURL URLWithString:urlString]; if (!url) { diff --git a/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods/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,18 +424,106 @@ 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 = Pods; + sourceTree = ""; + }; + 41488276780D879BE61AA0617BDC29A0 /* Alamofire */ = { + isa = PBXGroup; + children = ( + 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 = ""; + }; + 45199ED47CEA398ADDDFDE8F9D0A591D /* Support Files */ = { + isa = PBXGroup; + children = ( + 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 = ""; + }; + 72B5E9FE2F2C23CD28C86A837D09964A /* CorePromise */ = { + isa = PBXGroup; + children = ( + 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 = CorePromise; + sourceTree = ""; + }; + 79A7166061336F6A7FF214DB285A9584 /* Foundation */ = { + isa = PBXGroup; + children = ( + 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 = ""; @@ -433,45 +534,12 @@ 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, 22F52349E1BE90FC6E064DAAC9EA9612 /* Development Pods */, E85F5154C248966A1EC7B7B6EACB20CF /* Frameworks */, - CF22FA3EE19C3EC42FEBA1247EB70D85 /* Pods */, + 27098387544928716460DD8F5024EE8A /* Pods */, 01A9CB10E1E9A90B6A796034AF093E8C /* Products */, C1A60D10CED0E61146591438999C7502 /* Targets Support Files */, ); sourceTree = ""; }; - 7DFF028D9F7D443B2361EBEDACC99624 /* OMGHTTPURLRQ */ = { - isa = PBXGroup; - children = ( - 8FCF5C41226503429E7875DF4CA4D36E /* FormURLEncode */, - A00A425F2E132E8FF4DE929E7DF9CC1E /* RQ */, - 1D2330E920AD5F6E4655BE449D006A77 /* Support Files */, - 07467E828160702D1DB7EC2F492C337C /* UserAgent */, - ); - path = OMGHTTPURLRQ; - sourceTree = ""; - }; - 81B1E3A8E00502B38EACDE3617A7A73B /* Support Files */ = { - isa = PBXGroup; - children = ( - 792D14AC86CD98AA9C31373287E0F353 /* Info.plist */, - CDC4DD7DB9F4C34A288BECA73BC13B57 /* PromiseKit.modulemap */, - CC49FF2A84C0E0E9349747D94036B728 /* PromiseKit.xcconfig */, - 9042667D08D783E45394FE8B97EE6468 /* PromiseKit-dummy.m */, - 122D5005A81832479161CD1D223C573A /* PromiseKit-prefix.pch */, - ); - name = "Support Files"; - path = "../Target Support Files/PromiseKit"; - sourceTree = ""; - }; - 83C3888E1F7B1FC86D9CBF3B74DC2896 /* QuartzCore */ = { - isa = PBXGroup; - children = ( - 27E0FE41D771BE8BE3F0D4F1DAD0B179 /* CALayer+AnyPromise.h */, - 04A22F2595054D39018E03961CA7283A /* CALayer+AnyPromise.m */, - ); - name = QuartzCore; - sourceTree = ""; - }; 88CE2B3F08C34DDB098AD8A5DCC1DF1E /* Pods-SwaggerClient */ = { isa = PBXGroup; children = ( @@ -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,60 +572,48 @@ 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 */, - ); - path = Alamofire; - sourceTree = ""; - }; - 9E101A4CE6D982647EED5C067C563BED /* 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 */, - ); - name = "Support Files"; - path = "../Target Support Files/Alamofire"; - sourceTree = ""; - }; - A00A425F2E132E8FF4DE929E7DF9CC1E /* RQ */ = { - isa = PBXGroup; - children = ( - 450166FEA2155A5821D97744A0127DF8 /* OMGHTTPURLRQ.h */, - 9D579267FC1F163C8F04B444DAEFED0D /* OMGHTTPURLRQ.m */, + 859DDC0FFB13DB9C838BA38D0641A1BA /* OMGHTTPURLRQ.h */, + 3EEC1FB4B45C5C247D2D0FB33D4F5A1D /* OMGHTTPURLRQ.m */, ); name = RQ; sourceTree = ""; }; + 977CD7DB18C38452FB8DCFCEC690CBDE /* Support Files */ = { + isa = PBXGroup; + children = ( + 94F9363EEBC7855FA6B9A6B7485D5170 /* Info.plist */, + D3A577E7C7DF4A2157D9001CA0D40A72 /* PromiseKit.modulemap */, + 2E750A27FAB06DE866BC27CC8FA07806 /* PromiseKit.xcconfig */, + B09DEE52CBDEC1EA108DD327EF036F4A /* PromiseKit-dummy.m */, + 11683764D40FE241FCEEB379EE92E817 /* PromiseKit-prefix.pch */, + ); + name = "Support Files"; + path = "../Target Support Files/PromiseKit"; + sourceTree = ""; + }; AD94092456F8ABCB18F74CAC75AD85DE /* Classes */ = { isa = PBXGroup; children = ( @@ -586,6 +622,15 @@ path = Classes; sourceTree = ""; }; + B00B1E51F2524127FFF78DB52869057E /* FormURLEncode */ = { + isa = PBXGroup; + children = ( + 3B1578E353CE37C4C4201EC9101DE67F /* OMGFormURLEncode.h */, + 56CDA7C9327CF6F3DFC66FC128D7365B /* OMGFormURLEncode.m */, + ); + name = FormURLEncode; + sourceTree = ""; + }; B4A5C9FBC309EB945E2E089539878931 /* iOS */ = { isa = PBXGroup; children = ( @@ -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,14 +772,6 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 5F7B61281F714E2A64A51E80A2C9C062 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 2C5450AC69398958CF6F7539EF7D99E5 /* Alamofire-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; 8EC2461DE4442A7991319873E6012164 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; @@ -782,6 +783,14 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + EFDF3B631BBB965A372347705CA14854 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 9469DF81ECB494E84675969B5E13374C /* Alamofire-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; FF84DA06E91FBBAA756A7832375803CE /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; @@ -868,23 +877,6 @@ productReference = FE74210E04DEED84E2357049E4589759 /* PetstoreClient.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 = F2BEA8A3A2770EF455BB2ECCDA8CE0AD /* Alamofire.framework */; - productType = "com.apple.product-type.framework"; - }; 462B200BD111D7F438E47B7C42B6772F /* Pods-SwaggerClientTests */ = { isa = PBXNativeTarget; buildConfigurationList = 245A935A321D16F418F4D34C5D17D2B6 /* Build configuration list for PBXNativeTarget "Pods-SwaggerClientTests" */; @@ -902,6 +894,23 @@ productReference = FEEC58138887E454A6CBD0A7BFF2910A /* Pods_SwaggerClientTests.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 = F2BEA8A3A2770EF455BB2ECCDA8CE0AD /* Alamofire.framework */; + productType = "com.apple.product-type.framework"; + }; /* End PBXNativeTarget section */ /* Begin PBXProject 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,6 +1584,15 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; + 3CFB42910790CF0BDBCCEBAACD6B9367 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 75218111E718FACE36F771E8ABECDB62 /* Debug */, + 32AD5F8918CA8B349E4671410FA624C9 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; 620A8F6BEDF449F55F08EDB4CDBF60A2 /* Build configuration list for PBXNativeTarget "OMGHTTPURLRQ" */ = { isa = XCConfigurationList; buildConfigurations = ( @@ -1581,15 +1602,6 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 8B2B2DA2F7F80D41B1FDB5FACFA4B3DE /* Build configuration list for PBXNativeTarget "Alamofire" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - BE1BF3E5FC53BAFA505AB342C35E1F50 /* Debug */, - 9B26D3A39011247999C097562A550399 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; B5E28E2093F917340AF5AAA0FCE5E37D /* Build configuration list for PBXNativeTarget "PetstoreClient" */ = { isa = XCConfigurationList; buildConfigurations = ( 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 035/210] 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 036/210] 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 037/210] [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 java.util.List; 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 io.swagger.model.*; 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.*; 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 119/210] 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 120/210] [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 @@ public interface PetApi { 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 @@ import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; @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 class ClientConfiguration { 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 @@ 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; 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 @@ 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; 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 @@ 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; 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 @@ 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; 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 @@ 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; 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 @@ 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; 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 @@ public interface PetApi { 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 @@ 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; 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 @@ 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; 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 @@ 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; 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 @@ 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; 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 @@ 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; 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 @@ 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; 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 @@ public interface FakeApi { } - @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 @@ package io.swagger.api; 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 @@ public interface FakeApi { ); - @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 @@ package io.swagger.api; 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 @@ package io.swagger.api; 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 @@ public interface FakeApi { ); - @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 @@ package io.swagger.api; 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 121/210] [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 abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen 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 class JavaInflectorServerCodegen extends AbstractJavaCodegen { 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.codegen.*; 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 class SpringCodegen extends AbstractJavaCodegen { 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 class SpringCodegen extends AbstractJavaCodegen { 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 @@ import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; @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 class ClientConfiguration { 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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import org.joda.time.DateTime; */ 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 class Order { } @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 @@ import java.util.List; */ 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 class Pet { } @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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import org.joda.time.DateTime; */ 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 class Order { } @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 @@ import java.util.List; */ 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 class Pet { } @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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import java.util.Map; -@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 @@ import io.swagger.annotations.ApiModelProperty; -@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 @@ 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 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 @@ 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 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 @@ 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 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 @@ 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 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 @@ import io.swagger.model.Animal; -@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 @@ import io.swagger.annotations.ApiModelProperty; -@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 @@ import io.swagger.annotations.ApiModelProperty; -@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 @@ import io.swagger.model.Animal; -@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 @@ 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 EnumArrays { /** * Gets or Sets justSymbol @@ -30,11 +30,23 @@ public class EnumArrays { } @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 class EnumArrays { } @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.JsonValue; +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 @@ import io.swagger.annotations.ApiModelProperty; -@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 class EnumTest { } @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 class EnumTest { } @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 class EnumTest { } @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 @@ import java.util.Date; -@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 @@ import io.swagger.annotations.ApiModelProperty; -@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 @@ import java.util.Map; -@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 class MapTest { } @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 @@ import java.util.Map; -@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 @@ import io.swagger.annotations.ApiModelProperty; **/ @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 @@ import io.swagger.annotations.ApiModelProperty; -@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 @@ import io.swagger.annotations.ApiModelProperty; **/ @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 @@ import io.swagger.annotations.ApiModelProperty; **/ @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 @@ 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 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 @@ import java.util.Date; -@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 class Order { } @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 @@ 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 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 class Pet { } @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 @@ import io.swagger.annotations.ApiModelProperty; -@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 @@ import io.swagger.annotations.ApiModelProperty; -@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 @@ import io.swagger.annotations.ApiModelProperty; -@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 @@ import io.swagger.annotations.ApiModelProperty; -@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 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") +@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 io.swagger.model.Pet; 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 io.swagger.model.*; 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.*; 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.PetApiService; 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 class PetApi { @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 class PetApi { @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.StoreApiService; 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.UserApiService; 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 @@ 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; - +/** + * 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 class Category { 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 class Category { * 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 @@ 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; - +/** + * 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 class ModelApiResponse { 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 class ModelApiResponse { * 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 @@ 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; @@ -10,19 +11,31 @@ import java.util.Date; - +/** + * Order + */ 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; - + /** + * Order Status + */ public enum StatusEnum { PLACED("placed"), + APPROVED("approved"), + DELIVERED("delivered"); private String value; @@ -34,119 +47,137 @@ public class Order { @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 class Order { 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 class Order { * 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 @@ 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; @@ -13,20 +14,34 @@ import java.util.List; - +/** + * 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(); + + @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 class Pet { @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 class Pet { 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 class Pet { * 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 @@ 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; - +/** + * 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 class Tag { 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 class Tag { * 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 @@ 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; - +/** + * 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 class User { 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 class User { * 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 @@ import java.util.Map; */ 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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import java.util.List; */ 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 @@ import java.util.List; */ 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 @@ import java.util.List; */ 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 @@ import io.swagger.model.Animal; */ 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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import io.swagger.model.Animal; */ 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 class EnumArrays { } @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 class EnumArrays { } @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.JsonValue; +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 class EnumTest { } @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 class EnumTest { } @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 class EnumTest { } @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 @@ import java.time.OffsetDateTime; */ 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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import java.util.Map; */ public class MapTest { + @JsonProperty("map_map_of_string") private Map> mapMapOfString = new HashMap>(); /** @@ -35,11 +36,23 @@ public class MapTest { } @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 @@ import java.util.Map; */ 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 @@ import io.swagger.annotations.ApiModelProperty; @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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import io.swagger.annotations.ApiModelProperty; @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 @@ import io.swagger.annotations.ApiModelProperty; @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 @@ import java.math.BigDecimal; */ 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 @@ import java.time.OffsetDateTime; */ 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 class Order { } @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 @@ import java.util.List; */ 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 class Pet { } @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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ package io.swagger.api; 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 @@ package io.swagger.api; 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 @@ import java.util.Map; */ 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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import java.util.List; */ 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 @@ import java.util.List; */ 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 @@ import java.util.List; */ 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 @@ import io.swagger.model.Animal; */ 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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import io.swagger.model.Animal; */ 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 class EnumArrays { } @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 class EnumArrays { } @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.JsonValue; +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 class EnumTest { } @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 class EnumTest { } @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 class EnumTest { } @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 @@ import org.joda.time.LocalDate; */ 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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import java.util.Map; */ public class MapTest { + @JsonProperty("map_map_of_string") private Map> mapMapOfString = new HashMap>(); /** @@ -35,11 +36,23 @@ public class MapTest { } @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 @@ import org.joda.time.DateTime; */ 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 @@ import io.swagger.annotations.ApiModelProperty; @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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import io.swagger.annotations.ApiModelProperty; @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 @@ import io.swagger.annotations.ApiModelProperty; @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 @@ import java.math.BigDecimal; */ 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 @@ import org.joda.time.DateTime; */ 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 class Order { } @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 @@ import java.util.List; */ 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 class Pet { } @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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ package io.swagger.api; 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 @@ package io.swagger.api; 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 @@ import java.util.Map; */ 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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import java.util.List; */ 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 @@ import java.util.List; */ 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 @@ import java.util.List; */ 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 @@ import io.swagger.model.Animal; */ 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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import io.swagger.model.Animal; */ 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 class EnumArrays { } @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 class EnumArrays { } @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.JsonValue; +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 class EnumTest { } @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 class EnumTest { } @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 class EnumTest { } @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 @@ import org.joda.time.LocalDate; */ 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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import java.util.Map; */ public class MapTest { + @JsonProperty("map_map_of_string") private Map> mapMapOfString = new HashMap>(); /** @@ -35,11 +36,23 @@ public class MapTest { } @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 @@ import org.joda.time.DateTime; */ 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 @@ import io.swagger.annotations.ApiModelProperty; @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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import io.swagger.annotations.ApiModelProperty; @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 @@ import io.swagger.annotations.ApiModelProperty; @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 @@ import java.math.BigDecimal; */ 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 @@ import org.joda.time.DateTime; */ 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 class Order { } @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 @@ import java.util.List; */ 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 class Pet { } @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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 @@ import io.swagger.annotations.ApiModelProperty; */ 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 122/210] 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 123/210] 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 @@ import java.util.regex.Pattern; 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 class DefaultCodegen { 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 class DefaultGenerator extends AbstractGenerator implements Generator { 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 class CodegenConfigurator { 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 124/210] 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 | 21 ++++-- 11 files changed, 174 insertions(+), 79 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 class DefaultCodegen { * @return properly-escaped pattern */ public String toRegularExpression(String pattern) { - return escapeText(pattern); + return escapeText(addRegularExpressionDelimiter(pattern)); } /** @@ -3264,4 +3264,19 @@ public class DefaultCodegen { } } } + + /** + * 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 class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { 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 @@ class FakeApi(object): 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 @@ class FakeApi(object): >>> 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 @@ class FakeApi(object): """ 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 @@ class FakeApi(object): >>> 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 @@ class FakeApi(object): 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 @@ class FakeApi(object): # 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 @@ class FakeApi(object): 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 @@ class FakeApi(object): 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 @@ class FakeApi(object): 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 @@ class Configuration(object): :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 @@ class Configuration(object): '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 @@ module Petstore # 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 @@ module Petstore # 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore # 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 @@ module Petstore 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 @@ module Petstore # 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 @@ module Petstore # 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 @@ module Petstore :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,13 +201,6 @@ module Petstore # 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', @@ -215,6 +208,20 @@ module Petstore key: 'api_key', value: api_key_with_prefix('api_key') }, + 'petstore_auth' => + { + type: 'oauth2', + in: 'header', + key: 'Authorization', + value: "Bearer #{access_token}" + }, + 'http_basic_test' => + { + type: 'basic', + in: 'header', + key: 'Authorization', + value: basic_auth_token + }, } end 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 125/210] 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.DateTimeProperty; 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 class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig { 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 126/210] 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 class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod 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 127/210] [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 | 44 ++++---- .../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 | 44 ++++---- .../Swaggers/AlamofireImplementations.swift | 8 +- .../Classes/Swaggers/Models.swift | 4 + .../SwaggerClientTests/PetAPITests.swift | 14 ++- .../SwaggerClientTests/StoreAPITests.swift | 14 ++- .../SwaggerClientTests/UserAPITests.swift | 57 ++++++---- 22 files changed, 346 insertions(+), 308 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, - "lastName" : "aeiou", - "phone" : "aeiou", - "username" : "aeiou", - "email" : "aeiou", - "userStatus" : 123, + - examples: [{contentType=application/json, example={ "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}, {example= + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, + "phone" : "aeiou", + "id" : 123456789, + "email" : "aeiou", + "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, - "lastName" : "aeiou", - "phone" : "aeiou", - "username" : "aeiou", - "email" : "aeiou", - "userStatus" : 123, +}] + - examples: [{contentType=application/json, example={ "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}, {example= + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, + "phone" : "aeiou", + "id" : 123456789, + "email" : "aeiou", + "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, - "lastName" : "aeiou", - "phone" : "aeiou", - "username" : "aeiou", - "email" : "aeiou", - "userStatus" : 123, + - examples: [{contentType=application/json, example={ "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}, {example= + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, + "phone" : "aeiou", + "id" : 123456789, + "email" : "aeiou", + "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, - "lastName" : "aeiou", - "phone" : "aeiou", - "username" : "aeiou", - "email" : "aeiou", - "userStatus" : 123, +}] + - examples: [{contentType=application/json, example={ "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}, {example= + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, + "phone" : "aeiou", + "id" : 123456789, + "email" : "aeiou", + "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 128/210] 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 @@ public class InlineModelResolver { } } } + } 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 129/210] [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 130/210] [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 131/210] 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 beaf1fc7aa1c6f81dd47fa8a9b668b8ea1bb928b Mon Sep 17 00:00:00 2001 From: Tony Wang Date: Thu, 25 Aug 2016 19:34:12 +0800 Subject: [PATCH 132/210] 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 class SwiftCodegen extends DefaultCodegen implements CodegenConfig { 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 class ApiException extends Exception { 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 class HttpPatch extends HttpPost { 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 class Category { 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 class Order { 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 class Pet { 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 class Tag { 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 class User { 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 class Category { 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 class Order { 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 class Pet { 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 class Tag { 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 class User { 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 134/210] 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 135/210] 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 136/210] [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 class GoClientCodegen extends DefaultCodegen implements CodegenConfig { // 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 137/210] 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 class DefaultCodegen { } /** - * 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 class DefaultCodegen { } /** - * 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 class DefaultCodegen { * @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 class DefaultCodegen { * @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 class DefaultCodegen { */ 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 abstract class AbstractJavaCodegen extends DefaultCodegen implements Code @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 class GoClientCodegen extends DefaultCodegen implements CodegenConfig { } - // 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 class GoClientCodegen extends DefaultCodegen implements CodegenConfig { 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 class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig { 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 @@ public class TypescriptAngular2AdditionalPropertiesIntegrationTest extends Abstr @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 @@ public class TypescriptAngular2ArrayAndObjectTest extends AbstractIntegrationTes @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 @@ public class TypescriptNodeES5IntegrationTest extends AbstractIntegrationTest { @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 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 */ 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 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 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: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 @@ module Petstore # 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 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 * @return List */ @@ -218,7 +218,7 @@ public 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 * @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 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 * @return List */ @@ -392,7 +392,7 @@ public 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 void findPetsByStatus (List status, final Response.Listener> responseListener, final Response.ErrorListener errorListener) { @@ -454,7 +454,7 @@ public 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 * @return List */ @@ -519,7 +519,7 @@ public 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 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 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/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 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// 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 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// 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 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 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: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 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// 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 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// 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 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 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: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 @@ module Petstore # 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 @@ class App } /** - * 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 @@ import java.math.BigDecimal; 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 @@ import io.swagger.model.ModelApiResponse; 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 @@ import io.swagger.model.Order; 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 @@ import java.util.List; 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 class PetsApi { @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 class PetsApi { @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 @@ class App } /** - * 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 138/210] 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 139/210] 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 140/210] 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_query_string'} ) { - $form_params->{'enum_query_string'} = $self->{api_client}->to_form_value($args{'enum_query_string'}); + 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_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 141/210] 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 142/210] 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 @@ package io.swagger.codegen.languages; 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 class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod 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 143/210] 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 144/210] 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 145/210] 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 abstract class AbstractJavaCodegen extends DefaultCodegen implements Code 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 146/210] [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 class ApiInvoker { // 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 @@ 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/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 class PetApi { // 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 class PetApi { // 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 147/210] 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 148/210] 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 @@ 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 646c4faa62f6391070bfbdda68c14ae504c17f5a Mon Sep 17 00:00:00 2001 From: Zoltan Biro Date: Mon, 29 Aug 2016 16:53:38 +0200 Subject: [PATCH 149/210] 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 150/210] 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 151/210] 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 @@ class RESTClientObject(object): 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 @@ 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/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 @@ class Configuration(object): '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 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 @@ -42,13 +42,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__) @@ -120,7 +113,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() @@ -175,11 +168,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) From dd1ed1231884f08804fd5726ab5beabac59d7abd Mon Sep 17 00:00:00 2001 From: Daniel Ge Date: Mon, 29 Aug 2016 19:28:07 -0700 Subject: [PATCH 152/210] 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 @@ module Petstore 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 @@ module Petstore # 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 @@ module Petstore # 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore # 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 @@ module Petstore 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 153/210] 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 154/210] 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 @@ class FakeApi * * @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 @@ class FakeApi * @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 @@ class FakeApi * * @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 @@ class FakeApi * @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 @@ class FakeApi 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 @@ class FakeApi 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 @@ class FakeApi $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 @@ class FakeApi } 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 @@ class FakeApi } /** - * 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 @@ class FakeApi } $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 155/210] 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 156/210] 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 @@ class FakeApi extends Controller } $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 @@ class FakeApi extends Controller } $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 @@ class FakeApi extends Controller 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 @@ class FakeApi extends Controller //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 @@ class FakeApi extends Controller $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->PATCH('/v2/fake', 'FakeApi@testClientModel'); */ $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 157/210] 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 class PythonClientCodegen extends DefaultCodegen implements CodegenConfig + "/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 158/210] 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 159/210] 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 @@ class Configuration(object): :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 @@ class Configuration(object): '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 160/210] 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 161/210] 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 class CodegenConstants { 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 class DefaultGenerator extends AbstractGenerator implements Generator { 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 class PythonClientCodegen extends DefaultCodegen implements CodegenConfig .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 class PythonClientCodegen extends DefaultCodegen implements CodegenConfig 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 class PythonClientOptionsProvider implements OptionsProvider { 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 @@ class Configuration(object): :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 @@ class Configuration(object): '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 162/210] 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 class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { 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 class RubyClientOptionsProvider implements OptionsProvider { .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 @@ module Petstore # 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 @@ module Petstore 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 163/210] 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 class CSharpClientCodegen extends AbstractCSharpCodegen { 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 class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { 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 class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { 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 io.swagger.models.properties.*; 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 class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { // 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 class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { 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 class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { 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 class PythonClientCodegen extends DefaultCodegen implements CodegenConfig // 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 class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { // 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 class ObjcClientOptionsProvider implements OptionsProvider { .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 class PhpClientOptionsProvider implements OptionsProvider { .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 @@ class ObjectSerializer } 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 164/210] 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 | 40 +++---- 5 files changed, 113 insertions(+), 105 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 class SwiftCodegen extends DefaultCodegen implements CodegenConfig { 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 class SwiftOptionsProvider implements OptionsProvider { .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", - "lastName" : "aeiou", - "password" : "aeiou", - "userStatus" : 123, - "phone" : "aeiou", + - examples: [{example={ "id" : 123456789, + "lastName" : "aeiou", + "phone" : "aeiou", + "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", - "lastName" : "aeiou", - "password" : "aeiou", - "userStatus" : 123, - "phone" : "aeiou", +, contentType=application/xml}] + - examples: [{example={ "id" : 123456789, + "lastName" : "aeiou", + "phone" : "aeiou", + "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 165/210] 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 class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo 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 class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo 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 class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { // 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 class SwiftCodegen extends DefaultCodegen implements CodegenConfig { // 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 class JavaScriptOptionsProvider implements OptionsProvider { .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 166/210] 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 | 185 ++++++++---------- .../API/Client/StoreApi.js | 163 ++++++++------- .../API/Client/UserApi.js | 179 ++++++++--------- 10 files changed, 276 insertions(+), 290 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 class GoClientCodegen extends DefaultCodegen implements CodegenConfig { .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 class JavascriptClosureAngularClientCodegen extends DefaultCodegen implem 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 class GoClientOptionsProvider implements OptionsProvider { 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 class JavascriptClosureAnularClientOptionsProvider implements OptionsProv 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 */ /** @@ -45,45 +44,6 @@ API.Client.PetApi = function($http, $httpParamSerializer, $injector) { } API.Client.PetApi.$inject = ['$http', '$httpParamSerializer', '$injector']; -/** - * Update an existing 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.updatePet = function(body, opt_extraHttpRequestParams) { - /** @const {string} */ - var path = this.basePath_ + '/pet'; - - /** @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 updatePet'); - } - /** @type {!Object} */ - var httpRequestParams = { - method: 'PUT', - url: path, - json: true, - data: body, - - - params: queryParameters, - headers: headerParams - }; - - if (opt_extraHttpRequestParams) { - httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams); - } - - return (/** @type {?} */ (this.http_))(httpRequestParams); -} - /** * Add a new pet to the store * @@ -110,9 +70,47 @@ API.Client.PetApi.prototype.addPet = function(body, opt_extraHttpRequestParams) url: path, json: true, data: body, - - - params: queryParameters, + params: queryParameters, + headers: headerParams + }; + + if (opt_extraHttpRequestParams) { + httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams); + } + + return (/** @type {?} */ (this.http_))(httpRequestParams); +} + +/** + * Deletes a pet + * + * @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.deletePet = function(petId, opt_apiKey, opt_extraHttpRequestParams) { + /** @const {string} */ + 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 '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: 'DELETE', + url: path, + json: true, + 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,44 @@ API.Client.PetApi.prototype.getPetById = function(petId, opt_extraHttpRequestPar method: 'GET', url: path, json: true, - - - params: queryParameters, + params: queryParameters, + headers: headerParams + }; + + if (opt_extraHttpRequestParams) { + httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams); + } + + return (/** @type {?} */ (this.http_))(httpRequestParams); +} + +/** + * Update an existing 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.updatePet = function(body, opt_extraHttpRequestParams) { + /** @const {string} */ + var path = this.basePath_ + '/pet'; + + /** @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 updatePet'); + } + /** @type {!Object} */ + var httpRequestParams = { + method: 'PUT', + url: path, + json: true, + data: body, + params: queryParameters, headers: headerParams }; @@ -283,51 +312,7 @@ API.Client.PetApi.prototype.updatePetWithForm = function(petId, opt_name, opt_st method: 'POST', url: path, json: false, - - data: this.httpParamSerializer(formParams), - - params: queryParameters, - headers: headerParams - }; - - if (opt_extraHttpRequestParams) { - httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams); - } - - return (/** @type {?} */ (this.http_))(httpRequestParams); -} - -/** - * Deletes a pet - * - * @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.deletePet = function(petId, opt_apiKey, opt_extraHttpRequestParams) { - /** @const {string} */ - 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 '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: 'DELETE', - url: path, - json: true, - - + 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 */ /** @@ -44,6 +43,43 @@ API.Client.StoreApi = function($http, $httpParamSerializer, $injector) { } API.Client.StoreApi.$inject = ['$http', '$httpParamSerializer', '$injector']; +/** + * 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} + */ +API.Client.StoreApi.prototype.deleteOrder = function(orderId, opt_extraHttpRequestParams) { + /** @const {string} */ + 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: 'DELETE', + url: path, + json: true, + params: queryParameters, + headers: headerParams + }; + + if (opt_extraHttpRequestParams) { + httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams); + } + + return (/** @type {?} */ (this.http_))(httpRequestParams); +} + /** * Returns pet inventories by status * Returns a map of status codes to quantities @@ -64,9 +100,44 @@ API.Client.StoreApi.prototype.getInventory = function(opt_extraHttpRequestParams method: 'GET', url: path, json: true, - - - params: queryParameters, + params: queryParameters, + headers: headerParams + }; + + if (opt_extraHttpRequestParams) { + httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams); + } + + return (/** @type {?} */ (this.http_))(httpRequestParams); +} + +/** + * Find purchase order by ID + * 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} + */ +API.Client.StoreApi.prototype.getOrderById = function(orderId, opt_extraHttpRequestParams) { + /** @const {string} */ + 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 getOrderById'); + } + /** @type {!Object} */ + var httpRequestParams = { + method: 'GET', + url: path, + json: true, + params: queryParameters, headers: headerParams }; @@ -103,87 +174,7 @@ API.Client.StoreApi.prototype.placeOrder = function(body, opt_extraHttpRequestPa url: path, json: true, data: body, - - - params: queryParameters, - headers: headerParams - }; - - if (opt_extraHttpRequestParams) { - httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams); - } - - return (/** @type {?} */ (this.http_))(httpRequestParams); -} - -/** - * Find purchase order by ID - * 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} - */ -API.Client.StoreApi.prototype.getOrderById = function(orderId, opt_extraHttpRequestParams) { - /** @const {string} */ - 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 getOrderById'); - } - /** @type {!Object} */ - var httpRequestParams = { - method: 'GET', - url: path, - json: true, - - - params: queryParameters, - headers: headerParams - }; - - if (opt_extraHttpRequestParams) { - httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams); - } - - return (/** @type {?} */ (this.http_))(httpRequestParams); -} - -/** - * 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} - */ -API.Client.StoreApi.prototype.deleteOrder = function(orderId, opt_extraHttpRequestParams) { - /** @const {string} */ - 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: 'DELETE', - url: path, - json: true, - - - params: queryParameters, + 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,81 @@ API.Client.UserApi.prototype.createUsersWithListInput = function(body, opt_extra url: path, json: true, data: body, - - - params: queryParameters, + params: queryParameters, + headers: headerParams + }; + + if (opt_extraHttpRequestParams) { + httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams); + } + + return (/** @type {?} */ (this.http_))(httpRequestParams); +} + +/** + * 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} + */ +API.Client.UserApi.prototype.deleteUser = function(username, opt_extraHttpRequestParams) { + /** @const {string} */ + 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 deleteUser'); + } + /** @type {!Object} */ + var httpRequestParams = { + method: 'DELETE', + url: path, + json: true, + params: queryParameters, + headers: headerParams + }; + + if (opt_extraHttpRequestParams) { + httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams); + } + + return (/** @type {?} */ (this.http_))(httpRequestParams); +} + +/** + * 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} + */ +API.Client.UserApi.prototype.getUserByName = function(username, opt_extraHttpRequestParams) { + /** @const {string} */ + 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, headers: headerParams }; @@ -199,9 +266,7 @@ API.Client.UserApi.prototype.loginUser = function(username, password, opt_extraH method: 'GET', url: path, json: true, - - - params: queryParameters, + params: queryParameters, headers: headerParams }; @@ -232,48 +297,7 @@ API.Client.UserApi.prototype.logoutUser = function(opt_extraHttpRequestParams) { method: 'GET', url: path, json: true, - - - params: queryParameters, - headers: headerParams - }; - - if (opt_extraHttpRequestParams) { - httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams); - } - - return (/** @type {?} */ (this.http_))(httpRequestParams); -} - -/** - * 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} - */ -API.Client.UserApi.prototype.getUserByName = function(username, opt_extraHttpRequestParams) { - /** @const {string} */ - 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 }; @@ -316,48 +340,7 @@ API.Client.UserApi.prototype.updateUser = function(username, body, opt_extraHttp url: path, json: true, data: body, - - - params: queryParameters, - headers: headerParams - }; - - if (opt_extraHttpRequestParams) { - httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams); - } - - return (/** @type {?} */ (this.http_))(httpRequestParams); -} - -/** - * 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} - */ -API.Client.UserApi.prototype.deleteUser = function(username, opt_extraHttpRequestParams) { - /** @const {string} */ - 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 deleteUser'); - } - /** @type {!Object} */ - var httpRequestParams = { - method: 'DELETE', - url: path, - json: true, - - - params: queryParameters, + 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 167/210] 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 class CSharpClientCodegen extends AbstractCSharpCodegen { 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 class CSharpClientCodegen extends AbstractCSharpCodegen { @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 class CSharpClientOptionsProvider implements OptionsProvider { .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 @@ namespace IO.Swagger.Api /// 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 @@ namespace IO.Swagger.Api /// 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 @@ namespace IO.Swagger.Api /// 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 @@ namespace IO.Swagger.Api /// 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 @@ namespace IO.Swagger.Api /// 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 @@ namespace IO.Swagger.Api /// 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 @@ namespace IO.Swagger.Api // 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 @@ namespace IO.Swagger.Api 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 @@ namespace IO.Swagger.Api /// 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 @@ namespace IO.Swagger.Api /// 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 @@ namespace IO.Swagger.Api // 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 @@ namespace IO.Swagger.Api 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 @@ namespace IO.Swagger.Api } /// - /// 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 @@ namespace IO.Swagger.Api // 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 @@ namespace IO.Swagger.Api if (ExceptionFactory != null) { - Exception exception = ExceptionFactory("TestEnumQueryParameters", localVarResponse); + Exception exception = ExceptionFactory("TestEnumParameters", localVarResponse); if (exception != null) throw exception; } @@ -788,28 +846,38 @@ namespace IO.Swagger.Api } /// - /// 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 @@ namespace IO.Swagger.Api // 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 @@ namespace IO.Swagger.Api 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 @@ using Newtonsoft.Json.Converters; 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 168/210] 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 169/210] 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 @@ 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/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 @@ class FakeApi(object): 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 @@ class FakeApi(object): 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 @@ class PetApi(object): 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 @@ class PetApi(object): 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 170/210] 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 171/210] 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 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"; @@ -136,6 +137,44 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig 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 class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig 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 class ScalaClientOptionsProvider implements OptionsProvider { .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 @@ public class ScalaClientOptionsTest extends AbstractOptionsTest { 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 172/210] 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 class 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 @@ class AdditionalPropertiesClass implements ArrayAccess /** * 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 @@ class Animal implements ArrayAccess /** * 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 @@ class AnimalFarm implements ArrayAccess /** * 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 @@ class ApiResponse implements ArrayAccess /** * 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 @@ class ArrayOfArrayOfNumberOnly implements ArrayAccess /** * 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 @@ class ArrayOfNumberOnly implements ArrayAccess /** * 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 @@ class ArrayTest implements ArrayAccess /** * 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 @@ class Cat extends Animal implements ArrayAccess /** * 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 @@ class Category implements ArrayAccess /** * 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 @@ class Client implements ArrayAccess /** * 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 @@ class Dog extends Animal implements ArrayAccess /** * 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 @@ class EnumArrays implements ArrayAccess /** * 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 @@ class EnumTest implements ArrayAccess /** * 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 @@ class FormatTest implements ArrayAccess /** * 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 @@ class HasOnlyReadOnly implements ArrayAccess /** * 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 @@ class MapTest implements ArrayAccess /** * 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 @@ class MixedPropertiesAndAdditionalPropertiesClass implements ArrayAccess /** * 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 @@ class Model200Response implements ArrayAccess /** * 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 @@ class ModelList implements ArrayAccess /** * 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 @@ class ModelReturn implements ArrayAccess /** * 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 @@ class Name implements ArrayAccess /** * 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 @@ class NumberOnly implements ArrayAccess /** * 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 @@ class Order implements ArrayAccess /** * 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 @@ class Pet implements ArrayAccess /** * 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 @@ class ReadOnlyFirst implements ArrayAccess /** * 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 @@ class SpecialModelName implements ArrayAccess /** * 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 @@ class Tag implements ArrayAccess /** * 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 @@ class User implements ArrayAccess /** * 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 173/210] 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 @@ 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/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 @@ class DateAdapter implements JsonSerializer, JsonDeserializer { * @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 class ApiClient { 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.ApiClient; 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 @@ package io.swagger.client.api; 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 class Model200Response { 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 class Model200Response { } 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 class Model200Response { 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 class 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.Pair; 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 class FakeApi { * 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 class FakeApi { 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 @@ if (_double != null) 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 @@ if (password != null) }; 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 @@ if (password != null) 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.model.*; 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 class Model200Response { 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 class Model200Response { } 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 class Model200Response { 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 class 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 io.swagger.client.Pair; 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 class FakeApi { * 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 class FakeApi { 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 @@ if (_double != null) 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 @@ if (password != null) }; 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 @@ if (password != null) 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 io.swagger.client.Pair; 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 class Model200Response { 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 class Model200Response { } 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 class Model200Response { 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 class 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 javax.ws.rs.core.GenericType; 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 class FakeApi { * 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 class FakeApi { 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 @@ if (_double != null) 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 @@ if (password != null) }; 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 @@ if (password != null) 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 io.swagger.client.Pair; 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 class Model200Response { 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 class Model200Response { } 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 class Model200Response { 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 class 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 @@ 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/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 @@ 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/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 java.io.IOException; 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 class FakeApi { 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 @@ public class FakeApi { 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 @@ public class FakeApi { 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 class FakeApi { }); } - 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 class FakeApi { * 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 class FakeApi { * 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 class FakeApi { * @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 class FakeApi { * 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 class FakeApi { * @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 class FakeApi { }; } - 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 @@ public class FakeApi { 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 class FakeApi { } /** - * 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 class FakeApi { * @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 class FakeApi { }; } - 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 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.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 class Model200Response { 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 class Model200Response { } 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 class Model200Response { 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 class ApiClient { 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 retrofit.mime.*; 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 @@ public interface FakeApi { * 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 @@ public interface FakeApi { @FormUrlEncoded @POST("/fake") Void testEndpointParameters( - @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") 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 @@ public interface FakeApi { * 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 @@ public interface FakeApi { @FormUrlEncoded @POST("/fake") void testEndpointParameters( - @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") 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 @@ public interface FakeApi { @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 @@ public interface FakeApi { @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.http.*; import retrofit.mime.*; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.util.ArrayList; import java.util.HashMap; diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthFlow.java index 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 class Model200Response { 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 class Model200Response { } 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 class Model200Response { 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 class ApiClient { 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 okhttp3.RequestBody; 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 @@ public interface FakeApi { * 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 @@ public interface FakeApi { @FormUrlEncoded @POST("fake") Call testEndpointParameters( - @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") 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 @@ public interface FakeApi { @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 retrofit2.http.*; 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 class Model200Response { 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 class Model200Response { } 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 class Model200Response { 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 class ApiClient { 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 okhttp3.RequestBody; 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 @@ public interface FakeApi { * 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 @@ public interface FakeApi { @FormUrlEncoded @POST("fake") Observable testEndpointParameters( - @Field("number") BigDecimal number, @Field("double") Double _double, @Field("string") String string, @Field("byte") byte[] _byte, @Field("integer") Integer integer, @Field("int32") Integer int32, @Field("int64") Long int64, @Field("float") Float _float, @Field("binary") byte[] binary, @Field("date") 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 @@ public interface FakeApi { @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 retrofit2.http.*; 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 class Model200Response { 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 class Model200Response { } 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 class Model200Response { 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 174/210] [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.CliOption; 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 class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf 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 175/210] 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 @@ module Petstore # 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 @@ module Petstore 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 176/210] 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 @@ class FakeApi 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 @@ class FakeApi } 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 @@ class FormatTest implements ArrayAccess { 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 177/210] 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 @@ 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/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 @@ class FakeApi(object): 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 @@ class FakeApi(object): 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 @@ class FakeApi(object): 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 @@ class FakeApi(object): 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 @@ class FakeApi(object): 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 @@ class FakeApi(object): 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 @@ class FakeApi(object): 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 @@ class FakeApi(object): 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 @@ class PetApi(object): 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 @@ class PetApi(object): 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 @@ class PetApi(object): if ('pet_id' not in params) or (params['pet_id'] is None): raise ValueError("Missing the required parameter `pet_id` when calling `delete_pet`") + + collection_formats = {} + resource_path = '/pet/{petId}'.replace('{format}', 'json') path_params = {} if 'pet_id' in params: @@ -261,7 +268,8 @@ class PetApi(object): 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 @@ class PetApi(object): if ('status' not in params) or (params['status'] is None): raise ValueError("Missing the required parameter `status` when calling `find_pets_by_status`") + + 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 @@ class PetApi(object): 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 @@ class PetApi(object): if ('tags' not in params) or (params['tags'] is None): raise ValueError("Missing the required parameter `tags` when calling `find_pets_by_tags`") + + 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 @@ class PetApi(object): 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 @@ class PetApi(object): if ('pet_id' not in params) or (params['pet_id'] is None): raise ValueError("Missing the required parameter `pet_id` when calling `get_pet_by_id`") + + collection_formats = {} + resource_path = '/pet/{petId}'.replace('{format}', 'json') path_params = {} if 'pet_id' in params: @@ -573,7 +594,8 @@ class PetApi(object): 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 @@ class PetApi(object): 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 @@ class PetApi(object): 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 @@ class PetApi(object): if ('pet_id' not in params) or (params['pet_id'] is None): raise ValueError("Missing the required parameter `pet_id` when calling `update_pet_with_form`") + + collection_formats = {} + resource_path = '/pet/{petId}'.replace('{format}', 'json') path_params = {} if 'pet_id' in params: @@ -760,9 +789,9 @@ class PetApi(object): 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 @@ class PetApi(object): 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 @@ class PetApi(object): if ('pet_id' not in params) or (params['pet_id'] is None): raise ValueError("Missing the required parameter `pet_id` when calling `upload_file`") + + collection_formats = {} + resource_path = '/pet/{petId}/uploadImage'.replace('{format}', 'json') path_params = {} if 'pet_id' in params: @@ -872,7 +905,7 @@ class PetApi(object): 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 @@ class PetApi(object): 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 @@ class StoreApi(object): 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 @@ class StoreApi(object): 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 @@ class StoreApi(object): params[key] = val del params['kwargs'] + + collection_formats = {} + resource_path = '/store/inventory'.replace('{format}', 'json') path_params = {} @@ -252,7 +259,8 @@ class StoreApi(object): 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 @@ class StoreApi(object): 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 @@ class StoreApi(object): 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 @@ class StoreApi(object): 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 @@ class StoreApi(object): 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 @@ class UserApi(object): 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 @@ class UserApi(object): 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 @@ class UserApi(object): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `create_users_with_array_input`") + + collection_formats = {} + resource_path = '/user/createWithArray'.replace('{format}', 'json') path_params = {} @@ -257,7 +264,8 @@ class UserApi(object): 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 @@ class UserApi(object): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `create_users_with_list_input`") + + collection_formats = {} + resource_path = '/user/createWithList'.replace('{format}', 'json') path_params = {} @@ -361,7 +372,8 @@ class UserApi(object): 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 @@ class UserApi(object): 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 @@ class UserApi(object): 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 @@ class UserApi(object): if ('username' not in params) or (params['username'] is None): raise ValueError("Missing the required parameter `username` when calling `get_user_by_name`") + + collection_formats = {} + resource_path = '/user/{username}'.replace('{format}', 'json') path_params = {} if 'username' in params: @@ -569,7 +588,8 @@ class UserApi(object): 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 @@ class UserApi(object): 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 @@ class UserApi(object): 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 @@ class UserApi(object): params[key] = val del params['kwargs'] + + collection_formats = {} + resource_path = '/user/logout'.replace('{format}', 'json') path_params = {} @@ -777,7 +804,8 @@ class UserApi(object): 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 @@ class UserApi(object): 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 @@ class UserApi(object): 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 1539986984a78e083864c0fa5ee59b2af0d7d304 Mon Sep 17 00:00:00 2001 From: Kim Sondrup Date: Sat, 3 Sep 2016 10:06:07 +0200 Subject: [PATCH 178/210] [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 @@ class FakeApi * 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 @@ class FakeApi * @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 @@ class FakeApi * @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 @@ class PetApi * 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 @@ class PetApi * * @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 @@ class PetApi * 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 @@ class PetApi * 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 @@ class PetApi * 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 @@ class PetApi * 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 @@ class PetApi * @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 @@ class PetApi * @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 @@ class StoreApi * 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 @@ class StoreApi * * 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 @@ class StoreApi * 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 @@ class StoreApi * 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 @@ class UserApi * 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 @@ class UserApi * 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 @@ class UserApi * 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 @@ class UserApi * 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 @@ class UserApi * 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 @@ class UserApi * * @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 @@ class UserApi * * 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 @@ class UserApi * * @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 @@ 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) { @@ -345,7 +345,7 @@ class Configuration * * @param string $userAgent the user agent of the api client * - * @return ApiClient + * @return Configuration */ public function setUserAgent($userAgent) { @@ -372,7 +372,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/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 @@ 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 */ @@ -153,7 +153,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 */ @@ -171,7 +171,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 */ @@ -187,9 +187,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 */ @@ -220,12 +221,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) { From 92aa8ed767f8d442b7ccafdd6e884e3f8072f16a Mon Sep 17 00:00:00 2001 From: Masahiro Saito Date: Mon, 5 Sep 2016 16:37:54 +0900 Subject: [PATCH 179/210] [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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ describe 'BaseObject' do 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 180/210] 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 @@ module Petstore 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 181/210] 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 182/210] 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' + ]; - 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 (additionalMetadata !== undefined) { + formParams.set('additionalMetadata', additionalMetadata); + } + if (file !== undefined) { + formParams.set('file', file); + } + + 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' + ]; - 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 (additionalMetadata !== undefined) { + formParams.set('additionalMetadata', additionalMetadata); + } + if (file !== undefined) { + formParams.set('file', file); + } + + 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 183/210] [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 class DefaultCodegen { 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 class DefaultCodegen { 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 @@ class FakeApi(object): 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 @@ class StoreApi(object): 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 184/210] 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 | 426 ++++++++++++------ .../io/swagger/client/api/StoreApiTest.java | 179 ++++---- .../io/swagger/client/api/UserApiTest.java | 212 +++------ .../swagger/client/auth/ApiKeyAuthTest.java | 47 ++ .../client/auth/HttpBasicAuthTest.java | 52 +++ 12 files changed, 939 insertions(+), 438 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 class FakeApiTest { 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 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 com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.datatype.joda.*; +import io.swagger.TestUtils; + +import io.swagger.client.*; +import io.swagger.client.api.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; import java.util.ArrayList; -import java.util.HashMap; +import java.util.Arrays; import java.util.List; import java.util.Map; -/** - * API tests for PetApi - */ +import org.junit.*; +import static org.junit.Assert.*; + public class PetApiTest { + private PetApi api; + private ObjectMapper mapper; - private final PetApi api = new PetApi(); - - - /** - * Add a new pet to the store - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void addPetTest() throws ApiException { - Pet body = null; - // api.addPet(body); - - // TODO: test validations + @Before + public void setup() { + api = new PetApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); } - - /** - * Deletes a pet - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void deletePetTest() throws ApiException { - Long petId = null; - String apiKey = null; - // api.deletePet(petId, apiKey); - // TODO: test validations - } - - /** - * Finds Pets by status - * - * Multiple status values can be provided with comma separated strings - * - * @throws ApiException - * if the Api call fails - */ @Test - public void findPetsByStatusTest() throws ApiException { - List status = null; - // List response = api.findPetsByStatus(status); + public void testApiClient() { + // the default api client is used + assertEquals(Configuration.getDefaultApiClient(), api.getApiClient()); + assertNotNull(api.getApiClient()); + assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); + assertFalse(api.getApiClient().isDebugging()); - // TODO: test validations + ApiClient oldClient = api.getApiClient(); + + ApiClient newClient = new ApiClient(); + newClient.setBasePath("http://example.com"); + newClient.setDebugging(true); + + // set api client via constructor + api = new PetApi(newClient); + assertNotNull(api.getApiClient()); + assertEquals("http://example.com", api.getApiClient().getBasePath()); + assertTrue(api.getApiClient().isDebugging()); + + // set api client via setter method + api.setApiClient(oldClient); + assertNotNull(api.getApiClient()); + assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); + assertFalse(api.getApiClient().isDebugging()); } - - /** - * Finds Pets by tags - * - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void findPetsByTagsTest() throws ApiException { - List tags = null; - // List response = api.findPetsByTags(tags); + public void testCreateAndGetPet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); - // TODO: test validations + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); } - - /** - * Find pet by ID - * - * Returns a single pet - * - * @throws ApiException - * if the Api call fails - */ + + /* @Test - public void getPetByIdTest() throws ApiException { - Long petId = null; - // Pet response = api.getPetById(petId); + public void testCreateAndGetPetWithByteArray() throws Exception { + Pet pet = createRandomPet(); + byte[] bytes = serializeJson(pet).getBytes(); + api.addPetUsingByteArray(bytes); - // TODO: test validations + byte[] fetchedBytes = api.petPetIdtestingByteArraytrueGet(pet.getId()); + Pet fetched = deserializeJson(new String(fetchedBytes), Pet.class); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); } - - /** - * Update an existing pet - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void updatePetTest() throws ApiException { - Pet body = null; - // api.updatePet(body); + public void testGetPetByIdInObject() throws Exception { + Pet pet = new Pet(); + pet.setId(TestUtils.nextId()); + pet.setName("pet " + pet.getId()); - // TODO: test validations + Category category = new Category(); + category.setId(TestUtils.nextId()); + category.setName("category " + category.getId()); + pet.setCategory(category); + + pet.setStatus(Pet.StatusEnum.PENDING); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1"}); + pet.setPhotoUrls(photos); + + api.addPet(pet); + + InlineResponse200 fetched = api.getPetByIdInObject(pet.getId()); + assertEquals(pet.getId(), fetched.getId()); + assertEquals(pet.getName(), fetched.getName()); + + Object categoryObj = fetched.getCategory(); + assertNotNull(categoryObj); + assertTrue(categoryObj instanceof Map); + + Map categoryMap = (Map) categoryObj; + Object categoryIdObj = categoryMap.get("id"); + assertTrue(categoryIdObj instanceof Integer); + Integer categoryIdInt = (Integer) categoryIdObj; + assertEquals(category.getId(), Long.valueOf(categoryIdInt)); + assertEquals(category.getName(), categoryMap.get("name")); } - - /** - * Updates a pet in the store with form data - * - * - * - * @throws ApiException - * if the Api call fails - */ + */ + @Test - public void updatePetWithFormTest() throws ApiException { - Long petId = null; - String name = null; - String status = null; - // api.updatePetWithForm(petId, name, status); + public void testUpdatePet() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); - // TODO: test validations + api.updatePet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); } - - /** - * uploads an image - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void uploadFileTest() throws ApiException { - Long petId = null; - String additionalMetadata = null; - File file = null; - // ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); + public void testFindPetsByStatus() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); - // TODO: test validations + api.updatePet(pet); + + List pets = api.findPetsByStatus(Arrays.asList(new String[]{"available"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + assertTrue(found); + } + + @Test + public void testFindPetsByTags() throws Exception { + Pet pet = createRandomPet(); + pet.setName("monster"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + List tags = new ArrayList(); + Tag tag1 = new Tag(); + tag1.setName("friendly"); + tags.add(tag1); + pet.setTags(tags); + + api.updatePet(pet); + + List pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + assertTrue(found); + } + + @Test + public void testUpdatePetWithForm() throws Exception { + Pet pet = createRandomPet(); + pet.setName("frank"); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + + api.updatePetWithForm(fetched.getId(), "furt", null); + Pet updated = api.getPetById(fetched.getId()); + + assertEquals(updated.getName(), "furt"); + } + + @Test + public void testDeletePet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + api.deletePet(fetched.getId(), null); + + try { + fetched = api.getPetById(fetched.getId()); + fail("expected an error"); + } catch (ApiException e) { + assertEquals(404, e.getCode()); + } + } + + @Test + public void testUploadFile() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + File file = new File("hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.write("Hello world!"); + writer.close(); + + api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); + } + + @Test + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + + pet2.setName("really-happy"); + pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } + + private Pet createRandomPet() { + Pet pet = new Pet(); + pet.setId(TestUtils.nextId()); + pet.setName("gorilla"); + + Category category = new Category(); + category.setName("really-happy"); + + pet.setCategory(category); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); + pet.setPhotoUrls(photos); + + return pet; + } + + private String serializeJson(Object o) { + if (mapper == null) { + mapper = createObjectMapper(); + } + try { + return mapper.writeValueAsString(o); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private T deserializeJson(String json, Class klass) { + if (mapper == null) { + mapper = createObjectMapper(); + } + try { + return mapper.readValue(json, klass); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private ObjectMapper createObjectMapper() { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + mapper.registerModule(new JodaModule()); + return mapper; } - } diff --git a/samples/client/petstore/java/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); - - // TODO: test validations + @Before + public void setup() { + api = new StoreApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + // set custom date format that is used by the petstore server + api.getApiClient().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")); } - - /** - * Returns pet inventories by status - * - * Returns a map of status codes to quantities - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void getInventoryTest() throws ApiException { - // Map response = api.getInventory(); - // TODO: test validations - } - - /** - * Find purchase order by ID - * - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * - * @throws ApiException - * if the Api call fails - */ @Test - public void getOrderByIdTest() throws ApiException { - Long orderId = null; - // Order response = api.getOrderById(orderId); - - // TODO: test validations + public void testGetInventory() throws Exception { + Map inventory = api.getInventory(); + assertTrue(inventory.keySet().size() > 0); } - - /** - * Place an order for a pet - * - * - * - * @throws ApiException - * if the Api call fails - */ + + /* @Test - public void placeOrderTest() throws ApiException { - Order body = null; - // Order response = api.placeOrder(body); + public void testGetInventoryInObject() throws Exception { + Object inventoryObj = api.getInventoryInObject(); + assertTrue(inventoryObj instanceof Map); - // TODO: test validations + Map inventoryMap = (Map) inventoryObj; + assertTrue(inventoryMap.keySet().size() > 0); + + Map.Entry firstEntry = (Map.Entry) inventoryMap.entrySet().iterator().next(); + assertTrue(firstEntry.getKey() instanceof String); + assertTrue(firstEntry.getValue() instanceof Integer); + } + */ + + @Test + public void testPlaceOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(order.getId()); + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + assertEquals(order.getShipDate().withZone(DateTimeZone.UTC), fetched.getShipDate().withZone(DateTimeZone.UTC)); + } + + @Test + public void testDeleteOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(order.getId()); + assertEquals(fetched.getId(), order.getId()); + + api.deleteOrder(String.valueOf(order.getId())); + + try { + api.getOrderById(order.getId()); + // fail("expected an error"); + } catch (ApiException e) { + // ok + } + } + + private Order createOrder() { + Order order = new Order(); + order.setPetId(new Long(200)); + order.setQuantity(new Integer(13)); + order.setShipDate(DateTime.now()); + order.setStatus(Order.StatusEnum.PLACED); + order.setComplete(true); + + try { + Field idField = Order.class.getDeclaredField("id"); + idField.setAccessible(true); + idField.set(order, TestUtils.nextId()); + } catch (Exception e) { + throw new RuntimeException(e); + } + + return order; } - } diff --git a/samples/client/petstore/java/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.client.ApiException; -import io.swagger.client.model.User; -import org.junit.Test; +import io.swagger.TestUtils; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import io.swagger.client.api.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.util.Arrays; + +import org.junit.*; +import static org.junit.Assert.*; -/** - * API tests for UserApi - */ public class UserApiTest { + UserApi api = null; - private final UserApi api = new UserApi(); - - - /** - * Create user - * - * This can only be done by the logged in user. - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void createUserTest() throws ApiException { - User body = null; - // api.createUser(body); - - // TODO: test validations + @Before + public void setup() { + api = new UserApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); } - - /** - * Creates list of users with given input array - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void createUsersWithArrayInputTest() throws ApiException { - List body = null; - // api.createUsersWithArrayInput(body); - // TODO: test validations - } - - /** - * Creates list of users with given input array - * - * - * - * @throws ApiException - * if the Api call fails - */ @Test - public void createUsersWithListInputTest() throws ApiException { - List body = null; - // api.createUsersWithListInput(body); + public void testCreateUser() throws Exception { + User user = createUser(); - // TODO: test validations + api.createUser(user); + + User fetched = api.getUserByName(user.getUsername()); + assertEquals(user.getId(), fetched.getId()); } - - /** - * Delete user - * - * This can only be done by the logged in user. - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void deleteUserTest() throws ApiException { - String username = null; - // api.deleteUser(username); + public void testCreateUsersWithArray() throws Exception { + User user1 = createUser(); + user1.setUsername("user" + user1.getId()); + User user2 = createUser(); + user2.setUsername("user" + user2.getId()); - // TODO: test validations + api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); } - - /** - * Get user by user name - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void getUserByNameTest() throws ApiException { - String username = null; - // User response = api.getUserByName(username); + public void testCreateUsersWithList() throws Exception { + User user1 = createUser(); + user1.setUsername("user" + user1.getId()); + User user2 = createUser(); + user2.setUsername("user" + user2.getId()); - // TODO: test validations + api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); } - - /** - * Logs user into the system - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void loginUserTest() throws ApiException { - String username = null; - String password = null; - // String response = api.loginUser(username, password); + public void testLoginUser() throws Exception { + User user = createUser(); + api.createUser(user); - // TODO: test validations + String token = api.loginUser(user.getUsername(), user.getPassword()); + assertTrue(token.startsWith("logged in user session:")); } - - /** - * Logs out current logged in user session - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void logoutUserTest() throws ApiException { - // api.logoutUser(); - - // TODO: test validations + public void logoutUser() throws Exception { + api.logoutUser(); } - - /** - * Updated user - * - * This can only be done by the logged in user. - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void updateUserTest() throws ApiException { - String username = null; - User body = null; - // api.updateUser(username, body); - // TODO: test validations + private User createUser() { + User user = new User(); + user.setId(TestUtils.nextId()); + user.setUsername("fred" + user.getId()); + user.setFirstName("Fred"); + user.setLastName("Meyer"); + user.setEmail("fred@fredmeyer.com"); + user.setPassword("xxXXxx"); + user.setPhone("408-867-5309"); + user.setUserStatus(123); + + return user; } - } diff --git a/samples/client/petstore/java/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 185/210] 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 @@ use \Swagger\Client\ObjectSerializer; * @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 @@ namespace Swagger\Client; * @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 @@ use \Exception; * @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 @@ namespace Swagger\Client; * @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 @@ use \ArrayAccess; /** * @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 @@ namespace Swagger\Client; * @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 @@ use \Swagger\Client\ObjectSerializer; * @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 @@ namespace Swagger\Client; /** * @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 @@ use \Swagger\Client\ObjectSerializer; * @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 @@ use \Swagger\Client\ObjectSerializer; * @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 @@ use \Swagger\Client\ObjectSerializer; * @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 @@ use \Swagger\Client\ObjectSerializer; * @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 @@ namespace Swagger\Client; * @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 @@ use \Exception; * @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 @@ namespace Swagger\Client; * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ use \ArrayAccess; /** * @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 @@ namespace Swagger\Client; * @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 @@ use \Swagger\Client\ObjectSerializer; * @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 @@ use \Swagger\Client\ObjectSerializer; * @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 @@ use \Swagger\Client\ObjectSerializer; * @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 @@ use \Swagger\Client\ObjectSerializer; * @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 @@ use \Swagger\Client\ObjectSerializer; * @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 @@ use \Swagger\Client\ObjectSerializer; * @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 @@ namespace Swagger\Client\Model; * @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 @@ namespace Swagger\Client; * @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 @@ namespace Swagger\Client\Model; * @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 @@ namespace Swagger\Client\Model; * @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 @@ namespace Swagger\Client\Model; * @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 @@ namespace Swagger\Client\Model; * @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 @@ namespace Swagger\Client\Model; * @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 @@ namespace Swagger\Client\Model; * @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 @@ namespace Swagger\Client\Model; * @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 @@ namespace Swagger\Client; /** * @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 @@ namespace Swagger\Client\Model; * @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 @@ namespace Swagger\Client; /** * @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 @@ namespace Swagger\Client\Model; * @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 @@ namespace Swagger\Client\Model; * @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 @@ namespace Swagger\Client\Model; * @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 @@ namespace Swagger\Client\Model; * @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 @@ namespace Swagger\Client\Model; * @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 @@ namespace Swagger\Client\Model; * @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 @@ namespace Swagger\Client\Model; * @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 @@ namespace Swagger\Client; /** * @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 @@ namespace Swagger\Client\Model; * @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 @@ namespace Swagger\Client\Model; * @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 @@ namespace Swagger\Client\Model; * @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 @@ namespace Swagger\Client\Model; * @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 @@ namespace Swagger\Client; * @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 @@ namespace Swagger\Client\Model; * @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 @@ namespace Swagger\Client\Model; * @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 @@ namespace Swagger\Client\Model; * @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 @@ namespace Swagger\Client\Model; * @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 186/210] 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 @@ class FormatTest(object): 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 187/210] [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 class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { 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 class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { 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 class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { 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 class RubyClientOptionsProvider implements OptionsProvider { .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 @@ public class RubyClientOptionsTest extends AbstractOptionsTest { 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 188/210] 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 class ConfigParser { 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 @@ package io.swagger.codegen; 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 class Codegen extends DefaultGenerator { 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 final class CodegenModelFactory { 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 class CodegenOperation { @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 class CodegenResponse { 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 class CodegenResponse { @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 class DefaultCodegen { 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 class DefaultCodegen { 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 class DefaultCodegen { 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 class DefaultCodegen { 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 class DefaultCodegen { } 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 @@ public class DefaultCodegen { // 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 @@ public class DefaultCodegen { 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 @@ public class DefaultCodegen { 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 class DefaultGenerator extends AbstractGenerator implements Generator { // 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.IOException; 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 class MetaGenerator extends AbstractGenerator { 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 class CodegenConfigurator { 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 @@ public class CodegenConfigurator { 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 @@ public class ExampleGenerator { } 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 @@ public abstract class Rule { 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 abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co 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 abstract class AbstractJavaCodegen extends DefaultCodegen implements Code 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 abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg 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 abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg // 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 class CSharpClientCodegen extends AbstractCSharpCodegen { 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 class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf 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 class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf "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 class GoClientCodegen extends DefaultCodegen implements CodegenConfig { 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 class GoClientCodegen extends DefaultCodegen implements CodegenConfig { @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 class GoServerCodegen extends DefaultCodegen implements CodegenConfig { // 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 class GoServerCodegen extends DefaultCodegen implements CodegenConfig { */ 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 class GoServerCodegen extends DefaultCodegen implements CodegenConfig { "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 class GoServerCodegen extends DefaultCodegen implements CodegenConfig { 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 class JMeterCodegen extends DefaultCodegen implements CodegenConfig { // 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 class JMeterCodegen extends DefaultCodegen implements CodegenConfig { 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 class JMeterCodegen extends DefaultCodegen implements CodegenConfig { "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.Operation; 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 class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen 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 class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo 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 class LumenServerCodegen extends AbstractPhpCodegen 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 class LumenServerCodegen extends AbstractPhpCodegen 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 class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig // 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 class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig */ 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 class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig "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 class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig "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 class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { 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 class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { } // 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 class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { 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 class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { 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 class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { 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 class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { 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 class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { 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 class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { 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 class PythonClientCodegen extends DefaultCodegen implements CodegenConfig 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 class PythonClientCodegen extends DefaultCodegen implements CodegenConfig 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 class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig { // 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 class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig { "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 class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig { "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 class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig { "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 class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { 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 class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { 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 class SpringCodegen extends AbstractJavaCodegen { } 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 class SwiftCodegen extends DefaultCodegen implements CodegenConfig { 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 class SwiftCodegen extends DefaultCodegen implements CodegenConfig { // 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 class AssertFile { 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 189/210] 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 class Category { @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 class Order { @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 class Pet { @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 class Tag { @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 class User { @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 class ApiInvoker { // 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 class PetApi { // 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 class PetApi { // 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 class Category { @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 class Order { @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 class Pet { @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 class Tag { @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 class User { @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 190/210] 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 class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen 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 enum StatusEnum { } } + @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 enum StatusEnum { } } + @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 191/210] [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 @@ class FormatTest implements ArrayAccess 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 @@ class FormatTest implements ArrayAccess 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 @@ class FormatTest implements ArrayAccess 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 @@ class FormatTest implements ArrayAccess 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 @@ class FormatTest implements ArrayAccess 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 @@ class FormatTest implements ArrayAccess 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 @@ class FormatTest implements ArrayAccess 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 192/210] 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 193/210] 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 194/210] [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 195/210] 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 196/210] 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 197/210] 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 class ErlangServerCodegen extends DefaultCodegen implements CodegenConfig */ @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 @@ public class ErlangServerCodegen extends DefaultCodegen implements CodegenConfig 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 198/210] 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 199/210] 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 f9d1f2472609e0f16bb8e0d6d45d31fb88031b95 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 11 Sep 2016 14:52:46 +0800 Subject: [PATCH 200/210] 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 201/210] 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.CodegenProperty; 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.Iterator; 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 class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon embeddedTemplateDir = templateDir = "akka-scala"; apiPackage = mainPackage + ".api"; modelPackage = mainPackage + ".model"; + invokerPackage = mainPackage + ".core"; setReservedWordsLowerCase( Arrays.asList( @@ -135,25 +133,8 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon 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 class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon 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 class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon 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 class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon 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 class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon // 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.CliOption; 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 class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenCo 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 class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenCo 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.CliOption; 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 class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig 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 class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig 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 class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig 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 class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig 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.CliOption; 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 class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf 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 class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf 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 class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf 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 class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf } - @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 ac69f45ddc18dacd1b3972495c3613cdc47559e6 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 11 Sep 2016 18:44:36 +0800 Subject: [PATCH 202/210] 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 203/210] 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 204/210] 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 abstract class AbstractScalaCodegen extends DefaultCodegen { 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 @@ public class AkkaScalaClientOptionsTest extends AbstractOptionsTest { 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 @@ public class AsyncScalaClientOptionsTest extends AbstractOptionsTest { 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 com.google.common.collect.ImmutableMap; 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 class AkkaScalaClientOptionsProvider implements OptionsProvider { .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 com.google.common.collect.ImmutableMap; 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 class AsyncScalaClientOptionsProvider implements OptionsProvider { .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 com.google.common.collect.ImmutableMap; 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 class ScalaClientOptionsProvider implements OptionsProvider { .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 com.google.common.collect.ImmutableMap; 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 class ScalatraServerOptionsProvider implements OptionsProvider { .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 @@ public class ScalaClientOptionsTest extends AbstractOptionsTest { 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 @@ public class ScalatraServerOptionsTest extends AbstractOptionsTest { times = 1; clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(ScalatraServerOptionsProvider.SORT_PARAMS_VALUE)); times = 1; + clientCodegen.setSourceFolder(ScalatraServerOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; }}; } } 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 205/210] 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.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(); 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.List; 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