diff --git a/README.md b/README.md index 7b130b4b8ab7..a13c194837a1 100644 --- a/README.md +++ b/README.md @@ -64,8 +64,8 @@ The Swagger Specification has undergone 3 revisions since initial creation in 20 Swagger Codegen Version | Release Date | Swagger Spec compatibility | Notes -------------------------- | ------------ | -------------------------- | ----- -2.1.4-SNAPSHOT | | 1.0, 1.1, 1.2, 2.0 | [master](https://github.com/swagger-api/swagger-codegen) -2.1.3 (**current stable**) | 2015-08-24 | 1.0, 1.1, 1.2, 2.0 | [tag v2.1.3](https://github.com/swagger-api/swagger-codegen/tree/v2.1.3) +2.1.5-SNAPSHOT | | 1.0, 1.1, 1.2, 2.0 | [master](https://github.com/swagger-api/swagger-codegen) +2.1.4 (**current stable**) | 2015-10-25 | 1.0, 1.1, 1.2, 2.0 | [tag v2.1.4](https://github.com/swagger-api/swagger-codegen/tree/v2.1.4) 2.0.17 | 2014-08-22 | 1.1, 1.2 | [tag v2.0.17](https://github.com/swagger-api/swagger-codegen/tree/v2.0.17) 1.0.4 | 2012-04-12 | 1.0, 1.1 | [tag v1.0.4](https://github.com/swagger-api/swagger-codegen/tree/swagger-codegen_2.9.1-1.1) @@ -212,6 +212,36 @@ to the code generator like this: Great for creating libraries on your ci server, from the [Swagger Editor](http://editor.swagger.io)... or while coding on an airplane. +### Selective generation +You may not want to generate *all* models in your project. Likewise you may want just one or two apis to be written. If that's the case, you can use system properties to control the output: + +The default is generate *everything* supported by the specific library. Once you enable a feature, it will restrict the contents generated: + +``` +# generate only models +java -Dmodels {opts} + +# generate only apis +java -Dapis {opts} + +# generate only supporting files +java -DsupportingFiles + +# generate models and supporting files +java -Dmodels -DsupportingFiles +``` + +To control the specific files being generated, you can pass a CSV list of what you want: +``` +# generate the User and Pet models only +-Dmodels=User,Pet + +# generate the User model and the supportingFile `StringUtil.java`: +-Dmodels=User -DsupportingFiles=StringUtil.java +``` + +When using selective generation, _only_ the templates needed for the specific generation will be used. + ### Customizing the generator There are different aspects of customizing the code generator beyond just creating or modifying templates. Each language has a supporting configuration file to handle different type mappings, etc: diff --git a/modules/swagger-codegen-cli/pom.xml b/modules/swagger-codegen-cli/pom.xml index 5193e39531a6..8bd59c89c802 100644 --- a/modules/swagger-codegen-cli/pom.xml +++ b/modules/swagger-codegen-cli/pom.xml @@ -3,7 +3,7 @@ io.swagger swagger-codegen-project - 2.1.4-SNAPSHOT + 2.1.5-SNAPSHOT ../.. 4.0.0 diff --git a/modules/swagger-codegen-maven-plugin/pom.xml b/modules/swagger-codegen-maven-plugin/pom.xml index 4d7107dba7e1..b309bb39596b 100644 --- a/modules/swagger-codegen-maven-plugin/pom.xml +++ b/modules/swagger-codegen-maven-plugin/pom.xml @@ -6,7 +6,7 @@ io.swagger swagger-codegen-project - 2.1.4-SNAPSHOT + 2.1.5-SNAPSHOT ../.. swagger-codegen-maven-plugin diff --git a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java index 21eef59b0104..22726c84c046 100644 --- a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java +++ b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java @@ -36,6 +36,7 @@ import config.Config; import config.ConfigParser; import java.io.File; +import java.util.HashMap; import java.util.Map; import java.util.ServiceLoader; @@ -112,6 +113,9 @@ public class CodeGenMojo extends AbstractMojo { @Parameter(defaultValue = "true") private boolean addCompileSourceRoot = true; + @Parameter + protected Map environmentVariables = new HashMap(); + /** * The project being built. */ @@ -125,6 +129,17 @@ public class CodeGenMojo extends AbstractMojo { CodegenConfig config = CodegenConfigLoader.forName(language); config.setOutputDir(output.getAbsolutePath()); + if (environmentVariables != null) { + for(String key : environmentVariables.keySet()) { + String value = environmentVariables.get(key); + if(value == null) { + // don't put null values + value = ""; + } + System.setProperty(key, value); + } + } + if (null != templateDirectory) { config.additionalProperties().put(TEMPLATE_DIR_PARAM, templateDirectory.getAbsolutePath()); } diff --git a/modules/swagger-codegen/pom.xml b/modules/swagger-codegen/pom.xml index 3ca7295a3c90..116d6c0c9860 100644 --- a/modules/swagger-codegen/pom.xml +++ b/modules/swagger-codegen/pom.xml @@ -3,7 +3,7 @@ io.swagger swagger-codegen-project - 2.1.4-SNAPSHOT + 2.1.5-SNAPSHOT ../.. 4.0.0 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 d4c0707f1a73..ffb4a0112a57 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 @@ -1,5 +1,7 @@ package io.swagger.codegen; +import config.Config; +import config.ConfigParser; import io.swagger.models.Swagger; import io.swagger.parser.SwaggerParser; import org.apache.commons.cli.BasicParser; @@ -9,6 +11,7 @@ import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -41,6 +44,7 @@ public class Codegen extends DefaultGenerator { options.addOption("t", "template-dir", true, "folder containing the template files"); options.addOption("d", "debug-info", false, "prints additional info for debugging"); options.addOption("a", "auth", true, "adds authorization headers when fetching the swagger definitions remotely. Pass in a URL-encoded string of name:header with a comma separating multiple values"); + options.addOption("c", "config", true, "location of the configuration file"); ClientOptInput clientOptInput = new ClientOptInput(); ClientOpts clientOpts = new ClientOpts(); @@ -84,6 +88,18 @@ public class Codegen extends DefaultGenerator { if (cmd.hasOption("i")) { swagger = new SwaggerParser().read(cmd.getOptionValue("i"), clientOptInput.getAuthorizationValues(), true); } + if (cmd.hasOption("c")) { + String configFile = cmd.getOptionValue("c"); + Config genConfig = ConfigParser.read(configFile); + config = clientOptInput.getConfig(); + if (null != genConfig && null != config) { + for (CliOption langCliOption : config.cliOptions()) { + if (genConfig.hasOption(langCliOption.getOpt())) { + config.additionalProperties().put(langCliOption.getOpt(), genConfig.getOption(langCliOption.getOpt())); + } + } + } + } if (cmd.hasOption("t")) { clientOpts.getProperties().put(CodegenConstants.TEMPLATE_DIR, String.valueOf(cmd.getOptionValue("t"))); } @@ -145,4 +161,4 @@ public class Codegen extends DefaultGenerator { configString = sb.toString(); } } -} \ No newline at end of file +} 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 3292efbfe760..c111a3af2fcb 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 @@ -69,6 +69,8 @@ public interface CodegenConfig { CodegenModel fromModel(String name, Model model, Map allDefinitions); + CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map definitions, Swagger swagger); + CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map definitions); List fromSecurity(Map schemes); 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 b2ada4a19812..62659530a82f 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 @@ -40,4 +40,6 @@ public class CodegenConstants { public static final String SORT_PARAMS_BY_REQUIRED_FLAG = "sortParamsByRequiredFlag"; public static final String SORT_PARAMS_BY_REQUIRED_FLAG_DESC = "Sort method arguments to place required parameters before optional parameters. Default: true"; + public static final String PACKAGE_NAME = "packageName"; + public static final String PACKAGE_VERSION = "packageVersion"; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java index 373c5b2b7857..871b3f261c0f 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 @@ -10,7 +10,7 @@ import java.util.Set; public class CodegenOperation { public final List responseHeaders = new ArrayList(); - public Boolean hasConsumes, hasProduces, hasParams, returnTypeIsPrimitive, + public Boolean hasAuthMethods, hasConsumes, hasProduces, hasParams, returnTypeIsPrimitive, returnSimpleType, subresourceOperation, isMapContainer, isListContainer, hasMore = Boolean.TRUE, isMultipart, isResponseBinary = Boolean.FALSE; public String path, operationId, returnType, httpMethod, returnBaseType, diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java index edd65cc06034..101182063839 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java @@ -1,6 +1,7 @@ package io.swagger.codegen; -import java.util.Set; +import java.util.List; +import java.util.Map; public class CodegenSecurity { public String name; @@ -11,5 +12,5 @@ public class CodegenSecurity { public Boolean isKeyInQuery, isKeyInHeader; // Oauth specific public String flow, authorizationUrl, tokenUrl; - public Set scopes; + public List> scopes; } 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 45b5d9f64eec..dbfc4a0fef2f 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,7 +106,8 @@ public class DefaultCodegen { } if (additionalProperties.containsKey(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG)) { - this.setSortParamsByRequiredFlag(Boolean.valueOf((String)additionalProperties.get(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG).toString())); + this.setSortParamsByRequiredFlag(Boolean.valueOf(additionalProperties + .get(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG).toString())); } } @@ -244,18 +245,42 @@ public class DefaultCodegen { this.sortParamsByRequiredFlag = sortParamsByRequiredFlag; } + /** + * Return the file name of the Api + * + * @param name the file name of the Api + * @return the file name of the Api + */ public String toApiFilename(String name) { return toApiName(name); } + /** + * Return the variable name in the Api + * + * @param name the varible name of the Api + * @return the snake-cased variable name + */ public String toApiVarName(String name) { return snakeCase(name); } + /** + * Return the capitalized file name of the model + * + * @param name the model name + * @return the file name of the model + */ public String toModelFilename(String name) { return initialCaps(name); } + /** + * Return the operation ID (method name) + * + * @param operationId operation ID + * @return the sanitized method name + */ public String toOperationId(String operationId) { // throw exception if method name is empty if (StringUtils.isEmpty(operationId)) { @@ -265,6 +290,13 @@ public class DefaultCodegen { return operationId; } + /** + * Return the variable name by removing invalid characters and proper escaping if + * it's a reserved word. + * + * @param name the variable name + * @return the sanitized variable name + */ public String toVarName(String name) { if (reservedWords.contains(name)) { return escapeReservedWord(name); @@ -273,6 +305,13 @@ public class DefaultCodegen { } } + /** + * Return the parameter name by removing invalid characters and proper escaping if + * it's a reserved word. + * + * @param property Codegen property object + * @return the sanitized parameter name + */ public String toParamName(String name) { name = removeNonNameElementToCamelCase(name); if (reservedWords.contains(name)) { @@ -281,14 +320,33 @@ public class DefaultCodegen { return name; } + /** + * Return the Enum name (e.g. StatusEnum given 'status') + * + * @param property Codegen property object + * @return the Enum name + */ public String toEnumName(CodegenProperty property) { return StringUtils.capitalize(property.name) + "Enum"; } - + + /** + * Return the escaped name of the reserved word + * + * @param name the name to be escaped + * @throws Runtime exception as reserved word is not allowed (default behavior) + * @return the escaped reserved word + */ public String escapeReservedWord(String name) { throw new RuntimeException("reserved word " + name + " not allowed"); } + /** + * Return the fully-qualified "Model" name for import + * + * @param name the name of the "Model" + * @return the fully-qualified "Model" name for import + */ public String toModelImport(String name) { if ("".equals(modelPackage())) { return name; @@ -297,10 +355,26 @@ public class DefaultCodegen { } } + /** + * Return the fully-qualified "Api" name for import + * + * @param name the name of the "Api" + * @return the fully-qualified "Api" name for import + */ public String toApiImport(String name) { return apiPackage() + "." + name; } + /** + * Default constructor. + * This method will map between Swagger type and language-specified type, as well as mapping + * between Swagger type and the corresponding import statement for the language. This will + * also add some language specified CLI options, if any. + * + * @param path the path of the operation + * @param operation Swagger operation object + * @return string presentation of the example path + */ public DefaultCodegen() { defaultIncludes = new HashSet( Arrays.asList("double", @@ -364,7 +438,13 @@ public class DefaultCodegen { cliOptions.add(new CliOption(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC)); } - + /** + * Return the example path + * + * @param path the path of the operation + * @param operation Swagger operation object + * @return string presentation of the example path + */ public String generateExamplePath(String path, Operation operation) { StringBuilder sb = new StringBuilder(); sb.append(path); @@ -415,6 +495,12 @@ public class DefaultCodegen { return sb.toString(); } + /** + * Return the instantiation type of the property, especially for map and array + * + * @param p Swagger property object + * @return string presentation of the instantiation type of the property + */ public String toInstantiationType(Property p) { if (p instanceof MapProperty) { MapProperty ap = (MapProperty) p; @@ -435,6 +521,12 @@ public class DefaultCodegen { } } + /** + * Return the default value of the property + * + * @param p Swagger property object + * @return string presentation of the default value of the property + */ public String toDefaultValue(Property p) { if (p instanceof StringProperty) { return "null"; @@ -475,6 +567,8 @@ public class DefaultCodegen { /** * returns the swagger type for the property + * @param p Swagger property object + * @return string presentation of the type **/ public String getSwaggerType(Property p) { String datatype = null; @@ -520,18 +614,42 @@ public class DefaultCodegen { return datatype; } + /** + * Return the snake-case of the string + * + * @param name string to be snake-cased + * @return snake-cased string + */ public String snakeCase(String name) { return (name.length() > 0) ? (Character.toLowerCase(name.charAt(0)) + name.substring(1)) : ""; } + /** + * Capitalize the string + * + * @param name string to be capitalized + * @return capitalized string + */ public String initialCaps(String name) { return StringUtils.capitalize(name); } + /** + * Output the type declaration of a given name + * + * @param name name + * @return a string presentation of the type + */ public String getTypeDeclaration(String name) { return name; } + /** + * Output the type declaration of the property + * + * @param p Swagger Property object + * @return a string presentation of the property type + */ public String getTypeDeclaration(Property p) { String swaggerType = getSwaggerType(p); if (typeMapping.containsKey(swaggerType)) { @@ -540,6 +658,13 @@ public class DefaultCodegen { return swaggerType; } + /** + * Output the API (class) name (capitalized) ending with "Api" + * Return DefaultApi if name is empty + * + * @param name the name of the Api + * @return capitalized Api name ending with "Api" + */ public String toApiName(String name) { if (name.length() == 0) { return "DefaultApi"; @@ -547,14 +672,35 @@ public class DefaultCodegen { return initialCaps(name) + "Api"; } + /** + * Output the proper model name (capitalized) + * + * @param name the name of the model + * @return capitalized model name + */ public String toModelName(String name) { return initialCaps(name); } + /** + * Convert Swagger Model object to Codegen Model object without providing all model definitions + * + * @param name the name of the model + * @param model Swagger Model object + * @return Codegen Model object + */ public CodegenModel fromModel(String name, Model model) { return fromModel(name, model, null); } + /** + * Convert Swagger Model object to Codegen Model object + * + * @param name the name of the model + * @param model Swagger Model object + * @param allDefinitions a map of all Swagger models from the spec + * @return Codegen Model object + */ public CodegenModel fromModel(String name, Model model, Map allDefinitions) { CodegenModel m = CodegenModelFactory.newInstance(CodegenModelType.MODEL); if (reservedWords.contains(name)) { @@ -641,6 +787,12 @@ public class DefaultCodegen { return m; } + /** + * Camelize the method name of the getter and setter + * + * @param name string to be camelized + * @return Camelized string + */ public String getterAndSetterCapitalize(String name) { if (name == null || name.length() == 0) { return name; @@ -649,7 +801,14 @@ public class DefaultCodegen { return camelize(toVarName(name)); } - + + /** + * Convert Swagger Property object to Codegen Property object + * + * @param name name of the property + * @param p Swagger property object + * @return Codegen Property object + */ public CodegenProperty fromProperty(String name, Property p) { if (p == null) { LOGGER.error("unexpected missing property for name " + name); @@ -705,9 +864,10 @@ public class DefaultCodegen { property.allowableValues = allowableValues; } } - if(p instanceof IntegerProperty) { + + if (p instanceof IntegerProperty) { IntegerProperty sp = (IntegerProperty) p; - if(sp.getEnum() != null) { + if (sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = new ArrayList(); for(Integer i : _enum) { @@ -721,9 +881,10 @@ public class DefaultCodegen { property.allowableValues = allowableValues; } } - if(p instanceof LongProperty) { + + if (p instanceof LongProperty) { LongProperty sp = (LongProperty) p; - if(sp.getEnum() != null) { + if (sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = new ArrayList(); for(Long i : _enum) { @@ -737,9 +898,10 @@ public class DefaultCodegen { property.allowableValues = allowableValues; } } - if(p instanceof DoubleProperty) { + + if (p instanceof DoubleProperty) { DoubleProperty sp = (DoubleProperty) p; - if(sp.getEnum() != null) { + if (sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = new ArrayList(); for(Double i : _enum) { @@ -753,9 +915,10 @@ public class DefaultCodegen { property.allowableValues = allowableValues; } } - if(p instanceof FloatProperty) { + + if (p instanceof FloatProperty) { FloatProperty sp = (FloatProperty) p; - if(sp.getEnum() != null) { + if (sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = new ArrayList(); for(Float i : _enum) { @@ -769,9 +932,10 @@ public class DefaultCodegen { property.allowableValues = allowableValues; } } - if(p instanceof DateProperty) { + + if (p instanceof DateProperty) { DateProperty sp = (DateProperty) p; - if(sp.getEnum() != null) { + if (sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = new ArrayList(); for(String i : _enum) { @@ -785,9 +949,10 @@ public class DefaultCodegen { property.allowableValues = allowableValues; } } - if(p instanceof DateTimeProperty) { + + if (p instanceof DateTimeProperty) { DateTimeProperty sp = (DateTimeProperty) p; - if(sp.getEnum() != null) { + if (sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = new ArrayList(); for(String i : _enum) { @@ -876,8 +1041,31 @@ public class DefaultCodegen { } return responses.get(code); } - + + /** + * Convert Swagger Operation object to Codegen Operation object (without providing a Swagger object) + * + * @param path the path of the operation + * @param httpMethod HTTP method + * @param operation Swagger operation object + * @param definitions a map of Swagger models + * @return Codegen Operation object + */ public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions) { + return fromOperation(path, httpMethod, operation, definitions, null); + } + + /** + * Convert Swagger Operation object to Codegen Operation object + * + * @param path the path of the operation + * @param httpMethod HTTP method + * @param operation Swagger operation object + * @param definitions a map of Swagger models + * @param swagger a Swagger object representing the spec + * @return Codegen Operation object + */ + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { CodegenOperation op = CodegenModelFactory.newInstance(CodegenModelType.OPERATION); Set imports = new HashSet(); op.vendorExtensions = operation.getVendorExtensions(); @@ -913,15 +1101,32 @@ public class DefaultCodegen { op.summary = escapeText(operation.getSummary()); op.notes = escapeText(operation.getDescription()); op.tags = operation.getTags(); + op.hasConsumes = false; + op.hasProduces = false; - if (operation.getConsumes() != null && operation.getConsumes().size() > 0) { + List consumes = new ArrayList(); + if (operation.getConsumes() != null) { + if (operation.getConsumes().size() > 0) { + // use consumes defined in the operation + consumes = operation.getConsumes(); + } else { + // empty list, do nothing to override global setting + } + } else if (swagger != null && swagger.getConsumes() != null && swagger.getConsumes().size() > 0) { + // use consumes defined globally + consumes = swagger.getConsumes(); + LOGGER.debug("No consumes defined in operation. Using global consumes (" + swagger.getConsumes() + ") for " + op.operationId); + } + + // if "consumes" is defined (per operation or using global definition) + if (consumes != null && consumes.size() > 0) { List> c = new ArrayList>(); int count = 0; - for (String key : operation.getConsumes()) { + for (String key : consumes) { Map mediaType = new HashMap(); mediaType.put("mediaType", key); count += 1; - if (count < operation.getConsumes().size()) { + if (count < consumes.size()) { mediaType.put("hasMore", "true"); } else { mediaType.put("hasMore", null); @@ -932,14 +1137,29 @@ public class DefaultCodegen { op.hasConsumes = true; } - if (operation.getProduces() != null && operation.getProduces().size() > 0) { + List produces = new ArrayList(); + if (operation.getProduces() != null) { + if (operation.getProduces().size() > 0) { + // use produces defined in the operation + produces = operation.getProduces(); + } else { + // empty list, do nothing to override global setting + } + } else if (swagger != null && swagger.getProduces() != null && swagger.getProduces().size() > 0) { + // use produces defined globally + produces = swagger.getProduces(); + LOGGER.debug("No produces defined in operation. Using global produces (" + swagger.getProduces() + ") for " + op.operationId); + } + + // if "produces" is defined (per operation or using global definition) + if (produces != null && produces.size() > 0) { List> c = new ArrayList>(); int count = 0; - for (String key : operation.getProduces()) { + for (String key : produces) { Map mediaType = new HashMap(); mediaType.put("mediaType", key); count += 1; - if (count < operation.getProduces().size()) { + if (count < produces.size()) { mediaType.put("hasMore", "true"); } else { mediaType.put("hasMore", null); @@ -1092,6 +1312,13 @@ public class DefaultCodegen { return op; } + /** + * Convert Swagger Response object to Codegen Response object + * + * @param responseCode HTTP response code + * @param response Swagger Response object + * @return Codegen Response object + */ public CodegenResponse fromResponse(String responseCode, Response response) { CodegenResponse r = CodegenModelFactory.newInstance(CodegenModelType.RESPONSE); if ("default".equals(responseCode)) { @@ -1141,7 +1368,14 @@ public class DefaultCodegen { } return r; } - + + /** + * Convert Swagger Parameter object to Codegen Parameter object + * + * @param param Swagger parameter object + * @param a set of imports for library/package/module + * @return Codegen Parameter object + */ public CodegenParameter fromParameter(Parameter param, Set imports) { CodegenParameter p = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER); p.baseName = param.getName(); @@ -1287,6 +1521,12 @@ public class DefaultCodegen { return p; } + /** + * Convert map of Swagger SecuritySchemeDefinition objects to a list of Codegen Security objects + * + * @param schemes a map of Swagger SecuritySchemeDefinition object + * @return a list of Codegen Security objects + */ public List fromSecurity(Map schemes) { if (schemes == null) { return null; @@ -1319,7 +1559,23 @@ public class DefaultCodegen { sec.authorizationUrl = oauth2Definition.getAuthorizationUrl(); sec.tokenUrl = oauth2Definition.getTokenUrl(); if (oauth2Definition.getScopes() != null) { - sec.scopes = oauth2Definition.getScopes().keySet(); + List> scopes = new ArrayList>(); + int count = 0, numScopes = oauth2Definition.getScopes().size(); + for(Map.Entry scopeEntry : oauth2Definition.getScopes().entrySet()) { + Map scope = new HashMap(); + scope.put("scope", scopeEntry.getKey()); + scope.put("description", scopeEntry.getValue()); + + count += 1; + if (count < numScopes) { + scope.put("hasMore", "true"); + } else { + scope.put("hasMore", null); + } + + scopes.add(scope); + } + sec.scopes = scopes; } } @@ -1329,6 +1585,12 @@ public class DefaultCodegen { return secs; } + /** + * Check the type to see if it needs import the library/module/package + * + * @param type name of the type + * @return true if the library/module/package of the corresponding type needs to be imported + */ protected boolean needToImport(String type) { return !defaultIncludes.contains(type) && !languageSpecificPrimitives.contains(type) @@ -1386,6 +1648,15 @@ public class DefaultCodegen { return objs; } + /** + * Add operation to group + * + * @param tag name of the tag + * @param resourcePath path of the resource + * @param operation Swagger Operation object + * @param co Codegen Operation object + * @param operations map of Codegen operations + */ public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { List opList = operations.get(tag); if (opList == null) { @@ -1396,9 +1667,7 @@ public class DefaultCodegen { co.baseName = tag; } - /* underscore and camelize are copied from Twitter elephant bird - * https://github.com/twitter/elephant-bird/blob/master/core/src/main/java/com/twitter/elephantbird/util/Strings.java - */ + private void addParentContainer(CodegenModel m, String name, Property property) { final CodegenProperty tmp = fromProperty(name, property); @@ -1417,6 +1686,8 @@ public class DefaultCodegen { /** * Underscore the given word. + * Copied from Twitter elephant bird + * https://github.com/twitter/elephant-bird/blob/master/core/src/main/java/com/twitter/elephantbird/util/Strings.java * * @param word The word * @return The underscored version of the word @@ -1481,12 +1752,11 @@ public class DefaultCodegen { } } - /** * Remove characters not suitable for variable or method name from the input and camelize it * - * @param name - * @return + * @param name string to be camelize + * @return camelized string */ public String removeNonNameElementToCamelCase(String name) { String nonNameElementPattern = "[-_:;#]"; @@ -1502,11 +1772,26 @@ public class DefaultCodegen { } return name; } - + + /** + * Camelize name (parameter, property, method, etc) with upper case for first letter + * copied from Twitter elephant bird + * https://github.com/twitter/elephant-bird/blob/master/core/src/main/java/com/twitter/elephantbird/util/Strings.java + * + * @param word string to be camelize + * @return camelized string + */ public static String camelize(String word) { return camelize(word, false); } + /** + * Camelize name (parameter, property, method, etc) + * + * @param word string to be camelize + * @param lowercaseFirstLetter lower case for first letter if set to true + * @return camelized string + */ public static String camelize(String word, boolean lowercaseFirstLetter) { // Replace all slashes with dots (package separator) Pattern p = Pattern.compile("\\/(.?)"); @@ -1611,7 +1896,7 @@ public class DefaultCodegen { } /** - * sanitize name (parameter, property, method, etc) + * Sanitize name (parameter, property, method, etc) * * @param name string to be sanitize * @return sanitized string 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 5df85e1b88cd..38089e7eeed1 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 @@ -29,16 +29,7 @@ import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; public class DefaultGenerator extends AbstractGenerator implements Generator { Logger LOGGER = LoggerFactory.getLogger(DefaultGenerator.class); @@ -60,6 +51,53 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { @Override public List generate() { + Boolean generateApis = null; + Boolean generateModels = null; + Boolean generateSupportingFiles = null; + + Set modelsToGenerate = null; + Set apisToGenerate = null; + Set supportingFilesToGenerate = null; + + // allows generating only models by specifying a CSV of models to generate, or empty for all + if(System.getProperty("models") != null) { + String modelNames = System.getProperty("models"); + generateModels = true; + if(!modelNames.isEmpty()) { + modelsToGenerate = new HashSet(Arrays.asList(modelNames.split(","))); + } + } + if(System.getProperty("apis") != null) { + String apiNames = System.getProperty("apis"); + generateApis = true; + if(!apiNames.isEmpty()) { + apisToGenerate = new HashSet(Arrays.asList(apiNames.split(","))); + } + } + if(System.getProperty("supportingFiles") != null) { + String supportingFiles = System.getProperty("supportingFiles"); + generateSupportingFiles = true; + if(!supportingFiles.isEmpty()) { + supportingFilesToGenerate = new HashSet(Arrays.asList(supportingFiles.split(","))); + } + } + + if(generateApis == null && generateModels == null && generateSupportingFiles == null) { + // no specifics are set, generate everything + generateApis = true; generateModels = true; generateSupportingFiles = true; + } + else { + if(generateApis == null) { + generateApis = false; + } + if(generateModels == null) { + generateModels = false; + } + if(generateSupportingFiles == null) { + generateSupportingFiles = false; + } + } + if (swagger == null || config == null) { throw new RuntimeException("missing swagger input or config!"); } @@ -125,8 +163,13 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } String contextPath = swagger.getBasePath() == null ? "" : swagger.getBasePath(); String basePath = hostBuilder.toString(); + String basePathWithoutHost = swagger.getBasePath(); + // resolve inline models + InlineModelResolver inlineModelResolver = new InlineModelResolver(); + inlineModelResolver.flatten(swagger); + List allOperations = new ArrayList(); List allModels = new ArrayList(); @@ -135,28 +178,107 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { if (definitions != null) { List sortedModelKeys = sortModelsByInheritance(definitions); - for (String name : sortedModelKeys) { - try { - - //dont generate models that have an import mapping - if(config.importMapping().containsKey(name)) { - continue; + if(generateModels) { + if(modelsToGenerate != null && modelsToGenerate.size() > 0) { + List updatedKeys = new ArrayList(); + for(String m : sortedModelKeys) { + if(modelsToGenerate.contains(m)) { + updatedKeys.add(m); + } } + sortedModelKeys = updatedKeys; + } - Model model = definitions.get(name); - Map modelMap = new HashMap(); - modelMap.put(name, model); - Map models = processModels(config, modelMap, definitions); - models.putAll(config.additionalProperties()); - - allModels.add(((List) models.get("models")).get(0)); - - for (String templateName : config.modelTemplateFiles().keySet()) { - String suffix = config.modelTemplateFiles().get(templateName); - String filename = config.modelFileFolder() + File.separator + config.toModelFilename(name) + suffix; - if (!config.shouldOverwrite(filename)) { + for (String name : sortedModelKeys) { + try { + //don't generate models that have an import mapping + if(config.importMapping().containsKey(name)) { continue; } + + Model model = definitions.get(name); + Map modelMap = new HashMap(); + modelMap.put(name, model); + Map models = processModels(config, modelMap, definitions); + models.putAll(config.additionalProperties()); + + allModels.add(((List) models.get("models")).get(0)); + + for (String templateName : config.modelTemplateFiles().keySet()) { + String suffix = config.modelTemplateFiles().get(templateName); + String filename = config.modelFileFolder() + File.separator + config.toModelFilename(name) + suffix; + if (!config.shouldOverwrite(filename)) { + continue; + } + String templateFile = getFullTemplateFile(config, templateName); + String template = readTemplate(templateFile); + Template tmpl = Mustache.compiler() + .withLoader(new Mustache.TemplateLoader() { + @Override + public Reader getTemplate(String name) { + return getTemplateReader(getFullTemplateFile(config, name + ".mustache")); + } + }) + .defaultValue("") + .compile(template); + writeToFile(filename, tmpl.execute(models)); + files.add(new File(filename)); + } + } catch (Exception e) { + throw new RuntimeException("Could not generate model '" + name + "'", e); + } + } + } + } + if (System.getProperty("debugModels") != null) { + System.out.println("############ Model info ############"); + Json.prettyPrint(allModels); + } + + // apis + Map> paths = processPaths(swagger.getPaths()); + if(generateApis) { + if(apisToGenerate != null && apisToGenerate.size() > 0) { + Map> updatedPaths = new TreeMap>(); + for(String m : paths.keySet()) { + if(apisToGenerate.contains(m)) { + updatedPaths.put(m, paths.get(m)); + } + } + paths = updatedPaths; + } + for (String tag : paths.keySet()) { + try { + List ops = paths.get(tag); + Map operation = processOperations(config, tag, ops); + + operation.put("basePath", basePath); + operation.put("basePathWithoutHost", basePathWithoutHost); + operation.put("contextPath", contextPath); + operation.put("baseName", tag); + operation.put("modelPackage", config.modelPackage()); + operation.putAll(config.additionalProperties()); + operation.put("classname", config.toApiName(tag)); + operation.put("classVarName", config.toApiVarName(tag)); + operation.put("importPath", config.toApiImport(tag)); + + processMimeTypes(swagger.getConsumes(), operation, "consumes"); + processMimeTypes(swagger.getProduces(), operation, "produces"); + + allOperations.add(new HashMap(operation)); + for (int i = 0; i < allOperations.size(); i++) { + Map oo = (Map) allOperations.get(i); + if (i < (allOperations.size() - 1)) { + oo.put("hasMore", "true"); + } + } + + for (String templateName : config.apiTemplateFiles().keySet()) { + String filename = config.apiFilename(templateName, tag); + if (!config.shouldOverwrite(filename) && new File(filename).exists()) { + continue; + } + String templateFile = getFullTemplateFile(config, templateName); String template = readTemplate(templateFile); Template tmpl = Mustache.compiler() @@ -168,71 +290,15 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { }) .defaultValue("") .compile(template); - writeToFile(filename, tmpl.execute(models)); + + writeToFile(filename, tmpl.execute(operation)); files.add(new File(filename)); } } catch (Exception e) { - throw new RuntimeException("Could not generate model '" + name + "'", e); + throw new RuntimeException("Could not generate api file for '" + tag + "'", e); } } } - if (System.getProperty("debugModels") != null) { - System.out.println("############ Model info ############"); - Json.prettyPrint(allModels); - } - - // apis - Map> paths = processPaths(swagger.getPaths()); - for (String tag : paths.keySet()) { - try { - List ops = paths.get(tag); - Map operation = processOperations(config, tag, ops); - - operation.put("basePath", basePath); - operation.put("contextPath", contextPath); - operation.put("baseName", tag); - operation.put("modelPackage", config.modelPackage()); - operation.putAll(config.additionalProperties()); - operation.put("classname", config.toApiName(tag)); - operation.put("classVarName", config.toApiVarName(tag)); - operation.put("importPath", config.toApiImport(tag)); - - processMimeTypes(swagger.getConsumes(), operation, "consumes"); - processMimeTypes(swagger.getProduces(), operation, "produces"); - - allOperations.add(new HashMap(operation)); - for (int i = 0; i < allOperations.size(); i++) { - Map oo = (Map) allOperations.get(i); - if (i < (allOperations.size() - 1)) { - oo.put("hasMore", "true"); - } - } - - for (String templateName : config.apiTemplateFiles().keySet()) { - String filename = config.apiFilename(templateName, tag); - if (!config.shouldOverwrite(filename) && new File(filename).exists()) { - continue; - } - - String templateFile = getFullTemplateFile(config, templateName); - String template = readTemplate(templateFile); - Template tmpl = Mustache.compiler() - .withLoader(new Mustache.TemplateLoader() { - @Override - public Reader getTemplate(String name) { - return getTemplateReader(getFullTemplateFile(config, name + ".mustache")); - } - }) - .defaultValue("") - .compile(template); - - writeToFile(filename, tmpl.execute(operation)); - files.add(new File(filename)); - } - } catch (Exception e) { - throw new RuntimeException("Could not generate api file for '" + tag + "'", e); - } - } if (System.getProperty("debugOperations") != null) { System.out.println("############ Operation info ############"); Json.prettyPrint(allOperations); @@ -276,66 +342,79 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { Json.prettyPrint(bundle); } - for (SupportingFile support : config.supportingFiles()) { - try { - String outputFolder = config.outputFolder(); - if (isNotEmpty(support.folder)) { - outputFolder += File.separator + support.folder; - } - File of = new File(outputFolder); - if (!of.isDirectory()) { - of.mkdirs(); - } - String outputFilename = outputFolder + File.separator + support.destinationFilename; - if (!config.shouldOverwrite(outputFilename)) { - continue; - } + if(generateSupportingFiles) { + for (SupportingFile support : config.supportingFiles()) { + try { + String outputFolder = config.outputFolder(); + if (isNotEmpty(support.folder)) { + outputFolder += File.separator + support.folder; + } + File of = new File(outputFolder); + if (!of.isDirectory()) { + of.mkdirs(); + } + String outputFilename = outputFolder + File.separator + support.destinationFilename; + if (!config.shouldOverwrite(outputFilename)) { + continue; + } - String templateFile = getFullTemplateFile(config, support.templateFile); + String templateFile = getFullTemplateFile(config, support.templateFile); - if (templateFile.endsWith("mustache")) { - String template = readTemplate(templateFile); - Template tmpl = Mustache.compiler() - .withLoader(new Mustache.TemplateLoader() { - @Override - public Reader getTemplate(String name) { - return getTemplateReader(getFullTemplateFile(config, name + ".mustache")); + boolean shouldGenerate = true; + if(supportingFilesToGenerate != null && supportingFilesToGenerate.size() > 0) { + if(supportingFilesToGenerate.contains(support.destinationFilename)) { + shouldGenerate = true; + } + else { + shouldGenerate = false; + } + } + if(shouldGenerate) { + if (templateFile.endsWith("mustache")) { + String template = readTemplate(templateFile); + Template tmpl = Mustache.compiler() + .withLoader(new Mustache.TemplateLoader() { + @Override + public Reader getTemplate(String name) { + return getTemplateReader(getFullTemplateFile(config, name + ".mustache")); + } + }) + .defaultValue("") + .compile(template); + + writeToFile(outputFilename, tmpl.execute(bundle)); + files.add(new File(outputFilename)); + } else { + InputStream in = null; + + try { + in = new FileInputStream(templateFile); + } catch (Exception e) { + // continue + } + if (in == null) { + in = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(templateFile)); + } + File outputFile = new File(outputFilename); + OutputStream out = new FileOutputStream(outputFile, false); + if (in != null && out != null) { + System.out.println("writing file " + outputFile); + IOUtils.copy(in, out); + } else { + if (in == null) { + System.out.println("can't open " + templateFile + " for input"); } - }) - .defaultValue("") - .compile(template); + if (out == null) { + System.out.println("can't open " + outputFile + " for output"); + } + } - writeToFile(outputFilename, tmpl.execute(bundle)); - files.add(new File(outputFilename)); - } else { - InputStream in = null; - - try { - in = new FileInputStream(templateFile); - } catch (Exception e) { - // continue - } - if (in == null) { - in = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(templateFile)); - } - File outputFile = new File(outputFilename); - OutputStream out = new FileOutputStream(outputFile, false); - if (in != null && out != null) { - System.out.println("writing file " + outputFile); - IOUtils.copy(in, out); - } else { - if (in == null) { - System.out.println("can't open " + templateFile + " for input"); - } - if (out == null) { - System.out.println("can't open " + outputFile + " for output"); + files.add(outputFile); } } - - files.add(outputFile); + } catch (Exception e) { + throw new RuntimeException("Could not generate supporting file '" + support + "'", e); } - } catch (Exception e) { - throw new RuntimeException("Could not generate supporting file '" + support + "'", e); } } @@ -471,7 +550,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { for (String tag : tags) { CodegenOperation co = null; try { - co = config.fromOperation(resourcePath, httpMethod, operation, swagger.getDefinitions()); + co = config.fromOperation(resourcePath, httpMethod, operation, swagger.getDefinitions(), swagger); co.tags = new ArrayList(); co.tags.add(sanitizeTag(tag)); config.addOperationToGroup(sanitizeTag(tag), resourcePath, operation, co, operations); @@ -519,6 +598,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } if (!authMethods.isEmpty()) { co.authMethods = config.fromSecurity(authMethods); + co.hasAuthMethods = true; } } catch (Exception ex) { @@ -526,7 +606,8 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { + " Tag: " + tag + "\n"// + " Operation: " + operation.getOperationId() + "\n" // + " Resource: " + httpMethod + " " + resourcePath + "\n"// - + " Definitions: " + swagger.getDefinitions(); + + " Definitions: " + swagger.getDefinitions() + "\n" // + + " Exception: " + ex.getMessage(); throw new RuntimeException(msg, ex); } } 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 new file mode 100644 index 000000000000..d2f47f2a6f6d --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/InlineModelResolver.java @@ -0,0 +1,326 @@ +package io.swagger.codegen; + +import com.sun.org.apache.xpath.internal.operations.Mod; +import io.swagger.models.*; +import io.swagger.models.parameters.BodyParameter; +import io.swagger.models.parameters.Parameter; +import io.swagger.models.parameters.RefParameter; +import io.swagger.models.properties.*; +import io.swagger.util.Json; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class InlineModelResolver { + private Swagger swagger = null; + private boolean skipMatches = false; + + Map addedModels = new HashMap(); + Map generatedSignature = new HashMap(); + + public void flatten(Swagger swagger) { + this.swagger = swagger; + + if (swagger.getDefinitions() == null) { + swagger.setDefinitions(new HashMap()); + } + + // operations + Map paths = swagger.getPaths(); + Map models = swagger.getDefinitions(); + + if (paths != null) { + for (String pathname : paths.keySet()) { + Path path = paths.get(pathname); + + for (Operation operation : path.getOperations()) { + List parameters = operation.getParameters(); + + if (parameters != null) { + for (Parameter parameter : parameters) { + if (parameter instanceof BodyParameter) { + BodyParameter bp = (BodyParameter) parameter; + if (bp.getSchema() != null) { + Model model = bp.getSchema(); + if(model instanceof ModelImpl) { + String modelName = uniqueName(bp.getName()); + ModelImpl obj = (ModelImpl) model; + flattenProperties(obj.getProperties(), pathname); + + bp.setSchema(new RefModel(modelName)); + addGenerated(modelName, model); + swagger.addDefinition(modelName, model); + } + else if (model instanceof ArrayModel) { + ArrayModel am = (ArrayModel) model; + Property inner = am.getItems(); + + if(inner instanceof ObjectProperty) { + ObjectProperty op = (ObjectProperty) inner; + flattenProperties(op.getProperties(), pathname); + } + } + } + } + } + } + Map responses = operation.getResponses(); + if (responses != null) { + for (String key : responses.keySet()) { + Response response = responses.get(key); + if (response.getSchema() != null) { + Property property = response.getSchema(); + if (property instanceof ObjectProperty) { + String modelName = uniqueName("inline_response_" + key); + ObjectProperty op = (ObjectProperty) property; + Model model = modelFromProperty(op, modelName); + String existing = matchGenerated(model); + if (existing != null) { + response.setSchema(new RefProperty(existing)); + } else { + response.setSchema(new RefProperty(modelName)); + addGenerated(modelName, model); + swagger.addDefinition(modelName, model); + } + } else if (property instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) property; + if(ap.getItems() instanceof ObjectProperty) { + ObjectProperty op = (ObjectProperty) ap.getItems(); + Map props = op.getProperties(); + flattenProperties(props, "path"); + } + } else if (property instanceof MapProperty) { + MapProperty op = (MapProperty) property; + + Property innerProperty = op.getAdditionalProperties(); + if(innerProperty instanceof ObjectProperty) { + ModelImpl innerModel = new ModelImpl(); + // TODO: model props + innerModel.setTitle(property.getTitle()); + property.getVendorExtensions(); + property.getRequired(); + property.getReadOnly(); + property.getAccess(); + innerModel.setDescription(property.getDescription()); + innerModel.setExample(property.getExample()); + innerModel.setName(property.getName()); + innerModel.setXml(property.getXml()); + + innerModel.setAdditionalProperties(innerProperty); + + String modelName = uniqueName("inline_response_" + key); + String existing = matchGenerated(innerModel); + if (existing != null) { + response.setSchema(new RefProperty(existing)); + } else { + response.setSchema(new RefProperty(modelName)); + addGenerated(modelName, innerModel); + swagger.addDefinition(modelName, innerModel); + } + } + } + } + } + } + } + } + } + + // definitions + if (models != null) { + List modelNames = new ArrayList(models.keySet()); + for (String modelName : modelNames) { + Model model = models.get(modelName); + if (model instanceof ModelImpl) { + ModelImpl m = (ModelImpl) model; + + Map properties = m.getProperties(); + flattenProperties(properties, modelName); + + } else if (model instanceof ArrayModel) { + ArrayModel m = (ArrayModel) model; + Property inner = m.getItems(); + if (inner instanceof ObjectProperty) { + String innerModelName = uniqueName(modelName + "_inner"); + Model innerModel = modelFromProperty((ObjectProperty) inner, modelName); + + String existing = matchGenerated(innerModel); + if (existing == null) { + swagger.addDefinition(innerModelName, innerModel); + addGenerated(innerModelName, innerModel); + m.setItems(new RefProperty(innerModelName)); + } else { + m.setItems(new RefProperty(existing)); + } + } + } else if (model instanceof ComposedModel) { + ComposedModel m = (ComposedModel) model; + } + } + } + } + + public String matchGenerated(Model model) { + if (this.skipMatches) { + return null; + } + String json = Json.pretty(model); + if (generatedSignature.containsKey(json)) { + return generatedSignature.get(json); + } + return null; + } + + public void addGenerated(String name, Model model) { + generatedSignature.put(Json.pretty(model), name); + } + + public String uniqueName(String key) { + int count = 0; + boolean done = false; + key = key.replaceAll("[^a-z_\\.A-Z0-9 ]", ""); + while (!done) { + String name = key; + if (count > 0) { + name = key + "_" + count; + } + if (swagger.getDefinitions() == null) { + return name; + } else if (!swagger.getDefinitions().containsKey(name)) { + return name; + } + count += 1; + } + return key; + } + + public void flattenProperties(Map properties, String path) { + if (properties == null) { + return; + } + Map propsToUpdate = new HashMap(); + Map modelsToAdd = new HashMap(); + for (String key : properties.keySet()) { + Property property = properties.get(key); + if (property instanceof ObjectProperty && ((ObjectProperty)property).getProperties().size() > 0) { + String modelName = uniqueName(path + "_" + key); + + ObjectProperty op = (ObjectProperty) property; + Model model = modelFromProperty(op, modelName); + + String existing = matchGenerated(model); + + if (existing != null) { + propsToUpdate.put(key, new RefProperty(existing)); + } else { + propsToUpdate.put(key, new RefProperty(modelName)); + modelsToAdd.put(modelName, model); + addGenerated(modelName, model); + swagger.addDefinition(modelName, model); + } + } + } + if (propsToUpdate.size() > 0) { + for (String key : propsToUpdate.keySet()) { + properties.put(key, propsToUpdate.get(key)); + } + } + for (String key : modelsToAdd.keySet()) { + swagger.addDefinition(key, modelsToAdd.get(key)); + this.addedModels.put(key, modelsToAdd.get(key)); + } + } + + public Model modelFromProperty(ArrayProperty object, String path) { + String access = object.getAccess(); + String description = object.getDescription(); + String example = object.getExample(); + String name = object.getName(); + Integer position = object.getPosition(); + Boolean readOnly = object.getReadOnly(); + Boolean required = object.getRequired(); + String title = object.getTitle(); + Map extensions = object.getVendorExtensions(); + Xml xml = object.getXml(); + +// object.getItems() +// Map properties = object.getProperties(); + + Property inner = object.getItems(); + if (inner instanceof ObjectProperty) { + ArrayModel model = new ArrayModel(); + model.setDescription(description); + model.setExample(example); +// model.setName(name); +// model.setXml(xml); + + model.setItems(object.getItems()); + return model; + } + +// if(properties != null) { +// flattenProperties(properties, path); +// model.setProperties(properties); +// } + + return null; + } + + public Model modelFromProperty(ObjectProperty object, String path) { + String access = object.getAccess(); + String description = object.getDescription(); + String example = object.getExample(); + String name = object.getName(); + Integer position = object.getPosition(); + Boolean readOnly = object.getReadOnly(); + Boolean required = object.getRequired(); + String title = object.getTitle(); + Map extensions = object.getVendorExtensions(); + Xml xml = object.getXml(); + + Map properties = object.getProperties(); + + ModelImpl model = new ModelImpl(); + model.setDescription(description); + model.setExample(example); + model.setName(name); + model.setXml(xml); + + if (properties != null) { + flattenProperties(properties, path); + model.setProperties(properties); + } + + return model; + } + + public Model modelFromProperty(MapProperty object, String path) { + String access = object.getAccess(); + String description = object.getDescription(); + String example = object.getExample(); + String name = object.getName(); + Integer position = object.getPosition(); + Boolean readOnly = object.getReadOnly(); + Boolean required = object.getRequired(); + String title = object.getTitle(); + Map extensions = object.getVendorExtensions(); + Xml xml = object.getXml(); + + ArrayModel model = new ArrayModel(); + model.setDescription(description); + model.setExample(example); + model.setItems(object.getAdditionalProperties()); + + return model; + } + + public boolean isSkipMatches() { + return skipMatches; + } + + public void setSkipMatches(boolean skipMatches) { + this.skipMatches = skipMatches; + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java index a6bfc7d5ddd6..15f22dfe8ffd 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java @@ -84,12 +84,15 @@ public class XmlExampleGenerator { name = xml.getName(); } } - for (String pName : model.getProperties().keySet()) { - Property p = model.getProperties().get(pName); - if (p != null && p.getXml() != null && p.getXml().getAttribute() != null && p.getXml().getAttribute()) { - attributes.put(pName, p); - } else { - elements.put(pName, p); + // TODO: map objects will not enter this block + if(model.getProperties() != null) { + for (String pName : model.getProperties().keySet()) { + Property p = model.getProperties().get(pName); + if (p != null && p.getXml() != null && p.getXml().getAttribute() != null && p.getXml().getAttribute()) { + attributes.put(pName, p); + } else { + elements.put(pName, p); + } } } sb.append(indent(indent)).append(TAG_START); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java index cdc88d1f0235..35b876aabafa 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java @@ -17,6 +17,7 @@ import java.util.HashSet; import org.apache.commons.lang.StringUtils; public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfig { + public static final String USE_ANDROID_MAVEN_GRADLE_PLUGIN = "useAndroidMavenGradlePlugin"; protected String invokerPackage = "io.swagger.client"; protected String groupId = "io.swagger"; protected String artifactId = "swagger-android-client"; @@ -64,7 +65,7 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, "artifactId for use in the generated build.gradle and pom.xml")); cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, "artifact version for use in the generated build.gradle and pom.xml")); cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC)); - cliOptions.add(new CliOption("useAndroidMavenGradlePlugin", "A flag to toggle android-maven gradle plugin. Default is true.")); + cliOptions.add(new CliOption(USE_ANDROID_MAVEN_GRADLE_PLUGIN, "A flag to toggle android-maven gradle plugin. Default is true.")); } public CodegenType getTag() { @@ -220,14 +221,15 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); } - if (additionalProperties.containsKey("useAndroidMavenGradlePlugin")) { - this.setUseAndroidMavenGradlePlugin((Boolean) additionalProperties.get("useAndroidMavenGradlePlugin")); + if (additionalProperties.containsKey(USE_ANDROID_MAVEN_GRADLE_PLUGIN)) { + this.setUseAndroidMavenGradlePlugin(Boolean.valueOf((String) additionalProperties + .get(USE_ANDROID_MAVEN_GRADLE_PLUGIN))); } else { - additionalProperties.put("useAndroidMavenGradlePlugin", useAndroidMavenGradlePlugin); + additionalProperties.put(USE_ANDROID_MAVEN_GRADLE_PLUGIN, useAndroidMavenGradlePlugin); } supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); - additionalProperties.put("useAndroidMavenGradlePlugin", useAndroidMavenGradlePlugin); + additionalProperties.put(USE_ANDROID_MAVEN_GRADLE_PLUGIN, useAndroidMavenGradlePlugin); supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle")); 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 66692bf5f83a..1e218e5ca006 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 @@ -1,6 +1,7 @@ package io.swagger.codegen.languages; 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; @@ -79,8 +80,8 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig typeMapping.put("object", "Object"); cliOptions.clear(); - cliOptions.add(new CliOption("packageName", "C# package name (convention: Camel.Case), default: IO.Swagger")); - cliOptions.add(new CliOption("packageVersion", "C# package version, default: 1.0.0")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "C# package name (convention: Camel.Case), default: IO.Swagger")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "C# package version, default: 1.0.0")); } @@ -88,19 +89,19 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig public void processOpts() { super.processOpts(); - if (additionalProperties.containsKey("packageVersion")) { - packageVersion = (String) additionalProperties.get("packageVersion"); + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { + setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); } else { - additionalProperties.put("packageVersion", packageVersion); + additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); } - if (additionalProperties.containsKey("packageName")) { - packageName = (String) additionalProperties.get("packageName"); + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); apiPackage = packageName + ".Api"; modelPackage = packageName + ".Model"; clientPackage = packageName + ".Client"; } else { - additionalProperties.put("packageName", packageName); + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); } additionalProperties.put("clientPackage", clientPackage); @@ -252,4 +253,11 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig return camelize(sanitizeName(operationId)); } + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public void setPackageVersion(String packageVersion) { + this.packageVersion = packageVersion; + } } 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 06f87edef383..96f749074496 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 @@ -1,6 +1,7 @@ package io.swagger.codegen.languages; 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; @@ -15,6 +16,7 @@ import java.util.HashMap; import java.util.HashSet; public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements CodegenConfig { + public static final String CLIENT_PACKAGE = "clientPackage"; protected String packageName = "IO.Swagger"; protected String packageVersion = "1.0.0"; protected String clientPackage = "IO.Swagger.Client"; @@ -77,34 +79,34 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege typeMapping.put("object", "Object"); cliOptions.clear(); - cliOptions.add(new CliOption("packageName", "C# package name (convention: Camel.Case), default: IO.Swagger")); - cliOptions.add(new CliOption("packageVersion", "C# package version, default: 1.0.0")); - + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "C# package name (convention: Camel.Case), default: IO.Swagger")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "C# package version, default: 1.0.0")); + cliOptions.add(new CliOption(CLIENT_PACKAGE, "C# client package name (convention: Camel.Case), default: IO.Swagger.Client")); } @Override public void processOpts() { super.processOpts(); - if (additionalProperties.containsKey("packageVersion")) { - packageVersion = (String) additionalProperties.get("packageVersion"); + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { + setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); } else { - additionalProperties.put("packageVersion", packageVersion); + additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); } - if (additionalProperties.containsKey("packageName")) { - packageName = (String) additionalProperties.get("packageName"); + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); apiPackage = packageName + ".Api"; modelPackage = packageName + ".Model"; clientPackage = packageName + ".Client"; } else { - additionalProperties.put("packageName", packageName); + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); } - if (additionalProperties.containsKey("clientPackage")) { - this.setClientPackage((String) additionalProperties.get("clientPackage")); + if (additionalProperties.containsKey(CLIENT_PACKAGE)) { + this.setClientPackage((String) additionalProperties.get(CLIENT_PACKAGE)); } else { - additionalProperties.put("clientPackage", clientPackage); + additionalProperties.put(CLIENT_PACKAGE, clientPackage); } supportingFiles.add(new SupportingFile("Configuration.mustache", @@ -123,6 +125,14 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege this.clientPackage = clientPackage; } + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public void setPackageVersion(String packageVersion) { + this.packageVersion = packageVersion; + } + public CodegenType getTag() { return CodegenType.CLIENT; } 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 f156146580ae..e18b9eac0a22 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 @@ -2,6 +2,7 @@ package io.swagger.codegen.languages; 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; @@ -15,6 +16,10 @@ import java.util.HashSet; import java.util.HashMap; public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { + public static final String BROWSER_CLIENT = "browserClient"; + public static final String PUB_NAME = "pubName"; + public static final String PUB_VERSION = "pubVersion"; + public static final String PUB_DESCRIPTION = "pubDescription"; protected boolean browserClient = true; protected String pubName = "swagger"; protected String pubVersion = "1.0.0"; @@ -72,10 +77,11 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("date", "DateTime"); typeMapping.put("File", "MultipartFile"); - cliOptions.add(new CliOption("browserClient", "Is the client browser based")); - cliOptions.add(new CliOption("pubName", "Name in generated pubspec")); - cliOptions.add(new CliOption("pubVersion", "Version in generated pubspec")); - cliOptions.add(new CliOption("sourceFolder", "source folder for generated code")); + cliOptions.add(new CliOption(BROWSER_CLIENT, "Is the client browser based")); + cliOptions.add(new CliOption(PUB_NAME, "Name in generated pubspec")); + cliOptions.add(new CliOption(PUB_VERSION, "Version in generated pubspec")); + cliOptions.add(new CliOption(PUB_DESCRIPTION, "Description in generated pubspec")); + cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, "source folder for generated code")); } public CodegenType getTag() { @@ -94,37 +100,37 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { public void processOpts() { super.processOpts(); - if (additionalProperties.containsKey("browserClient")) { - this.setBrowserClient(Boolean.parseBoolean((String) additionalProperties.get("browserClient"))); - additionalProperties.put("browserClient", browserClient); + if (additionalProperties.containsKey(BROWSER_CLIENT)) { + this.setBrowserClient(Boolean.parseBoolean((String) additionalProperties.get(BROWSER_CLIENT))); + additionalProperties.put(BROWSER_CLIENT, browserClient); } else { //not set, use to be passed to template - additionalProperties.put("browserClient", browserClient); + additionalProperties.put(BROWSER_CLIENT, browserClient); } - if (additionalProperties.containsKey("pubName")) { - this.setPubName((String) additionalProperties.get("pubName")); + if (additionalProperties.containsKey(PUB_NAME)) { + this.setPubName((String) additionalProperties.get(PUB_NAME)); } else { //not set, use to be passed to template - additionalProperties.put("pubName", pubName); + additionalProperties.put(PUB_NAME, pubName); } - if (additionalProperties.containsKey("pubVersion")) { - this.setPubVersion((String) additionalProperties.get("pubVersion")); + if (additionalProperties.containsKey(PUB_VERSION)) { + this.setPubVersion((String) additionalProperties.get(PUB_VERSION)); } else { //not set, use to be passed to template - additionalProperties.put("pubVersion", pubVersion); + additionalProperties.put(PUB_VERSION, pubVersion); } - if (additionalProperties.containsKey("pubDescription")) { - this.setPubDescription((String) additionalProperties.get("pubDescription")); + if (additionalProperties.containsKey(PUB_DESCRIPTION)) { + this.setPubDescription((String) additionalProperties.get(PUB_DESCRIPTION)); } else { //not set, use to be passed to template - additionalProperties.put("pubDescription", pubDescription); + additionalProperties.put(PUB_DESCRIPTION, pubDescription); } - if (additionalProperties.containsKey("sourceFolder")) { - this.setSourceFolder((String) additionalProperties.get("sourceFolder")); + if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { + this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); } final String libFolder = sourceFolder + File.separator + "lib"; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java index cf91c8fd78c8..353174df0563 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java @@ -68,15 +68,19 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig importMapping.put("File", "flash.filesystem.File"); // from - reservedWords = new HashSet( - Arrays.asList( -"add", "for", "lt", "tellTarget", "and", "function", "ne", "this", "break", "ge", "new", "typeof", "continue", "gt", "not", "var", "delete", "if", "on", "void", "do", "ifFrameLoaded", "onClipEvent", "while", "else", "in", "or", "with", "eq", "le", "return")); + reservedWords = new HashSet(Arrays.asList("add", "for", "lt", "tellTarget", "and", + "function", "ne", "this", "break", "ge", "new", "typeof", "continue", "gt", "not", + "var", "delete", "if", "on", "void", "do", "ifFrameLoaded", "onClipEvent", "while", + "else", "in", "or", "with", "eq", "le", "return")); cliOptions.clear(); - cliOptions.add(new CliOption("packageName", "flash package name (convention: package.name), default: io.swagger")); - cliOptions.add(new CliOption("packageVersion", "flash package version, default: 1.0.0")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "flash package name (convention:" + + " package.name), default: io.swagger")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "flash package version, " + + "default: 1.0.0")); cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC)); - cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, "source folder for generated code. e.g. src/main/flex")); + cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, "source folder for generated " + + "code. e.g. src/main/flex")); } @@ -95,8 +99,8 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); } - if (additionalProperties.containsKey("packageName")) { - setPackageName((String) additionalProperties.get("packageName")); + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); apiPackage = packageName + ".client.api"; modelPackage = packageName + ".client.model"; } @@ -104,20 +108,21 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig setPackageName("io.swagger"); } - if (additionalProperties.containsKey("packageVersion")) { - setPackageVersion((String) additionalProperties.get("packageVersion")); + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { + setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); } else { setPackageVersion("1.0.0"); } - additionalProperties.put("packageName", packageName); - additionalProperties.put("packageVersion", packageVersion); + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); + additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); //modelPackage = invokerPackage + File.separatorChar + "client" + File.separatorChar + "model"; //apiPackage = invokerPackage + File.separatorChar + "client" + File.separatorChar + "api"; - final String invokerFolder = (sourceFolder + File.separator + invokerPackage + File.separator + "swagger" + File.separator).replace(".", File.separator).replace('.', File.separatorChar); + final String invokerFolder = (sourceFolder + File.separator + invokerPackage + File.separator + + "swagger" + File.separator).replace(".", File.separator).replace('.', File.separatorChar); supportingFiles.add(new SupportingFile("ApiInvoker.as", invokerFolder + "common", "ApiInvoker.as")); supportingFiles.add(new SupportingFile("ApiUrlHelper.as", invokerFolder + "common", "ApiUrlHelper.as")); @@ -131,13 +136,20 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig supportingFiles.add(new SupportingFile("Response.as", invokerFolder + "event", "Response.as")); supportingFiles.add(new SupportingFile("build.properties", sourceFolder, "build.properties")); supportingFiles.add(new SupportingFile("build.xml", sourceFolder, "build.xml")); - supportingFiles.add(new SupportingFile("AirExecutorApp-app.xml", sourceFolder + File.separatorChar + "bin", "AirExecutorApp-app.xml")); - supportingFiles.add(new SupportingFile("ASAXB-0.1.1.swc", sourceFolder + File.separatorChar + "lib", "ASAXB-0.1.1.swc")); - supportingFiles.add(new SupportingFile("as3corelib.swc", sourceFolder + File.separatorChar + "lib", "as3corelib.swc")); - supportingFiles.add(new SupportingFile("flexunit-4.1.0_RC2-28-flex_3.5.0.12683.swc", sourceFolder + File.separator + "lib" + File.separator + "ext", "flexunit-4.1.0_RC2-28-flex_3.5.0.12683.swc")); - supportingFiles.add(new SupportingFile("flexunit-aircilistener-4.1.0_RC2-28-3.5.0.12683.swc", sourceFolder + File.separator + "lib" + File.separator + "ext", "flexunit-aircilistener-4.1.0_RC2-28-3.5.0.12683.swc")); - supportingFiles.add(new SupportingFile("flexunit-cilistener-4.1.0_RC2-28-3.5.0.12683.swc", sourceFolder + File.separator + "lib" + File.separator + "ext", "flexunit-cilistener-4.1.0_RC2-28-3.5.0.12683.swc")); - supportingFiles.add(new SupportingFile("flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc", sourceFolder + File.separator + "lib" + File.separator + "ext", "flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc")); + supportingFiles.add(new SupportingFile("AirExecutorApp-app.xml", sourceFolder + File.separatorChar + + "bin", "AirExecutorApp-app.xml")); + supportingFiles.add(new SupportingFile("ASAXB-0.1.1.swc", sourceFolder + File.separatorChar + + "lib", "ASAXB-0.1.1.swc")); + supportingFiles.add(new SupportingFile("as3corelib.swc", sourceFolder + File.separatorChar + + "lib", "as3corelib.swc")); + supportingFiles.add(new SupportingFile("flexunit-4.1.0_RC2-28-flex_3.5.0.12683.swc", sourceFolder + + File.separator + "lib" + File.separator + "ext", "flexunit-4.1.0_RC2-28-flex_3.5.0.12683.swc")); + supportingFiles.add(new SupportingFile("flexunit-aircilistener-4.1.0_RC2-28-3.5.0.12683.swc", sourceFolder + + File.separator + "lib" + File.separator + "ext", "flexunit-aircilistener-4.1.0_RC2-28-3.5.0.12683.swc")); + supportingFiles.add(new SupportingFile("flexunit-cilistener-4.1.0_RC2-28-3.5.0.12683.swc", sourceFolder + + File.separator + "lib" + File.separator + "ext", "flexunit-cilistener-4.1.0_RC2-28-3.5.0.12683.swc")); + supportingFiles.add(new SupportingFile("flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc", sourceFolder + + File.separator + "lib" + File.separator + "ext", "flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc")); } private static String dropDots(String str) { @@ -163,11 +175,13 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig @Override public String apiFileFolder() { - return (outputFolder + File.separatorChar + sourceFolder + File.separatorChar + apiPackage().replace('.', File.separatorChar)).replace('/', File.separatorChar); + return (outputFolder + File.separatorChar + sourceFolder + File.separatorChar + + apiPackage().replace('.', File.separatorChar)).replace('/', File.separatorChar); } public String modelFileFolder() { - return (outputFolder + File.separatorChar + sourceFolder + File.separatorChar + modelPackage().replace('.', File.separatorChar)).replace('/', File.separatorChar); + return (outputFolder + File.separatorChar + sourceFolder + File.separatorChar + + modelPackage().replace('.', File.separatorChar)).replace('/', File.separatorChar); } @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java index 930295f172dc..fb59e451ba6d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java @@ -31,6 +31,7 @@ import org.slf4j.LoggerFactory; public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(JavaClientCodegen.class); + public static final String FULL_JAVA_UTIL = "fullJavaUtil"; protected String invokerPackage = "io.swagger.client"; protected String groupId = "io.swagger"; @@ -84,7 +85,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC)); cliOptions.add(new CliOption(CodegenConstants.LOCAL_VARIABLE_PREFIX, CodegenConstants.LOCAL_VARIABLE_PREFIX_DESC)); cliOptions.add(new CliOption(CodegenConstants.SERIALIZABLE_MODEL, CodegenConstants.SERIALIZABLE_MODEL_DESC)); - cliOptions.add(new CliOption("fullJavaUtil", "whether to use fully qualified name for classes under java.util (default to false)")); + cliOptions.add(new CliOption(FULL_JAVA_UTIL, "whether to use fully qualified name for classes under java.util (default to false)")); supportedLibraries.put("", "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2"); supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6"); @@ -150,7 +151,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { } if (additionalProperties.containsKey(CodegenConstants.SERIALIZABLE_MODEL)) { - this.setSerializableModel(Boolean.valueOf((String)additionalProperties.get(CodegenConstants.SERIALIZABLE_MODEL).toString())); + this.setSerializableModel(Boolean.valueOf(additionalProperties.get(CodegenConstants.SERIALIZABLE_MODEL).toString())); } if (additionalProperties.containsKey(CodegenConstants.LIBRARY)) { @@ -160,13 +161,13 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { // need to put back serializableModel (boolean) into additionalProperties as value in additionalProperties is string additionalProperties.put(CodegenConstants.SERIALIZABLE_MODEL, serializableModel); - if (additionalProperties.containsKey("fullJavaUtil")) { - fullJavaUtil = Boolean.valueOf(additionalProperties.get("fullJavaUtil").toString()); + if (additionalProperties.containsKey(FULL_JAVA_UTIL)) { + this.setFullJavaUtil(Boolean.valueOf(additionalProperties.get(FULL_JAVA_UTIL).toString())); } if (fullJavaUtil) { javaUtilPrefix = "java.util."; } - additionalProperties.put("fullJavaUtil", fullJavaUtil); + additionalProperties.put(FULL_JAVA_UTIL, fullJavaUtil); additionalProperties.put("javaUtilPrefix", javaUtilPrefix); if (fullJavaUtil) { @@ -378,7 +379,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { 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"); + throw new RuntimeException("Empty method/operation name (operationId) not allowed"); } // method name cannot use reserved keyword, e.g. return @@ -507,6 +508,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { List codegenProperties = codegenModel.vars; // Iterate over all of the parent model properties + boolean removedChildEnum = false; for (CodegenProperty parentModelCodegenPropery : parentModelCodegenProperties) { // Look for enums if (parentModelCodegenPropery.isEnum) { @@ -519,12 +521,21 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { // We found an enum in the child class that is // a duplicate of the one in the parent, so remove it. iterator.remove(); + removedChildEnum = true; } } } } - - codegenModel.vars = codegenProperties; + + if(removedChildEnum) { + // If we removed an entry from this model's vars, we need to ensure hasMore is updated + int count = 0, numVars = codegenProperties.size(); + for(CodegenProperty codegenProperty : codegenProperties) { + count += 1; + codegenProperty.hasMore = (count < numVars) ? true : null; + } + codegenModel.vars = codegenProperties; + } } return codegenModel; @@ -572,4 +583,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { return packageName; } + public void setFullJavaUtil(boolean fullJavaUtil) { + this.fullJavaUtil = fullJavaUtil; + } } 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 8117cc58ce9e..cddf223aeaa6 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 @@ -19,6 +19,11 @@ import java.util.HashSet; import org.apache.commons.lang3.StringUtils; public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { + public static final String VARIABLE_NAMING_CONVENTION = "variableNamingConvention"; + public static final String PACKAGE_PATH = "packagePath"; + public static final String SRC_BASE_PATH = "srcBasePath"; + public static final String COMPOSER_VENDOR_NAME = "composerVendorName"; + public static final String COMPOSER_PROJECT_NAME = "composerProjectName"; protected String invokerPackage = "Swagger\\Client"; protected String composerVendorName = "swagger"; protected String composerProjectName = "swagger-client"; @@ -86,12 +91,12 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("object", "object"); typeMapping.put("DateTime", "\\DateTime"); - cliOptions.add(new CliOption("variableNamingConvention", "naming convention of variable name, e.g. camelCase. Default: snake_case")); + cliOptions.add(new CliOption(VARIABLE_NAMING_CONVENTION, "naming convention of variable name, e.g. camelCase. Default: snake_case")); cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, "The main namespace to use for all classes. e.g. Yay\\Pets")); - cliOptions.add(new CliOption("packagePath", "The main package name for classes. e.g. GeneratedPetstore")); - cliOptions.add(new CliOption("srcBasePath", "The directory under packagePath to serve as source root.")); - cliOptions.add(new CliOption("composerVendorName", "The vendor name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. yaypets")); - cliOptions.add(new CliOption("composerProjectName", "The project name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. petstore-client")); + cliOptions.add(new CliOption(PACKAGE_PATH, "The main package name for classes. e.g. GeneratedPetstore")); + cliOptions.add(new CliOption(SRC_BASE_PATH, "The directory under packagePath to serve as source root.")); + cliOptions.add(new CliOption(COMPOSER_VENDOR_NAME, "The vendor name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. yaypets")); + 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")); cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, "The version to use in the composer package version field. e.g. 1.2.3")); } @@ -144,16 +149,16 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { public void processOpts() { super.processOpts(); - if (additionalProperties.containsKey("packagePath")) { - this.setPackagePath((String) additionalProperties.get("packagePath")); + if (additionalProperties.containsKey(PACKAGE_PATH)) { + this.setPackagePath((String) additionalProperties.get(PACKAGE_PATH)); } else { - additionalProperties.put("packagePath", packagePath); + additionalProperties.put(PACKAGE_PATH, packagePath); } - if (additionalProperties.containsKey("srcBasePath")) { - this.setSrcBasePath((String) additionalProperties.get("srcBasePath")); + if (additionalProperties.containsKey(SRC_BASE_PATH)) { + this.setSrcBasePath((String) additionalProperties.get(SRC_BASE_PATH)); } else { - additionalProperties.put("srcBasePath", srcBasePath); + additionalProperties.put(SRC_BASE_PATH, srcBasePath); } if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { @@ -162,28 +167,24 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); } - if (additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) { - this.setModelPackage((String) additionalProperties.get(CodegenConstants.MODEL_PACKAGE)); - } else { + if (!additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) { additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage); } - if (additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) { - this.setApiPackage((String) additionalProperties.get(CodegenConstants.API_PACKAGE)); - } else { + if (!additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) { additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage); } - if (additionalProperties.containsKey("composerProjectName")) { - this.setComposerProjectName((String) additionalProperties.get("composerProjectName")); + if (additionalProperties.containsKey(COMPOSER_PROJECT_NAME)) { + this.setComposerProjectName((String) additionalProperties.get(COMPOSER_PROJECT_NAME)); } else { - additionalProperties.put("composerProjectName", composerProjectName); + additionalProperties.put(COMPOSER_PROJECT_NAME, composerProjectName); } - if (additionalProperties.containsKey("composerVendorName")) { - this.setComposerVendorName((String) additionalProperties.get("composerVendorName")); + if (additionalProperties.containsKey(COMPOSER_VENDOR_NAME)) { + this.setComposerVendorName((String) additionalProperties.get(COMPOSER_VENDOR_NAME)); } else { - additionalProperties.put("composerVendorName", composerVendorName); + additionalProperties.put(COMPOSER_VENDOR_NAME, composerVendorName); } if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_VERSION)) { @@ -191,6 +192,10 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { } else { additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); } + + if (additionalProperties.containsKey(VARIABLE_NAMING_CONVENTION)) { + this.setParameterNamingConvention((String) additionalProperties.get(VARIABLE_NAMING_CONVENTION)); + } additionalProperties.put("escapedInvokerPackage", invokerPackage.replace("\\", "\\\\")); @@ -286,7 +291,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { this.variableNamingConvention = variableNamingConvention; } - private void setComposerVendorName(String composerVendorName) { + public void setComposerVendorName(String composerVendorName) { this.composerVendorName = composerVendorName; } @@ -296,10 +301,6 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toVarName(String name) { - if (additionalProperties.containsKey("variableNamingConvention")) { - this.setParameterNamingConvention((String) additionalProperties.get("variableNamingConvention")); - } - // sanitize name name = sanitizeName(name); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java index 23364b5d9829..ad8fbc683fc7 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 @@ -2,6 +2,7 @@ package io.swagger.codegen.languages; 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; @@ -62,30 +63,31 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig "return", "def", "for", "lambda", "try")); cliOptions.clear(); - cliOptions.add(new CliOption("packageName", "python package name (convention: snake_case), default: swagger_client")); - cliOptions.add(new CliOption("packageVersion", "python package version, default: 1.0.0")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "python package name (convention: snake_case)," + + " default: swagger_client")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "python package version, default: 1.0.0")); } @Override public void processOpts() { super.processOpts(); - if (additionalProperties.containsKey("packageName")) { - setPackageName((String) additionalProperties.get("packageName")); + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); } else { setPackageName("swagger_client"); } - if (additionalProperties.containsKey("packageVersion")) { - setPackageVersion((String) additionalProperties.get("packageVersion")); + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { + setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); } else { setPackageVersion("1.0.0"); } - additionalProperties.put("packageName", packageName); - additionalProperties.put("packageVersion", packageVersion); + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); + additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); String swaggerFolder = 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 d4453fe41021..12dcedd36aed 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 @@ -16,6 +16,9 @@ import java.util.HashSet; import org.apache.commons.lang.StringUtils; public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { + public static final String GEM_NAME = "gemName"; + public static final String MODULE_NAME = "moduleName"; + public static final String GEM_VERSION = "gemVersion"; protected String gemName = null; protected String moduleName = null; protected String gemVersion = "1.0.0"; @@ -68,20 +71,20 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { // remove modelPackage and apiPackage added by default cliOptions.clear(); - cliOptions.add(new CliOption("gemName", "gem name (convention: underscore_case), default: swagger_client")); - cliOptions.add(new CliOption("moduleName", "top module name (convention: CamelCase, usually corresponding to gem name), default: SwaggerClient")); - cliOptions.add(new CliOption("gemVersion", "gem version, default: 1.0.0")); + cliOptions.add(new CliOption(GEM_NAME, "gem name (convention: underscore_case), default: swagger_client")); + cliOptions.add(new CliOption(MODULE_NAME, "top module name (convention: CamelCase, usually corresponding to gem name), default: SwaggerClient")); + cliOptions.add(new CliOption(GEM_VERSION, "gem version, default: 1.0.0")); } @Override public void processOpts() { super.processOpts(); - if (additionalProperties.containsKey("gemName")) { - setGemName((String) additionalProperties.get("gemName")); + if (additionalProperties.containsKey(GEM_NAME)) { + setGemName((String) additionalProperties.get(GEM_NAME)); } - if (additionalProperties.containsKey("moduleName")) { - setModuleName((String) additionalProperties.get("moduleName")); + if (additionalProperties.containsKey(MODULE_NAME)) { + setModuleName((String) additionalProperties.get(MODULE_NAME)); } if (gemName == null && moduleName == null) { @@ -93,14 +96,14 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { setModuleName(generateModuleName(gemName)); } - additionalProperties.put("gemName", gemName); - additionalProperties.put("moduleName", moduleName); + additionalProperties.put(GEM_NAME, gemName); + additionalProperties.put(MODULE_NAME, moduleName); - if (additionalProperties.containsKey("gemVersion")) { - setGemVersion((String) additionalProperties.get("gemVersion")); + if (additionalProperties.containsKey(GEM_VERSION)) { + setGemVersion((String) additionalProperties.get(GEM_VERSION)); } else { // not set, pass the default value to template - additionalProperties.put("gemVersion", gemVersion); + additionalProperties.put(GEM_VERSION, gemVersion); } // use constant model/api package (folder path) 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 b98d75f49e3a..b0fc57f0574e 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 @@ -1,9 +1,11 @@ package io.swagger.codegen.languages; import com.google.common.base.Predicate; + import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import io.swagger.codegen.*; +import io.swagger.models.Swagger; import io.swagger.models.Model; import io.swagger.models.Operation; import io.swagger.models.parameters.HeaderParameter; @@ -13,6 +15,7 @@ import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.WordUtils; import javax.annotation.Nullable; import java.util.*; @@ -234,7 +237,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { List values = (List) codegenProperty.allowableValues.get("values"); for (String value : values) { Map map = new HashMap(); - map.put("enum", StringUtils.capitalize(value)); + map.put("enum", toSwiftyEnumName(value)); map.put("raw", value); swiftEnums.add(map); } @@ -248,6 +251,16 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { return codegenProperty; } + public String toSwiftyEnumName(String value) { + // Prevent from breaking properly cased identifier + if (value.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) { + return value; + } + char[] separators = {'-', '_', ' '}; + return WordUtils.capitalizeFully(StringUtils.lowerCase(value), separators).replaceAll("[-_ ]", ""); + } + + @Override public String toApiName(String name) { if(name.length() == 0) @@ -256,7 +269,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { } @Override - public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions) { + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { path = normalizePath(path); List parameters = operation.getParameters(); parameters = Lists.newArrayList(Iterators.filter(parameters.iterator(), new Predicate() { @@ -266,7 +279,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { } })); operation.setParameters(parameters); - return super.fromOperation(path, httpMethod, operation, definitions); + return super.fromOperation(path, httpMethod, operation, definitions, swagger); } private static String normalizePath(String path) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java index 65fdbb6f312f..4747b8bba880 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java @@ -1,7 +1,6 @@ package io.swagger.codegen.languages; import io.swagger.codegen.SupportingFile; - import java.io.File; public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCodegen { @@ -12,7 +11,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode } public String getHelp() { - return "Generates a TypeScript AngurlarJS client library."; + return "Generates a TypeScript AngularJS client library."; } public TypeScriptAngularClientCodegen() { @@ -25,4 +24,4 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode modelPackage = "API.Client"; supportingFiles.add(new SupportingFile("api.d.mustache", apiPackage().replace('.', File.separatorChar), "api.d.ts")); } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/Groovy/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Groovy/build.gradle.mustache index d98f375c61d6..342094c90ec9 100644 --- a/modules/swagger-codegen/src/main/resources/Groovy/build.gradle.mustache +++ b/modules/swagger-codegen/src/main/resources/Groovy/build.gradle.mustache @@ -24,9 +24,6 @@ repositories { dependencies { groovy "org.codehaus.groovy:groovy-all:2.0.5" compile 'org.codehaus.groovy.modules.http-builder:http-builder:0.6' - - } task wrapper(type: Wrapper) { gradleVersion = '1.6' } - diff --git a/modules/swagger-codegen/src/main/resources/Java/JSON.mustache b/modules/swagger-codegen/src/main/resources/Java/JSON.mustache index 7689856f5de5..43b38f6e21d3 100644 --- a/modules/swagger-codegen/src/main/resources/Java/JSON.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/JSON.mustache @@ -12,12 +12,13 @@ public class JSON { public JSON() { mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); mapper.registerModule(new JodaModule()); - } + } /** * Serialize the given Java object into JSON string. 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 10a43d97de07..9cc1324acb62 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 @@ -23,10 +23,9 @@ public class JSON { public JSON(ApiClient apiClient) { this.apiClient = apiClient; gson = new GsonBuilder() - .serializeNulls() .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) .create(); - } + } public Gson getGson() { return gson; diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache index 4046f9f107ca..eaca662c5838 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache @@ -41,7 +41,7 @@ public class ApiClient { apiAuthorizations = new LinkedHashMap(); createDefaultAdapter(); } - + public ApiClient(String[] authNames) { this(); okClient = new OkHttpClient(); @@ -49,16 +49,17 @@ public class ApiClient { for(String authName : authNames) { if (apiAuthorizations.containsKey(authName)) { throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations"); - } - Interceptor auth;{{#authMethods}} - if (authName == "{{name}}") { {{#isBasic}} + }{{#hasAuthMethods}} + Interceptor auth; + {{#authMethods}}if (authName == "{{name}}") { {{#isBasic}} auth = new HttpBasicAuth();{{/isBasic}}{{#isApiKey}} auth = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}");{{/isApiKey}}{{#isOAuth}} - auth = new OAuth(OAuthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{^-first}}, {{/-first}}{{this}}{{/scopes}}");{{/isOAuth}} + auth = new OAuth(OAuthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{scope}}{{#hasMore}}, {{/hasMore}}{{/scopes}}");{{/isOAuth}} } else {{/authMethods}}{ throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); } - apiAuthorizations.put(authName, auth); + apiAuthorizations.put(authName, auth);{{/hasAuthMethods}}{{^hasAuthMethods}} + throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names");{{/hasAuthMethods}} } addAuthsToOkClient(okClient); } diff --git a/modules/swagger-codegen/src/main/resources/Java/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/pom.mustache index 315ea9e5b924..3f4d9d9a55b9 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pom.mustache @@ -6,11 +6,7 @@ jar {{artifactId}} {{artifactVersion}} - - scm:git:git@github.com:swagger-api/swagger-mustache.git - scm:git:git@github.com:swagger-api/swagger-codegen.git - https://github.com/swagger-api/swagger-codegen - + 2.2.0 @@ -161,7 +157,7 @@ - 1.5.0 + 1.5.4 1.18 2.4.2 2.3 diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache index 20d5aaf30c64..0f489f4923dd 100644 --- a/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache @@ -83,7 +83,7 @@ 1.0.0 - 1.5.3 + 1.5.4 9.2.9.v20150224 1.0.1 4.8.2 diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/README.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/README.mustache index 3f0809d4734d..00431f63dbc9 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/README.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/README.mustache @@ -6,3 +6,9 @@ This server was generated by the [swagger-codegen](https://github.com/swagger-ap is an example of building a swagger-enabled JAX-RS server. This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework. + +To run the server, please execute the following: + +``` +mvn clean package jetty:run +``` diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/allowableValues.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/allowableValues.mustache new file mode 100644 index 000000000000..a48256d027a1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/allowableValues.mustache @@ -0,0 +1 @@ +{{#allowableValues}}allowableValues="{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}{{^values}}range=[{{#min}}{{.}}{{/min}}{{^min}}-infinity{{/min}}, {{#max}}{{.}}{{/max}}{{^max}}infinity{{/max}}]{{/values}}"{{/allowableValues}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache index 65dfa6835bfd..e919fa7ce712 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache @@ -22,7 +22,7 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; import javax.ws.rs.*; -@Path("/{{baseName}}") +@Path("{{basePathWithoutHost}}/{{baseName}}") {{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} {{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} @io.swagger.annotations.Api(value = "/{{baseName}}", description = "the {{baseName}} API") @@ -37,7 +37,13 @@ public class {{classname}} { {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} {{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} {{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} - @io.swagger.annotations.ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}) + @io.swagger.annotations.ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}{{#hasAuthMethods}}, authorizations = { + {{#authMethods}}@io.swagger.annotations.Authorization(value = "{{name}}"{{#isOAuth}}, scopes = { + {{#scopes}}@io.swagger.annotations.AuthorizationScope(scope = "{{scope}}", description = "{{description}}"){{#hasMore}}, + {{/hasMore}}{{/scopes}} + }{{/isOAuth}}){{#hasMore}}, + {{/hasMore}}{{/authMethods}} + }{{/hasAuthMethods}}) @io.swagger.annotations.ApiResponses(value = { {{#responses}} @io.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}){{#hasMore}}, {{/hasMore}}{{/responses}} }) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/bodyParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/bodyParams.mustache index 86546afb9ca4..2b28441d3d05 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/bodyParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/bodyParams.mustache @@ -1 +1 @@ -{{#isBodyParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file +{{#isBodyParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache index 1bae4717f4dc..632d39cf23ec 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache @@ -1,2 +1,2 @@ -{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@FormParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}} @FormDataParam("file") InputStream inputStream, +{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@FormParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}} @FormDataParam("file") InputStream inputStream, @FormDataParam("file") FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/headerParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/headerParams.mustache index 84a801e48acf..1360d796826b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/headerParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/headerParams.mustache @@ -1 +1 @@ -{{#isHeaderParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@HeaderParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file +{{#isHeaderParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@HeaderParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pathParams.mustache index 5bb31c704f75..8d80210b4b41 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pathParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pathParams.mustache @@ -1 +1 @@ -{{#isPathParam}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}} {{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @PathParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file +{{#isPathParam}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @PathParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache index ba58d23ca7f0..b8426a0a6931 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache @@ -168,7 +168,7 @@ - 1.5.3 + 1.5.4 9.2.9.v20150224 1.18.1 1.6.3 diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/queryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/queryParams.mustache index 067493867c9d..342da154a877 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/queryParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/queryParams.mustache @@ -1 +1 @@ -{{#isQueryParam}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @QueryParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file +{{#isQueryParam}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @QueryParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache index 695d1c5525b6..6eb6358a7026 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache @@ -10,6 +10,8 @@ import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.Authorization; +import io.swagger.annotations.AuthorizationScope; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -35,7 +37,13 @@ import static org.springframework.http.MediaType.*; public class {{classname}} { {{#operation}} - @ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}) + @ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}{{#hasAuthMethods}}, authorizations = { + {{#authMethods}}@Authorization(value = "{{name}}"{{#isOAuth}}, scopes = { + {{#scopes}}@AuthorizationScope(scope = "{{scope}}", description = "{{description}}"){{#hasMore}}, + {{/hasMore}}{{/scopes}} + }{{/isOAuth}}){{#hasMore}}, + {{/hasMore}}{{/authMethods}} + }{{/hasAuthMethods}}) @ApiResponses(value = { {{#responses}} @ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}},{{/hasMore}}{{/responses}} }) @RequestMapping(value = "{{path}}", diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache index ffbb0e435161..c4a71c199ce6 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache @@ -150,7 +150,7 @@ - 1.5.3 + 1.5.4 9.2.9.v20150224 1.13 1.6.3 diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache index b9fd8603baaa..b5c9997ce0f7 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache @@ -217,7 +217,7 @@ 2.3.9 1.2 2.2 - 1.5.3 + 1.5.4 1.0.0 4.8.1 diff --git a/modules/swagger-codegen/src/main/resources/android-java/pom.mustache b/modules/swagger-codegen/src/main/resources/android-java/pom.mustache index 05388db4e117..ad093828ecc2 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/pom.mustache @@ -145,7 +145,7 @@ - 1.5.0 + 1.5.4 2.3.1 4.8.1 1.0.0 diff --git a/modules/swagger-codegen/src/main/resources/codegen/pom.mustache b/modules/swagger-codegen/src/main/resources/codegen/pom.mustache index ad480b9b331b..29a980a50914 100644 --- a/modules/swagger-codegen/src/main/resources/codegen/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/codegen/pom.mustache @@ -95,7 +95,7 @@ - 2.1.2-M1 + 2.1.3 1.0.0 4.8.1 diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache index ae864113a9c5..f6dd29333316 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -214,12 +214,14 @@ namespace {{packageName}}.Client /// /// Deserialize the JSON string into a proper object. /// - /// HTTP body (e.g. string, JSON). + /// The HTTP response. /// Object type. - /// /// Object representation of the JSON string. - public object Deserialize(string content, Type type, IList headers=null) + public object Deserialize(IRestResponse response, Type type) { + byte[] data = response.RawBytes; + string content = response.Content; + IList headers = response.Headers; if (type == typeof(Object)) // return an object { return content; @@ -227,21 +229,22 @@ namespace {{packageName}}.Client if (type == typeof(Stream)) { - var filePath = String.IsNullOrEmpty(Configuration.TempFolderPath) - ? Path.GetTempPath() - : Configuration.TempFolderPath; - - var fileName = filePath + Guid.NewGuid(); if (headers != null) { + var filePath = String.IsNullOrEmpty(Configuration.TempFolderPath) + ? Path.GetTempPath() + : Configuration.TempFolderPath; var regex = new Regex(@"Content-Disposition:.*filename=['""]?([^'""\s]+)['""]?$"); var match = regex.Match(headers.ToString()); if (match.Success) - fileName = filePath + match.Value.Replace("\"", "").Replace("'", ""); + { + string fileName = filePath + match.Value.Replace("\"", "").Replace("'", ""); + File.WriteAllBytes(fileName, data); + return new FileStream(fileName, FileMode.Open); + } } - File.WriteAllText(fileName, content); - return new FileStream(fileName, FileMode.Open); - + var stream = new MemoryStream(data); + return stream; } if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index f54f42d2eca6..6708fa1e16db 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -102,7 +102,7 @@ namespace {{packageName}}.Api if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{nickname}}"); {{/required}}{{/allParams}} - var path = "{{path}}"; + var path_ = "{{path}}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -137,14 +137,14 @@ namespace {{packageName}}.Api String[] authSettings = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.ErrorMessage, response.ErrorMessage); - {{#returnType}}return ({{{returnType}}}) ApiClient.Deserialize(response.Content, typeof({{{returnType}}}), response.Headers);{{/returnType}}{{^returnType}}return;{{/returnType}} + {{#returnType}}return ({{{returnType}}}) ApiClient.Deserialize(response, typeof({{{returnType}}}));{{/returnType}}{{^returnType}}return;{{/returnType}} } /// @@ -158,7 +158,7 @@ namespace {{packageName}}.Api if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{nickname}}"); {{/required}}{{/allParams}} - var path = "{{path}}"; + var path_ = "{{path}}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -193,11 +193,11 @@ namespace {{packageName}}.Api String[] authSettings = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.Content, response.Content); - {{#returnType}}return ({{{returnType}}}) ApiClient.Deserialize(response.Content, typeof({{{returnType}}}), response.Headers);{{/returnType}}{{^returnType}} + {{#returnType}}return ({{{returnType}}}) ApiClient.Deserialize(response, typeof({{{returnType}}}));{{/returnType}}{{^returnType}} return;{{/returnType}} } {{/operation}} diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache index ac07a3fd9f55..9473309ff83a 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache @@ -87,6 +87,13 @@ {{/hasQueryParams}} + {{#hasFormParams}} +

Form parameters

+
+ {{#formParams}}{{>formParam}}{{/formParams}} +
+ {{/hasFormParams}} + diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/style.css.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/style.css.mustache index d69f0e7b1617..8d9a5755d7bb 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/style.css.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/style.css.mustache @@ -124,6 +124,20 @@ code { font-style: italic; } +.param-enum-header { +width: 700px; +padding: 0 0 0 60px; +color: #777; +font-weight: bold; +} + +.param-enum { +width: 700px; +padding: 0 0 0 80px; +color: #777; +font-style: italic; +} + .field-label { padding: 0; margin: 0; diff --git a/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache index f3fca3f41a75..e740ea593ab0 100644 --- a/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache @@ -28,7 +28,7 @@ sub to_hash { sub TO_JSON { my $self = shift; my $_data = {}; - foreach my $_key (keys $self->get_attribute_map) { + foreach my $_key (keys %{$self->get_attribute_map}) { if (defined $self->{$_key}) { $_data->{$self->get_attribute_map->{$_key}} = $self->{$_key}; } @@ -40,7 +40,7 @@ sub TO_JSON { sub from_hash { my ($self, $hash) = @_; # loop through attributes and use swagger_types to deserialize the data - while ( my ($_key, $_type) = each $self->get_swagger_types ) { + while ( my ($_key, $_type) = each %{$self->get_swagger_types} ) { if ($_type =~ /^array\[/i) { # array my $_subclass = substr($_type, 6, -1); my @_array = (); diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index 9db41df2aeec..e2193b1d754f 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -239,9 +239,14 @@ class ApiClient $data = $http_body; } } else { + $data = json_decode($http_body); + if (json_last_error() > 0) { // if response is a string + $data = $http_body; + } + throw new ApiException( "[".$response_info['http_code']."] Error connecting to the API ($url)", - $response_info['http_code'], $http_header, $http_body + $response_info['http_code'], $http_header, $data ); } return array($data, $http_header); diff --git a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache index 79d1b4fe0a15..b9022f42a901 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache @@ -46,30 +46,30 @@ use \Exception; class ApiException extends Exception { - /** - * The HTTP body of the server response. - * @var string + /** + * The HTTP body of the server response either as Json or string. + * @var mixed */ protected $responseBody; - + /** * The HTTP header of the server response. * @var string[] */ protected $responseHeaders; - + /** * The deserialized response object * @var $responseObject; */ protected $responseObject; - + /** * Constructor * @param string $message Error message - * @param string $code HTTP status code + * @param int $code HTTP status code * @param string $responseHeaders HTTP response header - * @param string $responseBody Deseralized response object + * @param mixed $responseBody HTTP body of the server response either as Json or string */ public function __construct($message="", $code=0, $responseHeaders=null, $responseBody=null) { @@ -77,7 +77,7 @@ class ApiException extends Exception $this->responseHeaders = $responseHeaders; $this->responseBody = $responseBody; } - + /** * Gets the HTTP response header * @@ -87,17 +87,17 @@ class ApiException extends Exception { return $this->responseHeaders; } - + /** - * Gets the HTTP response body + * Gets the HTTP body of the server response either as Json or string * - * @return string HTTP response body + * @return mixed HTTP body of the server response either as Json or string */ public function getResponseBody() { return $this->responseBody; } - + /** * Sets the deseralized response object (during deserialization) * @param mixed $obj Deserialized response object diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index db1d4c8cb4f2..78eaeb7cc6bf 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -140,7 +140,18 @@ use \{{invokerPackage}}\ObjectSerializer; }{{/pathParams}} {{#formParams}}// form params if (${{paramName}} !== null) { - $formParams['{{baseName}}'] = {{#isFile}}'@' . {{/isFile}}$this->apiClient->getSerializer()->toFormValue(${{paramName}}); + {{#isFile}} + // PHP 5.5 introduced a CurlFile object that deprecates the old @filename syntax + // See: https://wiki.php.net/rfc/curl-file-upload + if (function_exists('curl_file_create')) { + $formParams['{{baseName}}'] = curl_file_create($this->apiClient->getSerializer()->toFormValue(${{paramName}})); + } else { + $formParams['{{baseName}}'] = '@' . $this->apiClient->getSerializer()->toFormValue(${{paramName}}); + } + {{/isFile}} + {{^isFile}} + $formParams['{{baseName}}'] = $this->apiClient->getSerializer()->toFormValue(${{paramName}}); + {{/isFile}} }{{/formParams}} {{#bodyParams}}// body params $_tempBody = null; 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 77b320d07f43..ccf6db4a4fd1 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache @@ -60,14 +60,13 @@ module {{moduleName}} # return the object in the form of hash def to_hash hash = {} - self.class.attribute_map.each_pair do |key, value| - if self.send(key).is_a?(Array) - next if self.send(key).empty? - hash[value] = self.send(key).select{|v| !v.nil?}.map{ |v| _to_hash v} unless self.send(key).nil? + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + next if value.nil? + if value.is_a?(Array) + hash[param] = value.compact.map{ |v| _to_hash(v) } else - unless (_tmp_value = _to_hash self.send(key)).nil? - hash[value] = _tmp_value - end + hash[param] = _to_hash(value) end end hash diff --git a/modules/swagger-codegen/src/main/resources/scala/pom.mustache b/modules/swagger-codegen/src/main/resources/scala/pom.mustache index 5fc849ea87df..7a2e36c935ab 100644 --- a/modules/swagger-codegen/src/main/resources/scala/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/pom.mustache @@ -210,7 +210,7 @@ 1.2 2.2 1.19 - 1.5.3 + 1.5.4 1.0.5 1.0.0 2.4.2 diff --git a/modules/swagger-codegen/src/main/resources/scalatra/api.mustache b/modules/swagger-codegen/src/main/resources/scalatra/api.mustache index 54710361fe9a..b6749641e545 100644 --- a/modules/swagger-codegen/src/main/resources/scalatra/api.mustache +++ b/modules/swagger-codegen/src/main/resources/scalatra/api.mustache @@ -33,57 +33,16 @@ class {{classname}} (implicit val swagger: Swagger) extends ScalatraServlet val {{nickname}}Operation = (apiOperation[{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Unit{{/returnType}}]("{{nickname}}") summary "{{{summary}}}" - parameters( - {{#allParams}}{{#isQueryParam}}queryParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}} - {{/isQueryParam}} - {{#isPathParam}}pathParam[{{dataType}}]("{{paramName}}").description(""){{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}} - {{/isPathParam}} - {{#isHeaderParam}}headerParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}} - {{/isHeaderParam}} - {{#isBodyParam}}bodyParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}} - {{/isBodyParam}} - {{#isFormParam}}formParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}} - {{/isFormParam}} - {{#hasMore}},{{/hasMore}} - {{/allParams}}) + parameters({{#allParams}}{{>queryParam}}{{>pathParam}}{{>bodyParam}}{{>formParam}}{{#hasMore}}, + {{/hasMore}}{{/allParams}}) ) {{httpMethod}}("{{path}}",operation({{nickname}}Operation)) { {{#allParams}} - {{#isFile}} - val {{paramName}} = fileParams("{{paramName}}") - {{/isFile}} - {{^isFile}} - {{#isPathParam}} - val {{paramName}} = params.getOrElse("{{paramName}}", halt(400)) - {{/isPathParam}} - - {{#isQueryParam}} - {{#collectionFormat}}val {{paramName}}String = params.getAs[String]("{{paramName}}") - val {{paramName}} = if("{{collectionFormat}}".equals("default")) { - {{paramName}}String match { - case Some(str) => str.split(",") - case None => List() - } - } - else - List() - {{/collectionFormat}} - {{^collectionFormat}}val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}"){{/collectionFormat}} - - {{/isQueryParam}} - - {{#isHeaderParam}} - val {{paramName}} = request.getHeader("{{paramName}}") - {{/isHeaderParam}} - - {{#isFormParam}} - val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}") - {{/isFormParam}} - - {{#isBodyParam}} - val {{paramName}} = parsedBody.extract[{{dataType}}] - {{/isBodyParam}} + {{#isFile}}val {{paramName}} = fileParams("{{paramName}}"){{/isFile}} + {{^isFile}}{{#isPathParam}} + val {{paramName}} = params.getOrElse("{{paramName}}", halt(400)){{/isPathParam}} + {{>queryParamOperation}}{{>headerParamOperation}}{{>formParamMustache}}{{>bodyParam}} {{/isFile}} println("{{paramName}}: " + {{paramName}}) {{/allParams}} diff --git a/modules/swagger-codegen/src/main/resources/scalatra/bodyParam.mustache b/modules/swagger-codegen/src/main/resources/scalatra/bodyParam.mustache new file mode 100644 index 000000000000..07a90aa23cbc --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scalatra/bodyParam.mustache @@ -0,0 +1 @@ +{{#isBodyParam}}bodyParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/scalatra/bodyParamOperation.mustache b/modules/swagger-codegen/src/main/resources/scalatra/bodyParamOperation.mustache new file mode 100644 index 000000000000..cfb2bf49d235 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scalatra/bodyParamOperation.mustache @@ -0,0 +1,3 @@ + {{#isBodyParam}} + val {{paramName}} = parsedBody.extract[{{dataType}}] + {{/isBodyParam}} diff --git a/modules/swagger-codegen/src/main/resources/scalatra/formParam.mustache b/modules/swagger-codegen/src/main/resources/scalatra/formParam.mustache new file mode 100644 index 000000000000..1afcf12ccc6a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scalatra/formParam.mustache @@ -0,0 +1 @@ +{{#isFormParam}}formParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/scalatra/formParamMustache.mustache b/modules/swagger-codegen/src/main/resources/scalatra/formParamMustache.mustache new file mode 100644 index 000000000000..29c571ee2efd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scalatra/formParamMustache.mustache @@ -0,0 +1,3 @@ + {{#isFormParam}} + val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}") + {{/isFormParam}} diff --git a/modules/swagger-codegen/src/main/resources/scalatra/headerParam.mustache b/modules/swagger-codegen/src/main/resources/scalatra/headerParam.mustache new file mode 100644 index 000000000000..798bb0fe6d5d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scalatra/headerParam.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}headerParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/scalatra/headerParamOperation.mustache b/modules/swagger-codegen/src/main/resources/scalatra/headerParamOperation.mustache new file mode 100644 index 000000000000..7f8f5286392d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scalatra/headerParamOperation.mustache @@ -0,0 +1,3 @@ + {{#isHeaderParam}} + val {{paramName}} = request.getHeader("{{paramName}}") + {{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/scalatra/pathParam.mustache b/modules/swagger-codegen/src/main/resources/scalatra/pathParam.mustache new file mode 100644 index 000000000000..ae72aa8ec74f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scalatra/pathParam.mustache @@ -0,0 +1 @@ +{{#isPathParam}}pathParam[{{dataType}}]("{{paramName}}").description(""){{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/scalatra/queryParam.mustache b/modules/swagger-codegen/src/main/resources/scalatra/queryParam.mustache new file mode 100644 index 000000000000..79af702d0f04 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scalatra/queryParam.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}queryParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/scalatra/queryParamOperation.mustache b/modules/swagger-codegen/src/main/resources/scalatra/queryParamOperation.mustache new file mode 100644 index 000000000000..832bbed20300 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scalatra/queryParamOperation.mustache @@ -0,0 +1,13 @@ + {{#isQueryParam}} + {{#collectionFormat}}val {{paramName}}String = params.getAs[String]("{{paramName}}") + val {{paramName}} = if("{{collectionFormat}}".equals("default")) { + {{paramName}}String match { + case Some(str) => str.split(",") + case None => List() + } + } + else + List() + {{/collectionFormat}} + {{^collectionFormat}}val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}"){{/collectionFormat}} + {{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/swagger-static/assets/css/style.css b/modules/swagger-codegen/src/main/resources/swagger-static/assets/css/style.css index f14f6bdb62c5..b596c11a535f 100644 --- a/modules/swagger-codegen/src/main/resources/swagger-static/assets/css/style.css +++ b/modules/swagger-codegen/src/main/resources/swagger-static/assets/css/style.css @@ -100,6 +100,10 @@ float: left; } +.param-enum { + margin-left: 20px; +} + .section-header { border-bottom: 2px; font-weight: bold; diff --git a/modules/swagger-codegen/src/main/resources/swagger-static/model.mustache b/modules/swagger-codegen/src/main/resources/swagger-static/model.mustache index a9a39ab6e91c..e6f85872c766 100644 --- a/modules/swagger-codegen/src/main/resources/swagger-static/model.mustache +++ b/modules/swagger-codegen/src/main/resources/swagger-static/model.mustache @@ -5,7 +5,16 @@ {{#vars}}
  • {{name}} : {{datatype}} -
    {{description}} +
    {{description}} + {{#isEnum}} +
    +
    Enum: + {{#_enum}} +
    {{this}}
    + {{/_enum}} + +
    + {{/isEnum}}
{{/vars}} diff --git a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache index 21791168ab2f..dbc25584886c 100644 --- a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache @@ -75,29 +75,26 @@ class AlamofireRequestBuilder: RequestBuilder { request.authenticate(usingCredential: credential) } - request.responseJSON(options: .AllowFragments) { (req, res, result) in + request.responseJSON(options: .AllowFragments) { response in managerStore.removeValueForKey(managerId) - if result.isFailure { - completion(response: nil, erorr: result.error) + if response.result.isFailure { + completion(response: nil, erorr: response.result.error) return } if () is T { - let response = Response(response: res!, body: () as! T) - completion(response: response, erorr: nil) + completion(response: Response(response: response.response!, body: () as! T), erorr: nil) return } - if let json: AnyObject = result.value { + if let json: AnyObject = response.result.value { let body = Decoders.decode(clazz: T.self, source: json) - let response = Response(response: res!, body: body) - completion(response: response, erorr: nil) + completion(response: Response(response: response.response!, body: body), erorr: 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 - let response = Response(response: res!, body: "" as! T) - completion(response: response, erorr: nil) + completion(response: Response(response: response.response!, body: "" as! T), erorr: nil) return } @@ -113,4 +110,3 @@ class AlamofireRequestBuilder: RequestBuilder { return httpHeaders } } - diff --git a/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache b/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache index e36e0eedabdc..c27fd0c14d12 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache @@ -1,2 +1,2 @@ -github "Alamofire/Alamofire" >= 2.0.0{{#usePromiseKit}} +github "Alamofire/Alamofire" >= 3.0.0{{#usePromiseKit}} github "mxcl/PromiseKit" >=1.5.3{{/usePromiseKit}} diff --git a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache index e359edaff671..5cf337ad6f2a 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache @@ -16,5 +16,5 @@ Pod::Spec.new do |s| s.documentation_url = '{{podDocumentationURL}}'{{/podDocumentationURL}} s.source_files = '{{projectName}}/Classes/Swaggers/**/*.swift'{{#usePromiseKit}} s.dependency 'PromiseKit', '~> 2.1'{{/usePromiseKit}} - s.dependency 'Alamofire', '~> 2.0.0' + s.dependency 'Alamofire', '~> 3.0.0' end diff --git a/modules/swagger-codegen/src/main/resources/swift/model.mustache b/modules/swagger-codegen/src/main/resources/swift/model.mustache index a2510a26dd03..892a3a59f966 100644 --- a/modules/swagger-codegen/src/main/resources/swift/model.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/model.mustache @@ -21,6 +21,8 @@ public class {{classname}}: JSONEncodable { {{/description}}public var {{name}}: {{{datatype}}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{#required}}!{{/required}}{{/unwrapRequired}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{/isEnum}} {{/vars}} + public init() {} + // MARK: JSONEncodable func encodeToJSON() -> AnyObject { var nillableDictionary = [String:AnyObject?](){{#vars}}{{#isNotContainer}}{{#isPrimitiveType}}{{^isEnum}} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/AbstractOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/AbstractOptionsTest.java new file mode 100644 index 000000000000..8aa497417e91 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/AbstractOptionsTest.java @@ -0,0 +1,57 @@ +package io.swagger.codegen; + +import com.google.common.base.Function; +import com.google.common.collect.Lists; +import mockit.FullVerifications; +import org.apache.commons.lang3.StringUtils; +import org.testng.Assert; +import org.testng.annotations.Test; + +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public abstract class AbstractOptionsTest { + + @Test + public void checkOptionsProcessing() { + getCodegenConfig().additionalProperties().putAll(getAvaliableOptions()); + setExpectations(); + + getCodegenConfig().processOpts(); + + new FullVerifications() {{ + }}; + } + + @Test(description = "check if all options described in documentation are presented in test case") + public void checkOptionsHelp() { + final List cliOptions = Lists.transform(getCodegenConfig().cliOptions(), getCliOptionTransformer()); + final Set testOptions = getAvaliableOptions().keySet(); + final Set skipped = new HashSet(cliOptions); + skipped.removeAll(testOptions); + if (!skipped.isEmpty()) { + Assert.fail(String.format("These options weren't checked: %s.", StringUtils.join(skipped, ", "))); + } + final Set undocumented = new HashSet(testOptions); + undocumented.removeAll(cliOptions); + if (!undocumented.isEmpty()) { + Assert.fail(String.format("These options weren't documented: %s.", StringUtils.join(undocumented, ", "))); + } + } + + private Function getCliOptionTransformer() { + return new Function() { + public String apply(CliOption option) { + return option.getOpt(); + } + }; + } + + protected abstract CodegenConfig getCodegenConfig(); + + protected abstract void setExpectations(); + + protected abstract Map getAvaliableOptions(); +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java index ee70b427bfdf..0fa8953e7bf5 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java @@ -139,4 +139,52 @@ public class CodegenTest { Assert.assertTrue(op.bodyParam.isBinary); Assert.assertTrue(op.responses.get(0).isBinary); } + + @Test(description = "use operation consumes and produces") + public void localConsumesAndProducesTest() { + final Swagger model = new SwaggerParser().read("src/test/resources/2_0/globalConsumesAndProduces.json"); + final DefaultCodegen codegen = new DefaultCodegen(); + final String path = "/tests/localConsumesAndProduces"; + final Operation p = model.getPaths().get(path).getGet(); + CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions(), model); + + Assert.assertTrue(op.hasConsumes); + Assert.assertEquals(op.consumes.size(), 1); + Assert.assertEquals(op.consumes.get(0).get("mediaType"), "application/json"); + Assert.assertTrue(op.hasProduces); + Assert.assertEquals(op.produces.size(), 1); + Assert.assertEquals(op.produces.get(0).get("mediaType"), "application/json"); + } + + @Test(description = "use spec consumes and produces") + public void globalConsumesAndProducesTest() { + final Swagger model = new SwaggerParser().read("src/test/resources/2_0/globalConsumesAndProduces.json"); + final DefaultCodegen codegen = new DefaultCodegen(); + final String path = "/tests/globalConsumesAndProduces"; + final Operation p = model.getPaths().get(path).getGet(); + CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions(), model); + + Assert.assertTrue(op.hasConsumes); + Assert.assertEquals(op.consumes.size(), 1); + Assert.assertEquals(op.consumes.get(0).get("mediaType"), "application/global_consumes"); + Assert.assertTrue(op.hasProduces); + Assert.assertEquals(op.produces.size(), 1); + Assert.assertEquals(op.produces.get(0).get("mediaType"), "application/global_produces"); + } + + @Test(description = "use operation consumes and produces (reset in operation with empty array)") + public void localResetConsumesAndProducesTest() { + final Swagger model = new SwaggerParser().read("src/test/resources/2_0/globalConsumesAndProduces.json"); + final DefaultCodegen codegen = new DefaultCodegen(); + final String path = "/tests/localResetConsumesAndProduces"; + final Operation p = model.getPaths().get(path).getGet(); + CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions(), model); + + Assert.assertNotNull(op); + Assert.assertFalse(op.hasConsumes); + Assert.assertNull(op.consumes); + Assert.assertFalse(op.hasProduces); + Assert.assertNull(op.produces); + + } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/InlineModelResolverTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/InlineModelResolverTest.java new file mode 100644 index 000000000000..fa1bf8bab401 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/InlineModelResolverTest.java @@ -0,0 +1,301 @@ +package io.swagger.codegen; + + +import io.swagger.models.*; +import io.swagger.models.parameters.BodyParameter; +import io.swagger.models.parameters.Parameter; +import io.swagger.models.properties.*; +import io.swagger.util.Json; +import org.testng.annotations.Test; + +import java.util.Map; + +import static org.testng.AssertJUnit.*; + +public class InlineModelResolverTest { + @Test + public void resolveInlineModelTest() throws Exception { + Swagger swagger = new Swagger(); + + swagger.addDefinition("User", new ModelImpl() + .name("user") + .description("a common user") + .property("name", new StringProperty()) + .property("address", new ObjectProperty() + .title("title") + ._default("default") + .access("access") + .readOnly(false) + .required(true) + .description("description") + .name("name") + .property("street", new StringProperty()) + .property("city", new StringProperty()))); + + new InlineModelResolver().flatten(swagger); + + ModelImpl user = (ModelImpl)swagger.getDefinitions().get("User"); + + assertNotNull(user); + assertTrue(user.getProperties().get("address") instanceof RefProperty); + + ModelImpl address = (ModelImpl)swagger.getDefinitions().get("User_address"); + assertNotNull(address); + assertNotNull(address.getProperties().get("city")); + assertNotNull(address.getProperties().get("street")); + } + + @Test + public void testInlineResponseModel() throws Exception { + Swagger swagger = new Swagger(); + + swagger.path("/foo/bar", new Path() + .get(new Operation() + .response(200, new Response() + .description("it works!") + .schema(new ObjectProperty() + .property("name", new StringProperty()))))) + .path("/foo/baz", new Path() + .get(new Operation() + .response(200, new Response() + .vendorExtension("x-foo", "bar") + .description("it works!") + .schema(new ObjectProperty() + .property("name", new StringProperty()))))); + new InlineModelResolver().flatten(swagger); + + Map responses = swagger.getPaths().get("/foo/bar").getGet().getResponses(); + + Response response = responses.get("200"); + assertNotNull(response); + assertTrue(response.getSchema() instanceof RefProperty); + + ModelImpl model = (ModelImpl)swagger.getDefinitions().get("inline_response_200"); + assertTrue(model.getProperties().size() == 1); + assertNotNull(model.getProperties().get("name")); + } + + @Test + public void resolveInlineArrayModel() throws Exception { + Swagger swagger = new Swagger(); + + swagger.addDefinition("User", new ArrayModel() + .items(new ObjectProperty() + .title("title") + ._default("default") + .access("access") + .readOnly(false) + .required(true) + .description("description") + .name("name") + .property("street", new StringProperty()) + .property("city", new StringProperty()))); + + new InlineModelResolver().flatten(swagger); + + Model model = swagger.getDefinitions().get("User"); + assertTrue(model instanceof ArrayModel); + + Model user = swagger.getDefinitions().get("User_inner"); + assertNotNull(user); + assertEquals("description", user.getDescription()); + } + + @Test + public void resolveInlineBodyParameter() throws Exception { + Swagger swagger = new Swagger(); + + swagger.path("/hello", new Path() + .get(new Operation() + .parameter(new BodyParameter() + .name("body") + .schema(new ModelImpl() + .property("address", new ObjectProperty() + .property("street", new StringProperty())) + .property("name", new StringProperty()))))); + + new InlineModelResolver().flatten(swagger); + + Operation operation = swagger.getPaths().get("/hello").getGet(); + BodyParameter bp = (BodyParameter)operation.getParameters().get(0); + assertTrue(bp.getSchema() instanceof RefModel); + + Model body = swagger.getDefinitions().get("body"); + assertTrue(body instanceof ModelImpl); + + ModelImpl impl = (ModelImpl) body; + assertNotNull(impl.getProperties().get("address")); + } + + @Test + public void resolveInlineArrayBodyParameter() throws Exception { + Swagger swagger = new Swagger(); + + swagger.path("/hello", new Path() + .get(new Operation() + .parameter(new BodyParameter() + .name("body") + .schema(new ArrayModel() + .items(new ObjectProperty() + .property("address", new ObjectProperty() + .property("street", new StringProperty()))))))); + + new InlineModelResolver().flatten(swagger); + + Parameter param = swagger.getPaths().get("/hello").getGet().getParameters().get(0); + assertTrue(param instanceof BodyParameter); + + BodyParameter bp = (BodyParameter) param; + Model schema = bp.getSchema(); + + assertTrue(schema instanceof ArrayModel); + + ArrayModel am = (ArrayModel) schema; + Property inner = am.getItems(); + + ObjectProperty op = (ObjectProperty) inner; + Property name = op.getProperties().get("address"); + assertTrue(name instanceof RefProperty); + + Model model = swagger.getDefinitions().get("hello_address"); + assertNotNull(model); + } + + @Test + public void resolveInlineArrayResponse() throws Exception { + Swagger swagger = new Swagger(); + + swagger.path("/foo/baz", new Path() + .get(new Operation() + .response(200, new Response() + .vendorExtension("x-foo", "bar") + .description("it works!") + .schema(new ArrayProperty() + .items( + new ObjectProperty() + .property("name", new StringProperty())))))); + + new InlineModelResolver().flatten(swagger); + + Response response = swagger.getPaths().get("/foo/baz").getGet().getResponses().get("200"); + assertNotNull(response); + + assertNotNull(response.getSchema()); + Property responseProperty = response.getSchema(); + + // no need to flatten more + assertTrue(responseProperty instanceof ArrayProperty); + + ArrayProperty ap = (ArrayProperty) responseProperty; + Property p = ap.getItems(); + + assertNotNull(p); + + ObjectProperty innerModel = (ObjectProperty) p; + assertTrue(innerModel.getProperties().size() == 1); + assertNotNull(innerModel.getProperties().get("name")); + } + + @Test + public void testInlineMapResponse() throws Exception { + Swagger swagger = new Swagger(); + + MapProperty schema = new MapProperty(); + schema.setAdditionalProperties(new StringProperty()); + + swagger.path("/foo/baz", new Path() + .get(new Operation() + .response(200, new Response() + .vendorExtension("x-foo", "bar") + .description("it works!") + .schema(schema)))); + new InlineModelResolver().flatten(swagger); + Json.prettyPrint(swagger); + + Response response = swagger.getPaths().get("/foo/baz").getGet().getResponses().get("200"); + + Property property = response.getSchema(); + assertTrue(property instanceof MapProperty); + assertTrue(swagger.getDefinitions().size() == 0); + } + + @Test + public void testInlineMapResponseWithObjectProperty() throws Exception { + Swagger swagger = new Swagger(); + + MapProperty schema = new MapProperty(); + schema.setAdditionalProperties(new ObjectProperty() + .property("name", new StringProperty())); + + swagger.path("/foo/baz", new Path() + .get(new Operation() + .response(200, new Response() + .vendorExtension("x-foo", "bar") + .description("it works!") + .schema(schema)))); + new InlineModelResolver().flatten(swagger); + + Response response = swagger.getPaths().get("/foo/baz").getGet().getResponses().get("200"); + + Property property = response.getSchema(); + assertTrue(property instanceof RefProperty); + + Model inline = swagger.getDefinitions().get("inline_response_200"); + assertTrue(inline instanceof ModelImpl); + ModelImpl impl = (ModelImpl) inline; + + Property innerProperty = impl.getAdditionalProperties(); + assertTrue(innerProperty instanceof ObjectProperty); + + ObjectProperty obj = (ObjectProperty) innerProperty; + Property name = obj.getProperties().get("name"); + assertTrue(name instanceof StringProperty); + } + + @Test + public void testArrayResponse() { + Swagger swagger = new Swagger(); + + ArrayProperty schema = new ArrayProperty(); + schema.setItems(new ObjectProperty() + .property("name", new StringProperty())); + + swagger.path("/foo/baz", new Path() + .get(new Operation() + .response(200, new Response() + .vendorExtension("x-foo", "bar") + .description("it works!") + .schema(schema)))); + new InlineModelResolver().flatten(swagger); + + Response response = swagger.getPaths().get("/foo/baz").getGet().getResponses().get("200"); + assertTrue(response.getSchema() instanceof ArrayProperty); + + ArrayProperty am = (ArrayProperty) response.getSchema(); + Property items = am.getItems(); + assertTrue(items instanceof ObjectProperty); + ObjectProperty op = (ObjectProperty) items; + Property name = op.getProperties().get("name"); + assertTrue(name instanceof StringProperty); + } + + @Test + public void testBasicInput() { + Swagger swagger = new Swagger(); + + ModelImpl user = new ModelImpl() + .property("name", new StringProperty()); + + swagger.path("/foo/baz", new Path() + .post(new Operation() + .parameter(new BodyParameter() + .name("myBody") + .schema(new RefModel("User"))))); + + swagger.addDefinition("User", user); + + new InlineModelResolver().flatten(swagger); + + Json.prettyPrint(swagger); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java new file mode 100644 index 000000000000..4ea24aeca987 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java @@ -0,0 +1,71 @@ +package io.swagger.codegen.android; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.AndroidClientCodegen; + +import com.google.common.collect.ImmutableMap; +import mockit.Expectations; +import mockit.Tested; + +import java.util.Map; + +public class AndroidClientOptionsTest extends AbstractOptionsTest { + protected static final String ARTIFACT_ID_VALUE = "swagger-java-client-test"; + protected static final String MODEL_PACKAGE_VALUE = "package"; + protected static final String API_PACKAGE_VALUE = "apiPackage"; + protected static final String INVOKER_PACKAGE_VALUE = "io.swagger.client.test"; + protected static final String SORT_PARAMS_VALUE = "false"; + protected static final String GROUP_ID_VALUE = "io.swagger.test"; + protected static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; + protected static final String SOURCE_FOLDER_VALUE = "src/main/java/test"; + protected static final String ANDROID_MAVEN_GRADLE_PLUGIN_VALUE = "true"; + + @Tested + private AndroidClientCodegen clientCodegen; + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setModelPackage(MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setInvokerPackage(INVOKER_PACKAGE_VALUE); + times = 1; + clientCodegen.setGroupId(GROUP_ID_VALUE); + times = 1; + clientCodegen.setArtifactId(ARTIFACT_ID_VALUE); + times = 1; + clientCodegen.setArtifactVersion(ARTIFACT_VERSION_VALUE); + times = 1; + clientCodegen.setSourceFolder(SOURCE_FOLDER_VALUE); + times = 1; + clientCodegen.setUseAndroidMavenGradlePlugin(Boolean.valueOf(ANDROID_MAVEN_GRADLE_PLUGIN_VALUE)); + times = 1; + }}; + } + + @Override + protected Map getAvaliableOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) + .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) + .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) + .put(CodegenConstants.GROUP_ID, GROUP_ID_VALUE) + .put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID_VALUE) + .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) + .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) + .put(AndroidClientCodegen.USE_ANDROID_MAVEN_GRADLE_PLUGIN, ANDROID_MAVEN_GRADLE_PLUGIN_VALUE) + .build(); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java new file mode 100644 index 000000000000..5a64e676dcbe --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java @@ -0,0 +1,43 @@ +package io.swagger.codegen.csharp; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.CSharpClientCodegen; + +import com.google.common.collect.ImmutableMap; +import mockit.Expectations; +import mockit.Tested; + +import java.util.Map; + +public class CSharpClientOptionsTest extends AbstractOptionsTest { + protected static final String PACKAGE_NAME_VALUE = "swagger_client_csharp"; + protected static final String PACKAGE_VERSION_VALUE = "1.0.0-SNAPSHOT"; + + @Tested + private CSharpClientCodegen clientCodegen; + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setPackageName(PACKAGE_NAME_VALUE); + times = 1; + clientCodegen.setPackageVersion(PACKAGE_VERSION_VALUE); + times = 1; + }}; + } + + @Override + protected Map getAvaliableOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) + .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) + .build(); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharpdotnettwo/CsharpDotNet2ClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharpdotnettwo/CsharpDotNet2ClientOptionsTest.java new file mode 100644 index 000000000000..d9455103576c --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharpdotnettwo/CsharpDotNet2ClientOptionsTest.java @@ -0,0 +1,47 @@ +package io.swagger.codegen.csharpdotnettwo; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.CsharpDotNet2ClientCodegen; + +import com.google.common.collect.ImmutableMap; +import mockit.Expectations; +import mockit.Tested; + +import java.util.Map; + +public class CsharpDotNet2ClientOptionsTest extends AbstractOptionsTest { + protected static final String PACKAGE_NAME_VALUE = "swagger_client_csharp_dotnet"; + protected static final String PACKAGE_VERSION_VALUE = "1.0.0-SNAPSHOT"; + protected static final String CLIENT_PACKAGE_VALUE = "IO.Swagger.Client.Test"; + + @Tested + private CsharpDotNet2ClientCodegen clientCodegen; + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setPackageName(PACKAGE_NAME_VALUE); + times = 1; + clientCodegen.setPackageVersion(PACKAGE_VERSION_VALUE); + times = 1; + clientCodegen.setClientPackage(CLIENT_PACKAGE_VALUE); + times = 1; + }}; + } + + @Override + protected Map getAvaliableOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) + .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) + .put(CsharpDotNet2ClientCodegen.CLIENT_PACKAGE, CLIENT_PACKAGE_VALUE) + .build(); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/dart/DartClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/dart/DartClientOptionsTest.java new file mode 100644 index 000000000000..6a63754d6465 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/dart/DartClientOptionsTest.java @@ -0,0 +1,68 @@ +package io.swagger.codegen.dart; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.DartClientCodegen; + +import com.google.common.collect.ImmutableMap; +import mockit.Expectations; +import mockit.Tested; + +import java.util.Map; + +public class DartClientOptionsTest extends AbstractOptionsTest { + protected static final String MODEL_PACKAGE_VALUE = "packagedart"; + protected static final String API_PACKAGE_VALUE = "apiPackageDart"; + protected static final String SORT_PARAMS_VALUE = "false"; + protected static final String BROWSER_CLIENT_VALUE = "true"; + protected static final String PUB_NAME_VALUE = "swagger"; + protected static final String PUB_VERSION_VALUE = "1.0.0-SNAPSHOT"; + protected static final String PUB_DESCRIPTION_VALUE = "Swagger API client dart"; + protected static final String SOURCE_FOLDER_VALUE = "src"; + + @Tested + private DartClientCodegen clientCodegen; + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setModelPackage(MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setBrowserClient(Boolean.valueOf(BROWSER_CLIENT_VALUE)); + times = 1; + clientCodegen.setPubName(PUB_NAME_VALUE); + times = 1; + clientCodegen.setPubVersion(PUB_VERSION_VALUE); + times = 1; + clientCodegen.setPubDescription(PUB_DESCRIPTION_VALUE); + times = 1; + clientCodegen.setSourceFolder(SOURCE_FOLDER_VALUE); + times = 1; + }}; + } + + @Override + protected Map getAvaliableOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) + .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) + .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(DartClientCodegen.BROWSER_CLIENT, BROWSER_CLIENT_VALUE) + .put(DartClientCodegen.PUB_NAME, PUB_NAME_VALUE) + .put(DartClientCodegen.PUB_VERSION, PUB_VERSION_VALUE) + .put(DartClientCodegen.PUB_DESCRIPTION, PUB_DESCRIPTION_VALUE) + .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) + .build(); + } +} + diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/flash/FlashClienOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/flash/FlashClienOptionsTest.java new file mode 100644 index 000000000000..75a9df65e405 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/flash/FlashClienOptionsTest.java @@ -0,0 +1,51 @@ +package io.swagger.codegen.flash; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.FlashClientCodegen; + +import com.google.common.collect.ImmutableMap; +import mockit.Expectations; +import mockit.Tested; + +import java.util.Map; + +public class FlashClienOptionsTest extends AbstractOptionsTest { + protected static final String PACKAGE_NAME_VALUE = "io.swagger.flash"; + protected static final String PACKAGE_VERSION_VALUE = "1.0.0-SNAPSHOT"; + protected static final String INVOKER_PACKAGE_VALUE = "io.swagger.flash"; + protected static final String SOURCE_FOLDER_VALUE = "src/main/flex/test"; + + @Tested + private FlashClientCodegen clientCodegen; + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setPackageName(PACKAGE_NAME_VALUE); + times = 1; + clientCodegen.setPackageVersion(PACKAGE_VERSION_VALUE); + times = 1; + clientCodegen.setInvokerPackage(INVOKER_PACKAGE_VALUE); + times = 1; + clientCodegen.setSourceFolder(SOURCE_FOLDER_VALUE); + times = 1; + }}; + } + + @Override + protected Map getAvaliableOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) + .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) + .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) + .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) + .build(); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java new file mode 100644 index 000000000000..9cdac7d394bf --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java @@ -0,0 +1,84 @@ +package io.swagger.codegen.java; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.JavaClientCodegen; + +import com.google.common.collect.ImmutableMap; +import mockit.Expectations; +import mockit.Tested; + +import java.util.Map; + +public class JavaClientOptionsTest extends AbstractOptionsTest { + + protected static final String ARTIFACT_ID_VALUE = "swagger-java-client-test"; + protected static final String MODEL_PACKAGE_VALUE = "package"; + protected static final String API_PACKAGE_VALUE = "apiPackage"; + protected static final String INVOKER_PACKAGE_VALUE = "io.swagger.client.test"; + protected static final String SORT_PARAMS_VALUE = "false"; + protected static final String GROUP_ID_VALUE = "io.swagger.test"; + protected static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; + protected static final String SOURCE_FOLDER_VALUE = "src/main/java/test"; + protected static final String LOCAL_PREFIX_VALUE = "tst"; + protected static final String LIBRARY_VALUE = "jersey2"; + protected static final String SERIALIZABLE_MODEL_VALUE = "false"; + protected static final String FULL_JAVA_UTIL_VALUE = "true"; + + @Tested + private JavaClientCodegen clientCodegen; + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setModelPackage(MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setInvokerPackage(INVOKER_PACKAGE_VALUE); + times = 1; + clientCodegen.setGroupId(GROUP_ID_VALUE); + times = 1; + clientCodegen.setArtifactId(ARTIFACT_ID_VALUE); + times = 1; + clientCodegen.setArtifactVersion(ARTIFACT_VERSION_VALUE); + times = 1; + clientCodegen.setSourceFolder(SOURCE_FOLDER_VALUE); + times = 1; + clientCodegen.setLocalVariablePrefix(LOCAL_PREFIX_VALUE); + times = 1; + clientCodegen.setSerializableModel(Boolean.valueOf(SERIALIZABLE_MODEL_VALUE)); + times = 1; + clientCodegen.setLibrary(LIBRARY_VALUE); + times = 1; + clientCodegen.setFullJavaUtil(Boolean.valueOf(FULL_JAVA_UTIL_VALUE)); + times = 1; + }}; + } + + @Override + protected Map getAvaliableOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) + .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) + .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) + .put(CodegenConstants.GROUP_ID, GROUP_ID_VALUE) + .put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID_VALUE) + .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) + .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) + .put(CodegenConstants.LOCAL_VARIABLE_PREFIX, LOCAL_PREFIX_VALUE) + .put(CodegenConstants.SERIALIZABLE_MODEL, SERIALIZABLE_MODEL_VALUE) + .put(JavaClientCodegen.FULL_JAVA_UTIL, FULL_JAVA_UTIL_VALUE) + .put(CodegenConstants.LIBRARY, LIBRARY_VALUE) + .build(); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/jaxrs/AllowableValuesTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/jaxrs/AllowableValuesTest.java new file mode 100644 index 000000000000..ef24287b0051 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/jaxrs/AllowableValuesTest.java @@ -0,0 +1,64 @@ +package io.swagger.codegen.java.jaxrs; + +import io.swagger.codegen.CodegenParameter; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.samskivert.mustache.Mustache; +import com.samskivert.mustache.Template; +import org.apache.commons.io.IOUtils; +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + +public class AllowableValuesTest { + + private static final String TEMPLATE_FILE = "JavaJaxRS/allowableValues.mustache"; + private static final String PROVIDER_NAME = "operations"; + + private static String loadClassResource(Class cls, String name) throws IOException { + InputStream in = null; + try { + in = cls.getClassLoader().getResourceAsStream(name); + return IOUtils.toString(in, StandardCharsets.UTF_8); + } finally { + IOUtils.closeQuietly(in); + } + } + + @DataProvider(name = PROVIDER_NAME) + private Object[][] resource() { + final CodegenParameter param1 = new CodegenParameter(); + final CodegenParameter param2 = new CodegenParameter() {{ + allowableValues = ImmutableMap.of("values", ImmutableList.of("item1", "item2", "item3")); + }}; + final CodegenParameter param3 = new CodegenParameter() {{ + allowableValues = ImmutableMap.of("min", 1, "max", 10); + }}; + final CodegenParameter param4 = new CodegenParameter() {{ + allowableValues = ImmutableMap.of("min", 1); + }}; + final CodegenParameter param5 = new CodegenParameter() {{ + allowableValues = ImmutableMap.of("max", 10); + }}; + + return new Object[][]{ + {param1, ""}, + {param2, "allowableValues=\"item1, item2, item3\""}, + {param3, "allowableValues=\"range=[1, 10]\""}, + {param4, "allowableValues=\"range=[1, infinity]\""}, + {param5, "allowableValues=\"range=[-infinity, 10]\""}, + }; + } + + @Test(dataProvider = PROVIDER_NAME) + public void annotationsTest(CodegenParameter parameter, String expected) throws IOException { + final Template template = Mustache.compiler().compile(loadClassResource(this.getClass(), TEMPLATE_FILE)); + + Assert.assertEquals(template.execute(parameter), expected); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java new file mode 100644 index 000000000000..00f09ad036bc --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java @@ -0,0 +1,49 @@ +package io.swagger.codegen.jaxrs; + +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.java.JavaClientOptionsTest; +import io.swagger.codegen.languages.JaxRSServerCodegen; + +import mockit.Expectations; +import mockit.Tested; + +public class JaxRSServerOptionsTest extends JavaClientOptionsTest { + + @Tested + private JaxRSServerCodegen clientCodegen; + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setModelPackage(MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setInvokerPackage(INVOKER_PACKAGE_VALUE); + times = 1; + clientCodegen.setGroupId(GROUP_ID_VALUE); + times = 1; + clientCodegen.setArtifactId(ARTIFACT_ID_VALUE); + times = 1; + clientCodegen.setArtifactVersion(ARTIFACT_VERSION_VALUE); + times = 1; + clientCodegen.setSourceFolder(SOURCE_FOLDER_VALUE); + times = 1; + clientCodegen.setLocalVariablePrefix(LOCAL_PREFIX_VALUE); + times = 1; + clientCodegen.setSerializableModel(Boolean.valueOf(SERIALIZABLE_MODEL_VALUE)); + times = 1; + clientCodegen.setLibrary(LIBRARY_VALUE); + times = 1; + clientCodegen.setFullJavaUtil(Boolean.valueOf(FULL_JAVA_UTIL_VALUE)); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/SwiftCodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/SwiftCodegenTest.java new file mode 100644 index 000000000000..acede31f7361 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/SwiftCodegenTest.java @@ -0,0 +1,45 @@ +package io.swagger.codegen.languages; + +import org.testng.Assert; +import org.testng.annotations.Test; + +public class SwiftCodegenTest { + + SwiftCodegen swiftCodegen = new SwiftCodegen(); + + @Test + public void shouldNotBreakCorrectName() throws Exception { + Assert.assertEquals(swiftCodegen.toSwiftyEnumName("EntryName"), "EntryName"); + } + + @Test + public void testSingleWordAllCaps() throws Exception { + Assert.assertEquals(swiftCodegen.toSwiftyEnumName("VALUE"), "Value"); + } + + @Test + public void testSingleWordLowercase() throws Exception { + Assert.assertEquals(swiftCodegen.toSwiftyEnumName("value"), "Value"); + } + + @Test + public void testCapitalsWithUnderscore() throws Exception { + Assert.assertEquals(swiftCodegen.toSwiftyEnumName("ENTRY_NAME"), "EntryName"); + } + + @Test + public void testCapitalsWithDash() throws Exception { + Assert.assertEquals(swiftCodegen.toSwiftyEnumName("ENTRY-NAME"), "EntryName"); + } + + @Test + public void testCapitalsWithSpace() throws Exception { + Assert.assertEquals(swiftCodegen.toSwiftyEnumName("ENTRY NAME"), "EntryName"); + } + + @Test + public void testLowercaseWithUnderscore() throws Exception { + Assert.assertEquals(swiftCodegen.toSwiftyEnumName("entry_name"), "EntryName"); + } + +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/nodejs/NodeJSServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/nodejs/NodeJSServerOptionsTest.java new file mode 100644 index 000000000000..5ad3eb33f2a0 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/nodejs/NodeJSServerOptionsTest.java @@ -0,0 +1,48 @@ +package io.swagger.codegen.nodejs; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.JavaClientCodegen; +import io.swagger.codegen.languages.NodeJSServerCodegen; + +import com.google.common.collect.ImmutableMap; +import mockit.Expectations; +import mockit.Tested; + +import java.util.Map; + +public class NodeJSServerOptionsTest extends AbstractOptionsTest { + private static final String MODEL_PACKAGE_VALUE = "package"; + private static final String API_PACKAGE_VALUE = "apiPackage"; + private static final String SORT_PARAMS_VALUE = "false"; + + @Tested + private NodeJSServerCodegen clientCodegen; + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setModelPackage(MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SORT_PARAMS_VALUE)); + times = 1; + }}; + } + + @Override + protected Map getAvaliableOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) + .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) + .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .build(); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpClientOptionsTest.java new file mode 100644 index 000000000000..413ee5380537 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpClientOptionsTest.java @@ -0,0 +1,75 @@ +package io.swagger.codegen.php; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.PhpClientCodegen; + +import com.google.common.collect.ImmutableMap; +import mockit.Expectations; +import mockit.Tested; + +import java.util.Map; + +public class PhpClientOptionsTest extends AbstractOptionsTest { + protected static final String MODEL_PACKAGE_VALUE = "package"; + protected static final String API_PACKAGE_VALUE = "apiPackage"; + protected static final String SORT_PARAMS_VALUE = "false"; + protected static final String VARIABLE_NAMING_CONVENTION_VALUE = "snake_case"; + protected static final String INVOKER_PACKAGE_VALUE = "Swagger\\Client\\Php"; + protected static final String PACKAGE_PATH_VALUE = "SwaggerClient-php"; + protected static final String SRC_BASE_PATH_VALUE = "libPhp"; + protected static final String COMPOSER_VENDOR_NAME_VALUE = "swaggerPhp"; + protected static final String COMPOSER_PROJECT_NAME_VALUE = "swagger-client-php"; + protected static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; + + @Tested + private PhpClientCodegen clientCodegen; + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setModelPackage(MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setParameterNamingConvention(VARIABLE_NAMING_CONVENTION_VALUE); + times = 1; + clientCodegen.setInvokerPackage(INVOKER_PACKAGE_VALUE); + times = 1; + clientCodegen.setPackagePath(PACKAGE_PATH_VALUE); + times = 1; + clientCodegen.setSrcBasePath(SRC_BASE_PATH_VALUE); + times = 1; + clientCodegen.setComposerVendorName(COMPOSER_VENDOR_NAME_VALUE); + times = 1; + clientCodegen.setComposerProjectName(COMPOSER_PROJECT_NAME_VALUE); + times = 1; + clientCodegen.setArtifactVersion(ARTIFACT_VERSION_VALUE); + times = 1; + }}; + } + + @Override + protected Map getAvaliableOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) + .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) + .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(PhpClientCodegen.VARIABLE_NAMING_CONVENTION, VARIABLE_NAMING_CONVENTION_VALUE) + .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) + .put(PhpClientCodegen.PACKAGE_PATH, PACKAGE_PATH_VALUE) + .put(PhpClientCodegen.SRC_BASE_PATH, SRC_BASE_PATH_VALUE) + .put(PhpClientCodegen.COMPOSER_VENDOR_NAME, COMPOSER_VENDOR_NAME_VALUE) + .put(PhpClientCodegen.COMPOSER_PROJECT_NAME, COMPOSER_PROJECT_NAME_VALUE) + .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) + .build(); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonClientOptionsTest.java new file mode 100644 index 000000000000..645471789e81 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonClientOptionsTest.java @@ -0,0 +1,43 @@ +package io.swagger.codegen.python; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.PythonClientCodegen; + +import com.google.common.collect.ImmutableMap; +import mockit.Expectations; +import mockit.Tested; + +import java.util.Map; + +public class PythonClientOptionsTest extends AbstractOptionsTest { + protected static final String PACKAGE_NAME_VALUE = "swagger_client_python"; + protected static final String PACKAGE_VERSION_VALUE = "1.0.0-SNAPSHOT"; + + @Tested + private PythonClientCodegen clientCodegen; + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setPackageName(PACKAGE_NAME_VALUE); + times = 1; + clientCodegen.setPackageVersion(PACKAGE_VERSION_VALUE); + times = 1; + }}; + } + + @Override + protected Map getAvaliableOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) + .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) + .build(); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java new file mode 100644 index 000000000000..ca2ea19a2d9e --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java @@ -0,0 +1,46 @@ +package io.swagger.codegen.ruby; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.RubyClientCodegen; + +import com.google.common.collect.ImmutableMap; +import mockit.Expectations; +import mockit.Tested; + +import java.util.Map; + +public class RubyClientOptionsTest extends AbstractOptionsTest { + private static final String GEM_NAME_VALUE = "swagger_client_ruby"; + private static final String MODULE_NAME_VALUE = "SwaggerClientRuby"; + private static final String GEM_VERSION_VALUE = "1.0.0-SNAPSHOT"; + + @Tested + private RubyClientCodegen clientCodegen; + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setGemName(GEM_NAME_VALUE); + times = 1; + clientCodegen.setModuleName(MODULE_NAME_VALUE); + times = 1; + clientCodegen.setGemVersion(GEM_VERSION_VALUE); + times = 1; + }}; + } + + @Override + protected Map getAvaliableOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(RubyClientCodegen.GEM_NAME, GEM_NAME_VALUE) + .put(RubyClientCodegen.MODULE_NAME, MODULE_NAME_VALUE) + .put(RubyClientCodegen.GEM_VERSION, GEM_VERSION_VALUE) + .build(); + } +} diff --git a/modules/swagger-codegen/src/test/resources/2_0/globalConsumesAndProduces.json b/modules/swagger-codegen/src/test/resources/2_0/globalConsumesAndProduces.json new file mode 100644 index 000000000000..520218ed707e --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/2_0/globalConsumesAndProduces.json @@ -0,0 +1,130 @@ +{ + "swagger": "2.0", + "info": { + "description": "Spec for testing global consumes and produces", + "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", + "consumes": ["application/global_consumes"], + "produces": ["application/global_produces"], + "schemes": [ + "http" + ], + "paths": { + "/tests/localConsumesAndProduces": { + "get": { + "tags": [ + "tests" + ], + "summary": "Operation with local consumes and produces", + "description": "", + "operationId": "localConsumesAndProduces", + "produces": [ + "application/json" + ], + "consumes": [ + "application/json" + ], + "parameters": [ + ], + "responses": { + "200": { + "description": "successful operation. Returning a simple int.", + "schema": { + "type": "integer", + "format": "int64" + } + } + } + } + }, + "/tests/globalConsumesAndProduces": { + "get": { + "tags": [ + "tests" + ], + "summary": "Operation with global consumes and produces", + "description": "", + "operationId": "globalConsumesAndProduces", + "parameters": [ + ], + "responses": { + "200": { + "description": "successful operation. Returning a simple int.", + "schema": { + "type": "integer", + "format": "int64" + } + } + } + } + }, + "/tests/localResetConsumesAndProduces": { + "get": { + "tags": [ + "tests" + ], + "summary": "Operation with local consumes and produces set to empty (reset)", + "description": "", + "operationId": "localResetConsumesAndProduces", + "parameters": [ + ], + "consumes": [], + "produces": [], + "responses": { + "200": { + "description": "successful operation. Returning a simple int.", + "schema": { + "type": "integer", + "format": "int64" + } + } + } + } + } + + }, + "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": { + "CustomModel": { + "required": [ + "id" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string", + "example": "doggie" + } + } + } + } +} diff --git a/modules/swagger-codegen/src/test/resources/2_0/wordnik.yaml b/modules/swagger-codegen/src/test/resources/2_0/wordnik.yaml new file mode 100644 index 000000000000..5d46e5a8b7e0 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/2_0/wordnik.yaml @@ -0,0 +1,1643 @@ +swagger: '2.0' + +info: + version: 4.0.1 + title: The Wordnik Public API + description: "**Wordnik has an API, and you're invited.**\nThe Wordnik API lets you request definitions, example sentences, spelling suggestions, \nrelated words like synonyms and antonyms, phrases containing a given word, word \nautocompletion, random words, words of the day, and much more\n" + contact: + url: 'http://developer.wordnik.com/' + email: apiteam@wordnik.com + name: Wordnik API Team + +schemes: + - https +host: api.wordnik.com +basePath: /v4 + +securityDefinitions: + apiKey: + type: apiKey + in: header + name: api_key +security: + - apiKey: [] +paths: + /words.json/randomWord: + get: + tags: + - words + summary: Returns a single random WordObject + operationId: getRandomWord + parameters: + - name: hasDictionaryDef + in: query + description: Only return words with dictionary definitions + required: false + type: string + - name: includePartOfSpeech + in: query + description: CSV part-of-speech values to include + required: false + type: string + - name: excludePartOfSpeech + in: query + description: CSV part-of-speech values to exclude + required: false + type: string + - name: minCorpusCount + in: query + description: Minimum corpus frequency for terms + required: false + type: integer + format: int32 + - name: maxCorpusCount + in: query + description: Maximum corpus frequency for terms + required: false + type: integer + format: int32 + - name: minDictionaryCount + in: query + description: Minimum dictionary count + required: false + type: integer + format: int32 + - name: maxDictionaryCount + in: query + description: Maximum dictionary count + required: false + type: integer + format: int32 + - name: minLength + in: query + description: Minimum word length + required: false + type: integer + format: int32 + - name: maxLength + in: query + description: Maximum word length + required: false + type: integer + format: int32 + responses: + '200': + description: success + schema: + $ref: '#/definitions/WordObject' + '404': + description: No word found. + /account.json/user: + get: + tags: + - account + summary: Returns the logged-in User + description: Requires a valid auth_token to be set. + operationId: getLoggedInUser + parameters: + - name: auth_token + in: header + description: 'The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above)' + required: true + type: string + responses: + '200': + description: The logged-in user + schema: + $ref: '#/definitions/User' + '403': + description: Not logged in. + '404': + description: User not found. + '/word.json/{word}/pronunciations': + get: + tags: + - word + summary: Returns text pronunciations for a given word + operationId: getTextPronunciations + parameters: + - name: word + in: path + description: Word to get pronunciations for + required: true + type: string + - name: useCanonical + in: query + description: "If true will try to return a correct word root ('cats' -> 'cat'). If false returns exactly what was requested." + required: false + type: string + - name: sourceDictionary + in: query + description: Get from a single dictionary + required: false + type: string + - name: typeFormat + in: query + description: Text pronunciation type + required: false + type: string + - name: limit + in: query + description: Maximum number of results to return + required: false + type: integer + format: int32 + responses: + '200': + description: success + schema: + type: array + items: + $ref: '#/definitions/TextPron' + '400': + description: Invalid word supplied. + '/word.json/{word}/relatedWords': + get: + tags: + - word + summary: 'Given a word as a string, returns relationships from the Word Graph' + operationId: getRelatedWords + parameters: + - name: word + in: path + description: Word to fetch relationships for + required: true + type: string + - name: useCanonical + in: query + description: "If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested." + required: false + type: string + - name: relationshipTypes + in: query + description: Limits the total results per type of relationship type + required: false + type: string + - name: limitPerRelationshipType + in: query + description: Restrict to the supplied relationship types + required: false + type: integer + format: int32 + responses: + '200': + description: success + schema: + type: array + items: + $ref: '#/definitions/Related' + '400': + description: Invalid word supplied. + /words.json/reverseDictionary: + get: + tags: + - words + summary: Reverse dictionary search + operationId: reverseDictionary + parameters: + - name: query + in: query + description: Search term + required: true + type: string + - name: findSenseForWord + in: query + description: Restricts words and finds closest sense + required: false + type: string + - name: includeSourceDictionaries + in: query + description: Only include these comma-delimited source dictionaries + required: false + type: string + - name: excludeSourceDictionaries + in: query + description: Exclude these comma-delimited source dictionaries + required: false + type: string + - name: includePartOfSpeech + in: query + description: Only include these comma-delimited parts of speech + required: false + type: string + - name: excludePartOfSpeech + in: query + description: Exclude these comma-delimited parts of speech + required: false + type: string + - name: minCorpusCount + in: query + description: Minimum corpus frequency for terms + required: false + type: integer + format: int32 + - name: maxCorpusCount + in: query + description: Maximum corpus frequency for terms + required: false + type: integer + format: int32 + - name: minLength + in: query + description: Minimum word length + required: false + type: integer + format: int32 + - name: maxLength + in: query + description: Maximum word length + required: false + type: integer + format: int32 + - name: expandTerms + in: query + description: Expand terms + required: false + type: string + - name: includeTags + in: query + description: Return a closed set of XML tags in response + required: false + type: string + - name: sortBy + in: query + description: Attribute to sort by + required: false + type: string + - name: sortOrder + in: query + description: Sort direction + required: false + type: string + - name: skip + in: query + description: Results to skip + required: false + type: string + - name: limit + in: query + description: Maximum number of results to return + required: false + type: integer + format: int32 + responses: + '200': + description: success + schema: + $ref: '#/definitions/DefinitionSearchResults' + '400': + description: Invalid term supplied. + /account.json/apiTokenStatus: + get: + tags: + - account + summary: Returns usage statistics for the API account. + operationId: getApiTokenStatus + parameters: + - name: api_key + in: header + description: Wordnik authentication token + required: false + type: string + responses: + '200': + description: Usage statistics for the supplied API key + schema: + $ref: '#/definitions/ApiTokenStatus' + '400': + description: No token supplied. + '404': + description: No API account with supplied token. + '/word.json/{word}': + get: + tags: + - word + summary: 'Given a word as a string, returns the WordObject that represents it' + operationId: getWord + parameters: + - name: word + in: path + description: String value of WordObject to return + required: true + type: string + - name: useCanonical + in: query + description: "If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested." + required: false + type: string + - name: includeSuggestions + in: query + description: 'Return suggestions (for correct spelling, case variants, etc.)' + required: false + type: string + responses: + '200': + description: success + schema: + $ref: '#/definitions/WordObject' + '400': + description: Invalid word supplied. + '/wordList.json/{permalink}/deleteWords': + post: + tags: + - wordList + summary: Removes words from a WordList + operationId: deleteWordsFromWordList + parameters: + - name: permalink + in: path + description: permalink of WordList to use + required: true + type: string + - in: body + name: body + description: Words to remove from WordList + required: false + schema: + type: array + items: + $ref: '#/definitions/StringValue' + - name: auth_token + in: header + description: 'The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above)' + required: true + type: string + responses: + '200': + description: success + '400': + description: Invalid permalink supplied + '403': + description: Not Authorized to modify WordList + '404': + description: WordList not found + '/word.json/{word}/examples': + get: + tags: + - word + summary: Returns examples for a word + operationId: getExamples + parameters: + - name: word + in: path + description: Word to return examples for + required: true + type: string + - name: includeDuplicates + in: query + description: Show duplicate examples from different sources + required: false + type: string + - name: useCanonical + in: query + description: "If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested." + required: false + type: string + - name: skip + in: query + description: Results to skip + required: false + type: integer + format: int32 + - name: limit + in: query + description: Maximum number of results to return + required: false + type: integer + format: int32 + responses: + '200': + description: success + schema: + $ref: '#/definitions/ExampleSearchResults' + '400': + description: Invalid word supplied. + '400': + description: Invalid word supplied. + '/account.json/authenticate/{username}': + get: + tags: + - account + summary: Authenticates a User + operationId: authenticate + parameters: + - name: username + in: path + description: A confirmed Wordnik username + required: true + type: string + - name: password + in: query + description: "The user's password" + required: true + type: string + responses: + '200': + description: A valid authentication token + schema: + $ref: '#/definitions/AuthenticationToken' + '403': + description: Account not available. + '404': + description: User not found. + post: + tags: + - account + summary: Authenticates a user + operationId: authenticatePost + parameters: + - name: username + in: path + description: A confirmed Wordnik username + required: true + type: string + - in: body + name: body + schema: + type: string + description: "The user's password" + required: true + responses: + '200': + description: A valid authentication token + schema: + $ref: '#/definitions/AuthenticationToken' + '403': + description: Account not available. + '404': + description: User not found. + '/word.json/{word}/audio': + get: + tags: + - word + summary: Fetches audio metadata for a word. + description: The metadata includes a time-expiring fileUrl which allows reading the audio file directly from the API. Currently only audio pronunciations from the American Heritage Dictionary in mp3 format are supported. + operationId: getAudio + parameters: + - name: word + in: path + description: Word to get audio for. + required: true + type: string + - name: useCanonical + in: query + description: Use the canonical form of the word + required: false + type: string + - name: limit + in: query + description: Maximum number of results to return + required: false + type: integer + format: int32 + responses: + '200': + description: success + schema: + type: array + items: + $ref: '#/definitions/AudioFile' + '400': + description: Invalid word supplied. + /words.json/randomWords: + get: + tags: + - words + summary: Returns an array of random WordObjects + operationId: getRandomWords + parameters: + - name: hasDictionaryDef + in: query + description: Only return words with dictionary definitions + required: false + type: string + - name: includePartOfSpeech + in: query + description: CSV part-of-speech values to include + required: false + type: string + - name: excludePartOfSpeech + in: query + description: CSV part-of-speech values to exclude + required: false + type: string + - name: minCorpusCount + in: query + description: Minimum corpus frequency for terms + required: false + type: integer + format: int32 + - name: maxCorpusCount + in: query + description: Maximum corpus frequency for terms + required: false + type: integer + format: int32 + - name: minDictionaryCount + in: query + description: Minimum dictionary count + required: false + type: integer + format: int32 + - name: maxDictionaryCount + in: query + description: Maximum dictionary count + required: false + type: integer + format: int32 + - name: minLength + in: query + description: Minimum word length + required: false + type: integer + format: int32 + - name: maxLength + in: query + description: Maximum word length + required: false + type: integer + format: int32 + - name: sortBy + in: query + description: Attribute to sort by + required: false + type: string + - name: sortOrder + in: query + description: Sort direction + required: false + type: string + - name: limit + in: query + description: Maximum number of results to return + required: false + type: integer + format: int32 + responses: + '200': + description: success + schema: + type: array + items: + $ref: '#/definitions/WordObject' + '400': + description: Invalid term supplied. + '404': + description: No results. + /account.json/wordLists: + get: + tags: + - account + summary: Fetches WordList objects for the logged-in user. + operationId: getWordListsForLoggedInUser + parameters: + - name: auth_token + in: header + description: auth_token of logged-in user + required: true + type: string + - name: skip + in: query + description: Results to skip + required: false + type: integer + format: int32 + - name: limit + in: query + description: Maximum number of results to return + required: false + type: integer + format: int32 + responses: + '200': + description: success + schema: + type: array + items: + $ref: '#/definitions/WordList' + '403': + description: Not authenticated. + '404': + description: User account not found. + '/word.json/{word}/phrases': + get: + tags: + - word + summary: Fetches bi-gram phrases for a word + operationId: getPhrases + parameters: + - name: word + in: path + description: Word to fetch phrases for + required: true + type: string + - name: limit + in: query + description: Maximum number of results to return + required: false + type: integer + format: int32 + - name: wlmi + in: query + description: Minimum WLMI for the phrase + required: false + type: integer + format: int32 + - name: useCanonical + in: query + description: "If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested." + required: false + type: string + responses: + '200': + description: success + schema: + type: array + items: + $ref: '#/definitions/Bigram' + '400': + description: Invalid word supplied. + '/word.json/{word}/frequency': + get: + tags: + - word + summary: Returns word usage over time + operationId: getWordFrequency + parameters: + - name: word + in: path + description: Word to return + required: true + type: string + - name: useCanonical + in: query + description: "If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested." + required: false + type: string + - name: startYear + in: query + description: Starting Year + required: false + type: integer + format: int32 + - name: endYear + in: query + description: Ending Year + required: false + type: integer + format: int32 + responses: + '200': + description: success + schema: + $ref: '#/definitions/FrequencySummary' + '400': + description: Invalid word supplied. + '404': + description: No results. + '/wordList.json/{permalink}/words': + get: + tags: + - wordList + summary: Fetches words in a WordList + operationId: getWordListWords + parameters: + - name: permalink + in: path + description: ID of WordList to use + required: true + type: string + - name: sortBy + in: query + description: Field to sort by + required: false + type: string + - name: sortOrder + in: query + description: Direction to sort + required: false + type: string + - name: skip + in: query + description: Results to skip + required: false + type: integer + format: int32 + - name: limit + in: query + description: Maximum number of results to return + required: false + type: integer + format: int32 + - name: auth_token + in: header + description: 'The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above)' + required: true + type: string + responses: + '200': + description: success + schema: + type: array + items: + $ref: '#/definitions/WordListWord' + $ref: '#/definitions/WordListWord' + '400': + description: Invalid ID supplied + '403': + description: Not Authorized to access WordList + '404': + description: WordList not found + post: + tags: + - wordList + summary: Adds words to a WordList + operationId: addWordsToWordList + parameters: + - name: permalink + in: path + description: permalink of WordList to user + required: true + type: string + - in: body + name: body + description: Array of words to add to WordList + required: false + schema: + type: array + items: + $ref: '#/definitions/StringValue' + - name: auth_token + in: header + description: 'The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above)' + required: true + type: string + responses: + '200': + description: success + '400': + description: Invalid permalink supplied + '403': + description: Not Authorized to access WordList + '404': + description: WordList not found + /wordLists.json: + post: + tags: + - wordLists + summary: Creates a WordList. + operationId: createWordList + parameters: + - in: body + name: body + description: WordList to create + required: false + schema: + $ref: '#/definitions/WordList' + - name: auth_token + in: header + description: 'The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above)' + required: true + type: string + responses: + '200': + description: success + schema: + $ref: '#/definitions/WordList' + '400': + description: Invalid WordList supplied or mandatory fields are missing + '403': + description: Not authenticated + '404': + description: WordList owner not found + '/word.json/{word}/etymologies': + get: + tags: + - word + summary: Fetches etymology data + operationId: getEtymologies + parameters: + - name: word + in: path + description: Word to return + required: true + type: string + - name: useCanonical + in: query + description: "If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested." + required: false + type: string + responses: + '200': + description: success + schema: + type: array + items: + type: string + '400': + description: Invalid word supplied. + '404': + description: No definitions found. + '/word.json/{word}/topExample': + get: + tags: + - word + summary: Returns a top example for a word + operationId: getTopExample + parameters: + - name: word + in: path + description: Word to fetch examples for + required: true + type: string + - name: useCanonical + in: query + description: "If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested." + required: false + type: string + responses: + '200': + description: success + schema: + $ref: '#/definitions/Example' + '400': + description: Invalid word supplied. + '/word.json/{word}/definitions': + get: + tags: + - word + summary: Return definitions for a word + operationId: getDefinitions + parameters: + - name: word + in: path + description: Word to return definitions for + required: true + type: string + - name: limit + in: query + description: Maximum number of results to return + required: false + type: integer + format: int32 + - name: partOfSpeech + in: query + description: CSV list of part-of-speech types + required: false + type: string + - name: includeRelated + in: query + description: Return related words with definitions + required: false + type: string + - name: sourceDictionaries + in: query + description: "Source dictionary to return definitions from. If 'all' is received, results are returned from all sources. If multiple values are received (e.g. 'century,wiktionary'), results are returned from the first specified dictionary that has definitions. If left blank, results are returned from the first dictionary that has definitions. By default, dictionaries are searched in this order: ahd, wiktionary, webster, century, wordnet" + required: false + type: array + items: + type: string + collectionFormat: csv + - name: useCanonical + in: query + description: "If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested." + required: false + type: string + - name: includeTags + in: query + description: Return a closed set of XML tags in response + required: false + type: string + responses: + '200': + description: success + schema: + type: array + items: + $ref: '#/definitions/Definition' + '400': + description: Invalid word supplied. + '404': + description: No definitions found. + '/words.json/search/{query}': + get: + tags: + - words + summary: Searches words + operationId: searchWords + parameters: + - name: query + in: path + description: Search query + required: true + type: string + - name: caseSensitive + in: query + description: Search case sensitive + required: false + type: string + - name: includePartOfSpeech + in: query + description: Only include these comma-delimited parts of speech + required: false + type: string + - name: excludePartOfSpeech + in: query + description: Exclude these comma-delimited parts of speech + required: false + type: string + - name: minCorpusCount + in: query + description: Minimum corpus frequency for terms + required: false + type: integer + format: int32 + - name: maxCorpusCount + in: query + description: Maximum corpus frequency for terms + required: false + type: integer + format: int32 + - name: minDictionaryCount + in: query + description: Minimum number of dictionary entries for words returned + required: false + type: integer + format: int32 + - name: maxDictionaryCount + in: query + description: Maximum dictionary definition count + required: false + type: integer + format: int32 + - name: minLength + in: query + description: Minimum word length + required: false + type: integer + format: int32 + - name: maxLength + in: query + description: Maximum word length + required: false + type: integer + format: int32 + - name: skip + in: query + description: Results to skip + required: false + type: integer + format: int32 + - name: limit + in: query + description: Maximum number of results to return + required: false + type: integer + format: int32 + responses: + '200': + description: success + schema: + $ref: '#/definitions/WordSearchResults' + '400': + description: Invalid query supplied. + '/wordList.json/{permalink}': + get: + tags: + - wordList + summary: Fetches a WordList by ID + operationId: getWordListByPermalink + parameters: + - name: permalink + in: path + description: permalink of WordList to fetch + required: true + type: string + - name: auth_token + in: header + description: 'The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above)' + required: true + type: string + responses: + '200': + description: success + schema: + $ref: '#/definitions/WordList' + '400': + description: Invalid ID supplied + '403': + description: Not Authorized to access WordList + '404': + description: WordList not found + put: + tags: + - wordList + summary: Updates an existing WordList + operationId: updateWordList + parameters: + - name: permalink + in: path + description: permalink of WordList to update + required: true + type: string + - in: body + name: body + description: Updated WordList + required: false + schema: + $ref: '#/definitions/WordList' + - name: auth_token + in: header + description: 'The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above)' + required: true + type: string + responses: + '200': + description: success + '400': + description: Invalid ID supplied + '403': + description: Not Authorized to update WordList + '404': + description: WordList not found + delete: + tags: + - wordList + summary: Deletes an existing WordList + operationId: deleteWordList + parameters: + - name: permalink + in: path + description: ID of WordList to delete + required: true + type: string + - name: auth_token + in: header + description: 'The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above)' + required: true + type: string + responses: + '200': + description: success + '400': + description: Invalid ID supplied + '403': + description: Not Authorized to delete WordList + '404': + description: WordList not found + '/word.json/{word}/hyphenation': + get: + tags: + - word + summary: Returns syllable information for a word + operationId: getHyphenation + parameters: + - name: word + in: path + description: Word to get syllables for + required: true + type: string + - name: useCanonical + in: query + description: "If true will try to return a correct word root ('cats' -> 'cat'). If false returns exactly what was requested." + required: false + type: string + - name: sourceDictionary + in: query + description: 'Get from a single dictionary. Valid options: ahd, century, wiktionary, webster, and wordnet.' + required: false + type: string + - name: limit + in: query + description: Maximum number of results to return + required: false + type: integer + format: int32 + responses: + '200': + description: success + schema: + type: array + items: + $ref: '#/definitions/Syllable' + '400': + description: Invalid word supplied. + /words.json/wordOfTheDay: + get: + tags: + - words + summary: Returns a specific WordOfTheDay + operationId: getWordOfTheDay + parameters: + - name: date + in: query + description: Fetches by date in yyyy-MM-dd + required: false + type: string + responses: + default: + description: success + schema: + $ref: '#/definitions/WordOfTheDay' +definitions: + Syllable: + properties: + text: + type: string + seq: + type: integer + format: int32 + type: + type: string + StringValue: + properties: + word: + type: string + AuthenticationToken: + properties: + token: + type: string + userId: + type: integer + format: int64 + userSignature: + type: string + Sentence: + properties: + hasScoredWords: + type: boolean + id: + type: integer + format: int64 + scoredWords: + type: array + items: + $ref: '#/definitions/ScoredWord' + display: + type: string + rating: + type: integer + format: int32 + documentMetadataId: + type: integer + format: int64 + ExampleSearchResults: + properties: + facets: + type: array + items: + $ref: '#/definitions/Facet' + examples: + type: array + items: + $ref: '#/definitions/Example' + WordSearchResults: + properties: + searchResults: + type: array + items: + $ref: '#/definitions/WordSearchResult' + totalResults: + type: integer + format: int32 + SimpleDefinition: + properties: + text: + type: string + source: + type: string + note: + type: string + partOfSpeech: + type: string + Citation: + properties: + cite: + type: string + source: + type: string + WordList: + properties: + numberWordsInList: + type: integer + format: int64 + userId: + type: integer + format: int64 + name: + type: string + permalink: + type: string + updatedAt: + type: string + format: date-time + username: + type: string + lastActivityAt: + type: string + format: date-time + type: + type: string + id: + type: integer + format: int64 + createdAt: + type: string + format: date-time + description: + type: string + WordObject: + properties: + id: + type: integer + format: int64 + word: + type: string + originalWord: + type: string + suggestions: + type: array + items: + type: string + canonicalForm: + type: string + vulgar: + type: string + Example: + properties: + sentence: + $ref: '#/definitions/Sentence' + exampleId: + type: integer + format: int64 + word: + type: string + text: + type: string + url: + type: string + provider: + $ref: '#/definitions/ContentProvider' + score: + $ref: '#/definitions/ScoredWord' + documentId: + type: integer + format: int64 + title: + type: string + id: + type: integer + format: int64 + year: + type: integer + format: int32 + rating: + type: number + format: float + ContentProvider: + properties: + id: + type: integer + format: int32 + name: + type: string + FrequencySummary: + properties: + unknownYearCount: + type: integer + format: int32 + totalCount: + type: integer + format: int64 + frequencyString: + type: string + word: + type: string + frequency: + type: array + items: + $ref: '#/definitions/Frequency' + Related: + properties: + label1: + type: string + relationshipType: + type: string + label2: + type: string + label3: + type: string + words: + type: array + items: + type: string + gram: + type: string + label4: + type: string + User: + properties: + id: + type: integer + format: int64 + username: + type: string + email: + type: string + status: + type: integer + format: int32 + faceBookId: + type: string + userName: + type: string + displayName: + type: string + password: + type: string + WordOfTheDay: + properties: + definitions: + type: array + items: + $ref: '#/definitions/SimpleDefinition' + htmlExtra: + type: string + parentId: + type: string + examples: + type: array + items: + $ref: '#/definitions/SimpleExample' + contentProvider: + $ref: '#/definitions/ContentProvider' + word: + type: string + note: + type: string + id: + type: integer + format: int64 + createdAt: + type: string + format: date-time + publishDate: + type: string + format: date-time + category: + type: string + createdBy: + type: string + TextPron: + properties: + raw: + type: string + seq: + type: integer + format: int32 + rawType: + type: string + WordSearchResult: + properties: + count: + type: integer + format: int64 + lexicality: + type: number + format: double + word: + type: string + ApiTokenStatus: + properties: + valid: + type: boolean + token: + type: string + resetsInMillis: + type: integer + format: int64 + remainingCalls: + type: integer + format: int64 + expiresInMillis: + type: integer + format: int64 + totalRequests: + type: integer + format: int64 + Note: + properties: + noteType: + type: string + appliesTo: + type: array + items: + type: string + value: + type: string + pos: + type: integer + format: int32 + WordListWord: + properties: + id: + type: integer + format: int64 + word: + type: string + username: + type: string + userId: + type: integer + format: int64 + createdAt: + type: string + format: date-time + numberCommentsOnWord: + type: integer + format: int64 + numberLists: + type: integer + format: int64 + AudioFile: + properties: + voteCount: + type: integer + format: int32 + word: + type: string + attributionText: + type: string + audioType: + type: string + attributionUrl: + type: string + commentCount: + type: integer + format: int32 + fileUrl: + type: string + voteAverage: + type: number + format: float + duration: + type: number + format: double + id: + type: integer + format: int64 + createdAt: + type: string + format: date-time + voteWeightedAverage: + type: number + format: float + description: + type: string + createdBy: + type: string + Definition: + properties: + notes: + type: array + items: + $ref: '#/definitions/Note' + sequence: + type: string + textProns: + type: array + items: + $ref: '#/definitions/TextPron' + extendedText: + type: string + word: + type: string + attributionText: + type: string + citations: + type: array + items: + $ref: '#/definitions/Citation' + partOfSpeech: + type: string + text: + type: string + attributionUrl: + type: string + seqString: + type: string + sourceDictionary: + type: string + score: + type: number + format: float + exampleUses: + type: array + items: + $ref: '#/definitions/ExampleUsage' + relatedWords: + type: array + items: + $ref: '#/definitions/Related' + labels: + type: array + items: + $ref: '#/definitions/Label' + Label: + properties: + text: + type: string + type: + type: string + Facet: + properties: + facetValues: + type: array + items: + $ref: '#/definitions/FacetValue' + name: + type: string + ExampleUsage: + properties: + text: + type: string + SimpleExample: + properties: + id: + type: integer + format: int64 + title: + type: string + text: + type: string + url: + type: string + FacetValue: + properties: + count: + type: integer + format: int64 + value: + type: string + DefinitionSearchResults: + properties: + results: + type: array + items: + $ref: '#/definitions/Definition' + totalResults: + type: integer + format: int32 + Frequency: + properties: + count: + type: integer + format: int64 + year: + type: integer + format: int32 + ScoredWord: + properties: + wordType: + type: string + lemma: + type: string + position: + type: integer + format: int32 + word: + type: string + docTermCount: + type: integer + format: int32 + stopword: + type: boolean + partOfSpeech: + type: string + score: + type: number + format: float + baseWordScore: + type: number + format: double + id: + type: integer + format: int64 + sentenceId: + type: integer + format: int64 + Bigram: + properties: + count: + type: integer + format: int64 + gram2: + type: string + gram1: + type: string + wlmi: + type: number + format: double + mi: + type: number + format: double \ No newline at end of file diff --git a/modules/swagger-generator/pom.xml b/modules/swagger-generator/pom.xml index b42a51a86af0..4f8794c331b4 100644 --- a/modules/swagger-generator/pom.xml +++ b/modules/swagger-generator/pom.xml @@ -4,7 +4,7 @@ io.swagger swagger-codegen-project - 2.1.4-SNAPSHOT + 2.1.5-SNAPSHOT ../.. swagger-generator diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java b/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java index a81113ab76a1..a13995505c7c 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java @@ -49,6 +49,8 @@ public class Bootstrap extends HttpServlet { bc.setVersion("0.0.0"); } } + + bc.setSchemes(new String[]{"https"}); bc.setHost("generator.swagger.io"); bc.setLicenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html"); bc.setResourcePackage("io.swagger.generator.resource"); diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java b/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java index 775c96cda2ea..18e883effbf0 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java @@ -17,22 +17,44 @@ import io.swagger.util.Json; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.apache.commons.lang3.StringUtils.isNotEmpty; - import java.io.File; import java.util.ArrayList; import java.util.List; +import java.util.Map; public class Generator { static Logger LOGGER = LoggerFactory.getLogger(Generator.class); + public enum Type { + CLIENT("client"), + SERVER("server"); + + private String name; + + Type(String name) { + this.name = name; + } + + String getTypeName() { + return name; + } + } + public static String generateClient(String language, GeneratorInput opts) throws ApiException { - Swagger swagger; - LOGGER.debug("generate client for " + language); + return generate(language, opts, Type.CLIENT); + } + + public static String generateServer(String language, GeneratorInput opts) throws ApiException { + return generate(language, opts, Type.SERVER); + } + + private static String generate(String language, GeneratorInput opts, Type type) throws ApiException { + LOGGER.debug(String.format("generate %s for %s", type.getTypeName(), language)); if (opts == null) { throw new BadRequestException(400, "No options were supplied"); } JsonNode node = opts.getSpec(); + Swagger swagger; if (node == null) { if (opts.getSwaggerUrl() != null) { swagger = new SwaggerParser().read(opts.getSwaggerUrl()); @@ -48,7 +70,8 @@ public class Generator { ClientOptInput clientOptInput = new ClientOptInput(); ClientOpts clientOpts = new ClientOpts(); - String outputFolder = getTmpFolder().getAbsolutePath() + File.separator + language + "-client"; + String outputFolder = getTmpFolder().getAbsolutePath() + File.separator + language + "-" + + type.getTypeName(); String outputFilename = outputFolder + "-bundle.zip"; clientOptInput @@ -61,17 +84,9 @@ public class Generator { } catch(RuntimeException e) { throw new BadRequestException(400, "Unsupported target " + language + " supplied"); } - + if (opts.getOptions() != null) { - for(String key : new String[]{"apiPackage", "modelPackage", "invokerPackage", "groupId", "artifactId", "artifactVersion"}) { - if(isNotEmpty(opts.getOptions().get(key))) { - codegenConfig.additionalProperties().put(key , opts.getOptions().get(key)); - } - } - - if (isNotEmpty(opts.getOptions().get("library"))) { - codegenConfig.setLibrary(opts.getOptions().get("library")); - } + codegenConfig.additionalProperties().putAll(opts.getOptions()); } codegenConfig.setOutputDir(outputFolder); @@ -97,65 +112,6 @@ public class Generator { return outputFilename; } - public static String generateServer(String language, GeneratorInput opts) throws ApiException { - LOGGER.debug("generate server for " + language); - Swagger swagger; - if (opts == null) { - throw new BadRequestException(400, "No options were supplied"); - } - if (opts == null) { - throw new BadRequestException(400, "No options were supplied"); - } - JsonNode node = opts.getSpec(); - if (node == null) { - if (opts.getSwaggerUrl() != null) { - swagger = new SwaggerParser().read(opts.getSwaggerUrl()); - } else { - throw new BadRequestException(400, "No swagger specification was supplied"); - } - } else { - swagger = new SwaggerParser().read(node, true); - } - if (swagger == null) { - throw new BadRequestException(400, "The swagger specification supplied was not valid"); - } - - ClientOptInput clientOptInput = new ClientOptInput(); - ClientOpts clientOpts = new ClientOpts(); - String outputFolder = getTmpFolder().getAbsolutePath() + File.separator + language + "-server"; - String outputFilename = outputFolder + "-bundle.zip"; - - clientOptInput - .opts(clientOpts) - .swagger(swagger); - - CodegenConfig codegenConfig = Codegen.getConfig(language); - if (codegenConfig == null) { - throw new BadRequestException(400, "Unsupported target " + language + " supplied"); - } - - codegenConfig.setOutputDir(outputFolder); - - Json.prettyPrint(clientOpts); - - clientOptInput.setConfig(codegenConfig); - - try { - List files = new Codegen().opts(clientOptInput).generate(); - if (files.size() > 0) { - List filesToAdd = new ArrayList(); - filesToAdd.add(new File(outputFolder)); - ZipUtil zip = new ZipUtil(); - zip.compressFiles(filesToAdd, outputFilename); - } else { - throw new BadRequestException(400, "A target generation was attempted, but no files were created!"); - } - } catch (Exception e) { - throw new BadRequestException(500, "Unable to build target: " + e.getMessage()); - } - return outputFilename; - } - public static InputOption clientOptions(String language) { return null; } diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java b/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java index ddfd6fa39502..fa6a4785c5b9 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java @@ -21,10 +21,7 @@ import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.servlet.http.HttpServletRequest; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; @Path("/gen") @Api(value = "/gen", description = "Resource for generating swagger components") @@ -68,8 +65,17 @@ public class SwaggerResource { @ApiParam(value = "Configuration for building the client library", required = true) GeneratorInput opts) throws Exception { String filename = Generator.generateClient(language, opts); + String scheme = request.getHeader("X-SSL"); + String port = ""; + if("1".equals(scheme)) { + scheme = "https"; + } + else { + scheme = request.getScheme(); + port = ":" + request.getServerPort(); + } - String host = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort(); + String host = scheme + "://" + request.getServerName() + port; if (filename != null) { String code = String.valueOf(System.currentTimeMillis()); Generated g = new Generated(); diff --git a/modules/swagger-generator/src/main/webapp/index.html b/modules/swagger-generator/src/main/webapp/index.html index 021310d9dec8..5a19fbffa431 100644 --- a/modules/swagger-generator/src/main/webapp/index.html +++ b/modules/swagger-generator/src/main/webapp/index.html @@ -27,7 +27,7 @@ if (url && url.length > 1) { url = decodeURIComponent(url[1]); } else { - url = "http://generator.swagger.io/api/swagger.json"; + url = "https://generator.swagger.io/api/swagger.json"; } window.swaggerUi = new SwaggerUi({ url: url, diff --git a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineGeneratorOptionsTest.java b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineGeneratorOptionsTest.java new file mode 100644 index 000000000000..e6eb42abb355 --- /dev/null +++ b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineGeneratorOptionsTest.java @@ -0,0 +1,97 @@ +package io.swagger.generator.online; + +import static org.testng.Assert.assertNotEquals; + +import io.swagger.generator.exception.ApiException; +import io.swagger.generator.model.GeneratorInput; +import io.swagger.generator.online.Generator; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.Maps; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.testng.annotations.Test; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; + +public abstract class OnlineGeneratorOptionsTest { + private final boolean isServer; + private final String language; + + protected OnlineGeneratorOptionsTest(String language, boolean isServer) { + this.language = language; + this.isServer = isServer; + } + + @Test + public void optionsTest() throws ApiException, IOException { + final GeneratorInput input = new GeneratorInput(); + final HashMap options = convertOptions(); + + final Maps.EntryTransformer transformer = + new Maps.EntryTransformer() { + public String transformEntry(String key, InvocationCounter value) { + return value.getValue(); + } + }; + + input.setOptions(Maps.transformEntries(options, transformer)); + final ObjectMapper mapper = new ObjectMapper(); + input.setSpec(mapper.readTree(loadClassResource(getClass(), "petstore.json"))); + String outputFilename; + if (isServer) { + outputFilename = Generator.generateServer(language, input); + } else { + outputFilename = Generator.generateClient(language, input); + } + final File dir = new File(new File(outputFilename).getParent()); + FileUtils.deleteDirectory(dir); + for (InvocationCounter option : options.values()) { + assertNotEquals(option.getCounter(), 0, String.format("Option \"%s\" wasn't processed.", + option.getValue())); + } + } + + protected abstract Map getOptions(); + + private HashMap convertOptions() { + HashMap options = new HashMap(); + for (Map.Entry entry : getOptions().entrySet()) { + options.put(entry.getKey(), new InvocationCounter(entry.getValue())); + } + return options; + } + + private static String loadClassResource(Class cls, String name) throws IOException { + InputStream in = null; + try { + in = cls.getClassLoader().getResourceAsStream(name); + return IOUtils.toString(in, StandardCharsets.UTF_8); + } finally { + IOUtils.closeQuietly(in); + } + } + + private static class InvocationCounter { + private String value; + private int counter; + + public InvocationCounter(String value) { + this.value = value; + } + + public int getCounter() { + return counter; + } + + public String getValue() { + ++counter; + return value; + } + } +} diff --git a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java new file mode 100644 index 000000000000..50605cff1109 --- /dev/null +++ b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java @@ -0,0 +1,34 @@ +package io.swagger.generator.online; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class OnlineJavaClientOptionsTest extends OnlineGeneratorOptionsTest { + + public OnlineJavaClientOptionsTest() { + super("java", false); + } + + protected OnlineJavaClientOptionsTest(String language, boolean isServer) { + super(language, isServer); + } + + @Override + protected Map getOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put("modelPackage", "package") + .put("apiPackage", "apiPackage") + .put("sortParamsByRequiredFlag", "false") + .put("invokerPackage", "io.swagger.client.test") + .put("groupId", "io.swagger.test") + .put("artifactId", "swagger-java-client-test") + .put("artifactVersion", "1.0.0-SNAPSHOT") + .put("sourceFolder", "src/main/java/test") + .put("localVariablePrefix", "tst") + .put("serializableModel", "false") + .put("fullJavaUtil", "true") + .put("library", "jersey2") + .build(); + } +} diff --git a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJaxRSServerOptionsTest.java b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJaxRSServerOptionsTest.java new file mode 100644 index 000000000000..c64466fe696e --- /dev/null +++ b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJaxRSServerOptionsTest.java @@ -0,0 +1,9 @@ +package io.swagger.generator.online; + +public class OnlineJaxRSServerOptionsTest extends OnlineJavaClientOptionsTest{ + + public OnlineJaxRSServerOptionsTest() { + super("jaxrs", true); + } + +} diff --git a/modules/swagger-generator/src/test/resources/petstore.json b/modules/swagger-generator/src/test/resources/petstore.json new file mode 100644 index 000000000000..67c4d47292da --- /dev/null +++ b/modules/swagger-generator/src/test/resources/petstore.json @@ -0,0 +1,1030 @@ +{ + "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 seperated 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", + "enum": [ + "available", + "pending", + "sold" + ], + "default": "available" + }, + "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": "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", + "operationId": "findPetsByTags", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "tags", + "in": "query", + "description": "Tags to filter by", + "required": true, + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "csv" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } + } + }, + "400": { + "description": "Invalid tag value" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/{petId}": { + "get": { + "tags": [ + "pet" + ], + "summary": "Find pet by ID", + "description": "Returns a single pet", + "operationId": "getPetById", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet to return", + "required": true, + "type": "integer", + "format": "int64" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Pet" + } + }, + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Pet not found" + } + }, + "security": [ + { + "api_key": [] + } + ] + }, + "post": { + "tags": [ + "pet" + ], + "summary": "Updates a pet in the store with form data", + "description": "", + "operationId": "updatePetWithForm", + "consumes": [ + "application/x-www-form-urlencoded" + ], + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet that needs to be updated", + "required": true, + "type": "integer", + "format": "int64" + }, + { + "name": "name", + "in": "formData", + "description": "Updated name of the pet", + "required": false, + "type": "string" + }, + { + "name": "status", + "in": "formData", + "description": "Updated status of the pet", + "required": false, + "type": "string" + } + ], + "responses": { + "405": { + "description": "Invalid input" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + }, + "delete": { + "tags": [ + "pet" + ], + "summary": "Deletes a pet", + "description": "", + "operationId": "deletePet", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "api_key", + "in": "header", + "required": false, + "type": "string" + }, + { + "name": "petId", + "in": "path", + "description": "Pet id to delete", + "required": true, + "type": "integer", + "format": "int64" + } + ], + "responses": { + "400": { + "description": "Invalid pet value" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/{petId}/uploadImage": { + "post": { + "tags": [ + "pet" + ], + "summary": "uploads an image", + "description": "", + "operationId": "uploadFile", + "consumes": [ + "multipart/form-data" + ], + "produces": [ + "application/json" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet to update", + "required": true, + "type": "integer", + "format": "int64" + }, + { + "name": "additionalMetadata", + "in": "formData", + "description": "Additional data to pass to server", + "required": false, + "type": "string" + }, + { + "name": "file", + "in": "formData", + "description": "file to upload", + "required": false, + "type": "file" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/ApiResponse" + } + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/store/inventory": { + "get": { + "tags": [ + "store" + ], + "summary": "Returns pet inventories by status", + "description": "Returns a map of status codes to quantities", + "operationId": "getInventory", + "produces": [ + "application/json" + ], + "parameters": [], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "object", + "additionalProperties": { + "type": "integer", + "format": "int32" + } + } + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, + "/store/order": { + "post": { + "tags": [ + "store" + ], + "summary": "Place an order for a pet", + "description": "", + "operationId": "placeOrder", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "order placed for purchasing the pet", + "required": true, + "schema": { + "$ref": "#/definitions/Order" + } + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Order" + } + }, + "400": { + "description": "Invalid Order" + } + } + } + }, + "/store/order/{orderId}": { + "get": { + "tags": [ + "store" + ], + "summary": "Find purchase order by ID", + "description": "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", + "operationId": "getOrderById", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "orderId", + "in": "path", + "description": "ID of pet that needs to be fetched", + "required": true, + "type": "integer", + "maximum": 5.0, + "minimum": 1.0, + "format": "int64" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Order" + } + }, + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Order not found" + } + } + }, + "delete": { + "tags": [ + "store" + ], + "summary": "Delete purchase order by ID", + "description": "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", + "operationId": "deleteOrder", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "orderId", + "in": "path", + "description": "ID of the order that needs to be deleted", + "required": true, + "type": "string", + "minimum": 1.0 + } + ], + "responses": { + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Order not found" + } + } + } + }, + "/user": { + "post": { + "tags": [ + "user" + ], + "summary": "Create user", + "description": "This can only be done by the logged in user.", + "operationId": "createUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Created user object", + "required": true, + "schema": { + "$ref": "#/definitions/User" + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/createWithArray": { + "post": { + "tags": [ + "user" + ], + "summary": "Creates list of users with given input array", + "description": "", + "operationId": "createUsersWithArrayInput", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "List of user object", + "required": true, + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/User" + } + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/createWithList": { + "post": { + "tags": [ + "user" + ], + "summary": "Creates list of users with given input array", + "description": "", + "operationId": "createUsersWithListInput", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "List of user object", + "required": true, + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/User" + } + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/login": { + "get": { + "tags": [ + "user" + ], + "summary": "Logs user into the system", + "description": "", + "operationId": "loginUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "username", + "in": "query", + "description": "The user name for login", + "required": true, + "type": "string" + }, + { + "name": "password", + "in": "query", + "description": "The password for login in clear text", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "string" + }, + "headers": { + "X-Rate-Limit": { + "type": "integer", + "format": "int32", + "description": "calls per hour allowed by the user" + }, + "X-Expires-After": { + "type": "string", + "format": "date-time", + "description": "date in UTC when toekn expires" + } + } + }, + "400": { + "description": "Invalid username/password supplied" + } + } + } + }, + "/user/logout": { + "get": { + "tags": [ + "user" + ], + "summary": "Logs out current logged in user session", + "description": "", + "operationId": "logoutUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/{username}": { + "get": { + "tags": [ + "user" + ], + "summary": "Get user by user name", + "description": "", + "operationId": "getUserByName", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "The name that needs to be fetched. Use user1 for testing. ", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/User" + } + }, + "400": { + "description": "Invalid username supplied" + }, + "404": { + "description": "User not found" + } + } + }, + "put": { + "tags": [ + "user" + ], + "summary": "Updated user", + "description": "This can only be done by the logged in user.", + "operationId": "updateUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "name that need to be deleted", + "required": true, + "type": "string" + }, + { + "in": "body", + "name": "body", + "description": "Updated user object", + "required": true, + "schema": { + "$ref": "#/definitions/User" + } + } + ], + "responses": { + "400": { + "description": "Invalid user supplied" + }, + "404": { + "description": "User not found" + } + } + }, + "delete": { + "tags": [ + "user" + ], + "summary": "Delete user", + "description": "This can only be done by the logged in user.", + "operationId": "deleteUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "The name that needs to be deleted", + "required": true, + "type": "string" + } + ], + "responses": { + "400": { + "description": "Invalid username supplied" + }, + "404": { + "description": "User not found" + } + } + } + } + }, + "securityDefinitions": { + "petstore_auth": { + "type": "oauth2", + "authorizationUrl": "http://petstore.swagger.io/api/oauth/dialog", + "flow": "implicit", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + }, + "api_key": { + "type": "apiKey", + "name": "api_key", + "in": "header" + } + }, + "definitions": { + "Order": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "petId": { + "type": "integer", + "format": "int64" + }, + "quantity": { + "type": "integer", + "format": "int32" + }, + "shipDate": { + "type": "string", + "format": "date-time" + }, + "status": { + "type": "string", + "description": "Order Status", + "enum": [ + "placed", + "approved", + "delivered" + ] + }, + "complete": { + "type": "boolean", + "default": false + } + }, + "xml": { + "name": "Order" + } + }, + "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" + } + }, + "Category": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "xml": { + "name": "Category" + } + }, + "Tag": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "xml": { + "name": "Tag" + } + }, + "ApiResponse": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "type": { + "type": "string" + }, + "message": { + "type": "string" + } + } + }, + "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" + } + } + }, + "externalDocs": { + "description": "Find out more about Swagger", + "url": "http://swagger.io" + } +} diff --git a/pom.xml b/pom.xml index 27ce57442785..466b8f300b8a 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ swagger-codegen-project pom swagger-codegen-project - 2.1.4-SNAPSHOT + 2.1.5-SNAPSHOT https://github.com/swagger-api/swagger-codegen scm:git:git@github.com:swagger-api/swagger-codegen.git @@ -517,11 +517,11 @@ - 1.0.11-SNAPSHOT + 1.0.11 2.11.1 2.3.4 - 1.5.4-SNAPSHOT - 2.1.4 + 1.5.4 + 2.1.5-SNAPSHOT 2.3 1.2 4.8.1 diff --git a/samples/client/petstore/akka-scala/pom.xml b/samples/client/petstore/akka-scala/pom.xml index a047ad86cc01..a6e81fb75f4f 100644 --- a/samples/client/petstore/akka-scala/pom.xml +++ b/samples/client/petstore/akka-scala/pom.xml @@ -217,7 +217,7 @@ 2.3.9 1.2 2.2 - 1.5.0 + 1.5.4 1.0.0 4.8.1 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 591d055dad6b..7decd51b03c0 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 @@ -11,18 +11,18 @@ object PetApi { /** * * Expected answers: - * code 405 : (Validation exception) - * code 404 : (Pet not found) * code 400 : (Invalid ID supplied) + * code 404 : (Pet not found) + * code 405 : (Validation exception) * * @param body Pet object that needs to be added to the store */ def updatePet(body: Option[Pet] = None): ApiRequest[Unit] = ApiRequest[Unit](ApiMethods.PUT, "http://petstore.swagger.io/v2", "/pet", "application/json") .withBody(body) - .withErrorResponse[Unit](405) - .withErrorResponse[Unit](404) .withErrorResponse[Unit](400) + .withErrorResponse[Unit](404) + .withErrorResponse[Unit](405) /** * @@ -70,9 +70,9 @@ object PetApi { * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions * * Expected answers: - * code 404 : (Pet not found) * code 200 : Pet (successful operation) * code 400 : (Invalid ID supplied) + * code 404 : (Pet not found) * * Available security schemes: * api_key (apiKey) @@ -83,9 +83,9 @@ object PetApi { ApiRequest[Pet](ApiMethods.GET, "http://petstore.swagger.io/v2", "/pet/{petId}", "application/json") .withApiKey(apiKey, "api_key", HEADER) .withPathParam("petId", petId) - .withErrorResponse[Unit](404) .withSuccessResponse[Pet](200) .withErrorResponse[Unit](400) + .withErrorResponse[Unit](404) /** * diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/StoreApi.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/StoreApi.scala index 686e85e105dc..f3ab28da05f2 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/StoreApi.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/StoreApi.scala @@ -39,33 +39,33 @@ object StoreApi { * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * * Expected answers: - * code 404 : (Order not found) * code 200 : Order (successful operation) * code 400 : (Invalid ID supplied) + * code 404 : (Order not found) * * @param orderId ID of pet that needs to be fetched */ def getOrderById(orderId: String): ApiRequest[Order] = ApiRequest[Order](ApiMethods.GET, "http://petstore.swagger.io/v2", "/store/order/{orderId}", "application/json") .withPathParam("orderId", orderId) - .withErrorResponse[Unit](404) .withSuccessResponse[Order](200) .withErrorResponse[Unit](400) + .withErrorResponse[Unit](404) /** * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * * Expected answers: - * code 404 : (Order not found) * code 400 : (Invalid ID supplied) + * code 404 : (Order not found) * * @param orderId ID of the order that needs to be deleted */ def deleteOrder(orderId: String): ApiRequest[Unit] = ApiRequest[Unit](ApiMethods.DELETE, "http://petstore.swagger.io/v2", "/store/order/{orderId}", "application/json") .withPathParam("orderId", orderId) - .withErrorResponse[Unit](404) .withErrorResponse[Unit](400) + .withErrorResponse[Unit](404) diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/UserApi.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/UserApi.scala index 4c2ab10e9e7b..b759a799e3dc 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/UserApi.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/UserApi.scala @@ -72,25 +72,25 @@ object UserApi { /** * * Expected answers: - * code 404 : (User not found) * code 200 : User (successful operation) * code 400 : (Invalid username supplied) + * code 404 : (User not found) * - * @param username The name that needs to be fetched. Use user1 for testing. + * @param username The name that needs to be fetched. Use user1 for testing. */ def getUserByName(username: String): ApiRequest[User] = ApiRequest[User](ApiMethods.GET, "http://petstore.swagger.io/v2", "/user/{username}", "application/json") .withPathParam("username", username) - .withErrorResponse[Unit](404) .withSuccessResponse[User](200) .withErrorResponse[Unit](400) + .withErrorResponse[Unit](404) /** * This can only be done by the logged in user. * * Expected answers: - * code 404 : (User not found) * code 400 : (Invalid user supplied) + * code 404 : (User not found) * * @param username name that need to be deleted * @param body Updated user object @@ -99,23 +99,23 @@ object UserApi { ApiRequest[Unit](ApiMethods.PUT, "http://petstore.swagger.io/v2", "/user/{username}", "application/json") .withBody(body) .withPathParam("username", username) - .withErrorResponse[Unit](404) .withErrorResponse[Unit](400) + .withErrorResponse[Unit](404) /** * This can only be done by the logged in user. * * Expected answers: - * code 404 : (User not found) * code 400 : (Invalid username supplied) + * code 404 : (User not found) * * @param username The name that needs to be deleted */ def deleteUser(username: String): ApiRequest[Unit] = ApiRequest[Unit](ApiMethods.DELETE, "http://petstore.swagger.io/v2", "/user/{username}", "application/json") .withPathParam("username", username) - .withErrorResponse[Unit](404) .withErrorResponse[Unit](400) + .withErrorResponse[Unit](404) diff --git a/samples/client/petstore/android-java/pom.xml b/samples/client/petstore/android-java/pom.xml index 639000ecc6d9..f9c620b7528e 100644 --- a/samples/client/petstore/android-java/pom.xml +++ b/samples/client/petstore/android-java/pom.xml @@ -145,7 +145,7 @@ - 1.5.0 + 1.5.4 2.3.1 4.8.1 1.0.0 diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/UserApi.java index a16a745c7f8a..4c1bf7b1a3dd 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/UserApi.java @@ -316,7 +316,7 @@ public class UserApi { /** * Get user by user name * - * @param username The name that needs to be fetched. Use user1 for testing. + * @param username The name that needs to be fetched. Use user1 for testing. * @return User */ public User getUserByName (String username) throws ApiException { diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java index 90a840e6e422..20865ad54340 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java @@ -18,9 +18,9 @@ public class Pet { @SerializedName("name") private String name = null; @SerializedName("photoUrls") - private List photoUrls = new ArrayList() ; + private List photoUrls = null; @SerializedName("tags") - private List tags = new ArrayList() ; + private List tags = null; public enum StatusEnum { available, pending, sold, }; 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 4b6a2b155d9a..84b6ba4c7ead 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 @@ -145,8 +145,9 @@ class PetApi(client: TransportClient, config: SwaggerConfig) extends ApiClient(c } - def deletePet(apiKey: Option[String] = None, - petId: Long)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + def deletePet(petId: Long, + apiKey: Option[String] = None + )(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { // create path and map variables val path = (addFmt("/pet/{petId}") replaceAll ("\\{" + "petId" + "\\}",petId.toString)) diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs index 4e7e84fb7251..00bd7a5e9f2e 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs @@ -248,7 +248,7 @@ namespace IO.Swagger.Api { - var path = "/pet"; + var path_ = "/pet"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -279,7 +279,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling UpdatePet: " + response.Content, response.Content); @@ -298,7 +298,7 @@ namespace IO.Swagger.Api { - var path = "/pet"; + var path_ = "/pet"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -329,7 +329,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling UpdatePet: " + response.Content, response.Content); @@ -346,7 +346,7 @@ namespace IO.Swagger.Api { - var path = "/pet"; + var path_ = "/pet"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -377,7 +377,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling AddPet: " + response.Content, response.Content); @@ -396,7 +396,7 @@ namespace IO.Swagger.Api { - var path = "/pet"; + var path_ = "/pet"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -427,7 +427,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling AddPet: " + response.Content, response.Content); @@ -444,7 +444,7 @@ namespace IO.Swagger.Api { - var path = "/pet/findByStatus"; + var path_ = "/pet/findByStatus"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -475,14 +475,14 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByStatus: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByStatus: " + response.ErrorMessage, response.ErrorMessage); - return (List) ApiClient.Deserialize(response.Content, typeof(List), response.Headers); + return (List) ApiClient.Deserialize(response, typeof(List)); } /// @@ -494,7 +494,7 @@ namespace IO.Swagger.Api { - var path = "/pet/findByStatus"; + var path_ = "/pet/findByStatus"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -525,11 +525,11 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByStatus: " + response.Content, response.Content); - return (List) ApiClient.Deserialize(response.Content, typeof(List), response.Headers); + return (List) ApiClient.Deserialize(response, typeof(List)); } /// @@ -541,7 +541,7 @@ namespace IO.Swagger.Api { - var path = "/pet/findByTags"; + var path_ = "/pet/findByTags"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -572,14 +572,14 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByTags: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByTags: " + response.ErrorMessage, response.ErrorMessage); - return (List) ApiClient.Deserialize(response.Content, typeof(List), response.Headers); + return (List) ApiClient.Deserialize(response, typeof(List)); } /// @@ -591,7 +591,7 @@ namespace IO.Swagger.Api { - var path = "/pet/findByTags"; + var path_ = "/pet/findByTags"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -622,11 +622,11 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByTags: " + response.Content, response.Content); - return (List) ApiClient.Deserialize(response.Content, typeof(List), response.Headers); + return (List) ApiClient.Deserialize(response, typeof(List)); } /// @@ -641,7 +641,7 @@ namespace IO.Swagger.Api if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling GetPetById"); - var path = "/pet/{petId}"; + var path_ = "/pet/{petId}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -669,17 +669,17 @@ namespace IO.Swagger.Api // authentication setting, if any - String[] authSettings = new String[] { "api_key", "petstore_auth" }; + String[] authSettings = new String[] { "api_key" }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetPetById: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling GetPetById: " + response.ErrorMessage, response.ErrorMessage); - return (Pet) ApiClient.Deserialize(response.Content, typeof(Pet), response.Headers); + return (Pet) ApiClient.Deserialize(response, typeof(Pet)); } /// @@ -693,7 +693,7 @@ namespace IO.Swagger.Api if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling GetPetById"); - var path = "/pet/{petId}"; + var path_ = "/pet/{petId}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -721,14 +721,14 @@ namespace IO.Swagger.Api // authentication setting, if any - String[] authSettings = new String[] { "api_key", "petstore_auth" }; + String[] authSettings = new String[] { "api_key" }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetPetById: " + response.Content, response.Content); - return (Pet) ApiClient.Deserialize(response.Content, typeof(Pet), response.Headers); + return (Pet) ApiClient.Deserialize(response, typeof(Pet)); } /// @@ -745,7 +745,7 @@ namespace IO.Swagger.Api if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling UpdatePetWithForm"); - var path = "/pet/{petId}"; + var path_ = "/pet/{petId}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -778,7 +778,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling UpdatePetWithForm: " + response.Content, response.Content); @@ -801,7 +801,7 @@ namespace IO.Swagger.Api if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling UpdatePetWithForm"); - var path = "/pet/{petId}"; + var path_ = "/pet/{petId}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -834,7 +834,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling UpdatePetWithForm: " + response.Content, response.Content); @@ -855,7 +855,7 @@ namespace IO.Swagger.Api if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling DeletePet"); - var path = "/pet/{petId}"; + var path_ = "/pet/{petId}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -887,7 +887,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling DeletePet: " + response.Content, response.Content); @@ -909,7 +909,7 @@ namespace IO.Swagger.Api if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling DeletePet"); - var path = "/pet/{petId}"; + var path_ = "/pet/{petId}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -941,7 +941,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling DeletePet: " + response.Content, response.Content); @@ -963,7 +963,7 @@ namespace IO.Swagger.Api if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling UploadFile"); - var path = "/pet/{petId}/uploadImage"; + var path_ = "/pet/{petId}/uploadImage"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -996,7 +996,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling UploadFile: " + response.Content, response.Content); @@ -1019,7 +1019,7 @@ namespace IO.Swagger.Api if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling UploadFile"); - var path = "/pet/{petId}/uploadImage"; + var path_ = "/pet/{petId}/uploadImage"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -1052,7 +1052,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling UploadFile: " + response.Content, response.Content); diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs index f96b773c76f9..b0a439ddf1a9 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs @@ -155,7 +155,7 @@ namespace IO.Swagger.Api { - var path = "/store/inventory"; + var path_ = "/store/inventory"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -185,14 +185,14 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "api_key" }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.ErrorMessage, response.ErrorMessage); - return (Dictionary) ApiClient.Deserialize(response.Content, typeof(Dictionary), response.Headers); + return (Dictionary) ApiClient.Deserialize(response, typeof(Dictionary)); } /// @@ -203,7 +203,7 @@ namespace IO.Swagger.Api { - var path = "/store/inventory"; + var path_ = "/store/inventory"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -233,11 +233,11 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "api_key" }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.Content, response.Content); - return (Dictionary) ApiClient.Deserialize(response.Content, typeof(Dictionary), response.Headers); + return (Dictionary) ApiClient.Deserialize(response, typeof(Dictionary)); } /// @@ -249,7 +249,7 @@ namespace IO.Swagger.Api { - var path = "/store/order"; + var path_ = "/store/order"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -280,14 +280,14 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.ErrorMessage, response.ErrorMessage); - return (Order) ApiClient.Deserialize(response.Content, typeof(Order), response.Headers); + return (Order) ApiClient.Deserialize(response, typeof(Order)); } /// @@ -299,7 +299,7 @@ namespace IO.Swagger.Api { - var path = "/store/order"; + var path_ = "/store/order"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -330,11 +330,11 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.Content, response.Content); - return (Order) ApiClient.Deserialize(response.Content, typeof(Order), response.Headers); + return (Order) ApiClient.Deserialize(response, typeof(Order)); } /// @@ -349,7 +349,7 @@ namespace IO.Swagger.Api if (orderId == null) throw new ApiException(400, "Missing required parameter 'orderId' when calling GetOrderById"); - var path = "/store/order/{orderId}"; + var path_ = "/store/order/{orderId}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -380,14 +380,14 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.ErrorMessage, response.ErrorMessage); - return (Order) ApiClient.Deserialize(response.Content, typeof(Order), response.Headers); + return (Order) ApiClient.Deserialize(response, typeof(Order)); } /// @@ -401,7 +401,7 @@ namespace IO.Swagger.Api if (orderId == null) throw new ApiException(400, "Missing required parameter 'orderId' when calling GetOrderById"); - var path = "/store/order/{orderId}"; + var path_ = "/store/order/{orderId}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -432,11 +432,11 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.Content, response.Content); - return (Order) ApiClient.Deserialize(response.Content, typeof(Order), response.Headers); + return (Order) ApiClient.Deserialize(response, typeof(Order)); } /// @@ -451,7 +451,7 @@ namespace IO.Swagger.Api if (orderId == null) throw new ApiException(400, "Missing required parameter 'orderId' when calling DeleteOrder"); - var path = "/store/order/{orderId}"; + var path_ = "/store/order/{orderId}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -482,7 +482,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling DeleteOrder: " + response.Content, response.Content); @@ -503,7 +503,7 @@ namespace IO.Swagger.Api if (orderId == null) throw new ApiException(400, "Missing required parameter 'orderId' when calling DeleteOrder"); - var path = "/store/order/{orderId}"; + var path_ = "/store/order/{orderId}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -534,7 +534,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling DeleteOrder: " + response.Content, response.Content); diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs index f7c68cfbe35d..b4c8d93c28c9 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs @@ -240,7 +240,7 @@ namespace IO.Swagger.Api { - var path = "/user"; + var path_ = "/user"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -271,7 +271,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling CreateUser: " + response.Content, response.Content); @@ -290,7 +290,7 @@ namespace IO.Swagger.Api { - var path = "/user"; + var path_ = "/user"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -321,7 +321,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling CreateUser: " + response.Content, response.Content); @@ -338,7 +338,7 @@ namespace IO.Swagger.Api { - var path = "/user/createWithArray"; + var path_ = "/user/createWithArray"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -369,7 +369,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithArrayInput: " + response.Content, response.Content); @@ -388,7 +388,7 @@ namespace IO.Swagger.Api { - var path = "/user/createWithArray"; + var path_ = "/user/createWithArray"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -419,7 +419,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithArrayInput: " + response.Content, response.Content); @@ -436,7 +436,7 @@ namespace IO.Swagger.Api { - var path = "/user/createWithList"; + var path_ = "/user/createWithList"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -467,7 +467,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithListInput: " + response.Content, response.Content); @@ -486,7 +486,7 @@ namespace IO.Swagger.Api { - var path = "/user/createWithList"; + var path_ = "/user/createWithList"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -517,7 +517,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithListInput: " + response.Content, response.Content); @@ -535,7 +535,7 @@ namespace IO.Swagger.Api { - var path = "/user/login"; + var path_ = "/user/login"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -567,14 +567,14 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling LoginUser: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling LoginUser: " + response.ErrorMessage, response.ErrorMessage); - return (string) ApiClient.Deserialize(response.Content, typeof(string), response.Headers); + return (string) ApiClient.Deserialize(response, typeof(string)); } /// @@ -587,7 +587,7 @@ namespace IO.Swagger.Api { - var path = "/user/login"; + var path_ = "/user/login"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -619,11 +619,11 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling LoginUser: " + response.Content, response.Content); - return (string) ApiClient.Deserialize(response.Content, typeof(string), response.Headers); + return (string) ApiClient.Deserialize(response, typeof(string)); } /// @@ -634,7 +634,7 @@ namespace IO.Swagger.Api { - var path = "/user/logout"; + var path_ = "/user/logout"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -664,7 +664,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling LogoutUser: " + response.Content, response.Content); @@ -682,7 +682,7 @@ namespace IO.Swagger.Api { - var path = "/user/logout"; + var path_ = "/user/logout"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -712,7 +712,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling LogoutUser: " + response.Content, response.Content); @@ -732,7 +732,7 @@ namespace IO.Swagger.Api if (username == null) throw new ApiException(400, "Missing required parameter 'username' when calling GetUserByName"); - var path = "/user/{username}"; + var path_ = "/user/{username}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -763,14 +763,14 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetUserByName: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling GetUserByName: " + response.ErrorMessage, response.ErrorMessage); - return (User) ApiClient.Deserialize(response.Content, typeof(User), response.Headers); + return (User) ApiClient.Deserialize(response, typeof(User)); } /// @@ -784,7 +784,7 @@ namespace IO.Swagger.Api if (username == null) throw new ApiException(400, "Missing required parameter 'username' when calling GetUserByName"); - var path = "/user/{username}"; + var path_ = "/user/{username}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -815,11 +815,11 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetUserByName: " + response.Content, response.Content); - return (User) ApiClient.Deserialize(response.Content, typeof(User), response.Headers); + return (User) ApiClient.Deserialize(response, typeof(User)); } /// @@ -835,7 +835,7 @@ namespace IO.Swagger.Api if (username == null) throw new ApiException(400, "Missing required parameter 'username' when calling UpdateUser"); - var path = "/user/{username}"; + var path_ = "/user/{username}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -867,7 +867,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling UpdateUser: " + response.Content, response.Content); @@ -889,7 +889,7 @@ namespace IO.Swagger.Api if (username == null) throw new ApiException(400, "Missing required parameter 'username' when calling UpdateUser"); - var path = "/user/{username}"; + var path_ = "/user/{username}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -921,7 +921,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling UpdateUser: " + response.Content, response.Content); @@ -941,7 +941,7 @@ namespace IO.Swagger.Api if (username == null) throw new ApiException(400, "Missing required parameter 'username' when calling DeleteUser"); - var path = "/user/{username}"; + var path_ = "/user/{username}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -972,7 +972,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling DeleteUser: " + response.Content, response.Content); @@ -993,7 +993,7 @@ namespace IO.Swagger.Api if (username == null) throw new ApiException(400, "Missing required parameter 'username' when calling DeleteUser"); - var path = "/user/{username}"; + var path_ = "/user/{username}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -1024,7 +1024,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling DeleteUser: " + response.Content, response.Content); diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs index 74b898be6260..0416f985360c 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs @@ -214,12 +214,14 @@ namespace IO.Swagger.Client /// /// Deserialize the JSON string into a proper object. /// - /// HTTP body (e.g. string, JSON). + /// The HTTP response. /// Object type. - /// /// Object representation of the JSON string. - public object Deserialize(string content, Type type, IList headers=null) + public object Deserialize(IRestResponse response, Type type) { + byte[] data = response.RawBytes; + string content = response.Content; + IList headers = response.Headers; if (type == typeof(Object)) // return an object { return content; @@ -227,21 +229,22 @@ namespace IO.Swagger.Client if (type == typeof(Stream)) { - var filePath = String.IsNullOrEmpty(Configuration.TempFolderPath) - ? Path.GetTempPath() - : Configuration.TempFolderPath; - - var fileName = filePath + Guid.NewGuid(); if (headers != null) { + var filePath = String.IsNullOrEmpty(Configuration.TempFolderPath) + ? Path.GetTempPath() + : Configuration.TempFolderPath; var regex = new Regex(@"Content-Disposition:.*filename=['""]?([^'""\s]+)['""]?$"); var match = regex.Match(headers.ToString()); if (match.Success) - fileName = filePath + match.Value.Replace("\"", "").Replace("'", ""); + { + string fileName = filePath + match.Value.Replace("\"", "").Replace("'", ""); + File.WriteAllBytes(fileName, data); + return new FileStream(fileName, FileMode.Open); + } } - File.WriteAllText(fileName, content); - return new FileStream(fileName, FileMode.Open); - + var stream = new MemoryStream(data); + return stream; } if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll index 74b5b6455e3f..3541160c3b9a 100755 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll and b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb index 9700c554fbd4..1a9c96751ba6 100644 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb and b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll index 74b5b6455e3f..3541160c3b9a 100755 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll and b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb index 9700c554fbd4..1a9c96751ba6 100644 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb and b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb differ diff --git a/samples/client/petstore/java/bin/io/swagger/client/ApiClient.class b/samples/client/petstore/java/bin/io/swagger/client/ApiClient.class new file mode 100644 index 000000000000..db57f1ecc879 Binary files /dev/null and b/samples/client/petstore/java/bin/io/swagger/client/ApiClient.class differ diff --git a/samples/client/petstore/java/bin/io/swagger/client/ApiClientTest.class b/samples/client/petstore/java/bin/io/swagger/client/ApiClientTest.class new file mode 100644 index 000000000000..99c30aef0123 Binary files /dev/null and b/samples/client/petstore/java/bin/io/swagger/client/ApiClientTest.class differ diff --git a/samples/client/petstore/java/bin/io/swagger/client/ApiException.class b/samples/client/petstore/java/bin/io/swagger/client/ApiException.class new file mode 100644 index 000000000000..5004d8cf0897 Binary files /dev/null and b/samples/client/petstore/java/bin/io/swagger/client/ApiException.class differ diff --git a/samples/client/petstore/java/bin/io/swagger/client/Configuration.class b/samples/client/petstore/java/bin/io/swagger/client/Configuration.class new file mode 100644 index 000000000000..f90a4f410339 Binary files /dev/null and b/samples/client/petstore/java/bin/io/swagger/client/Configuration.class differ diff --git a/samples/client/petstore/java/bin/io/swagger/client/ConfigurationTest.class b/samples/client/petstore/java/bin/io/swagger/client/ConfigurationTest.class new file mode 100644 index 000000000000..f3f80dbccd8d Binary files /dev/null and b/samples/client/petstore/java/bin/io/swagger/client/ConfigurationTest.class differ diff --git a/samples/client/petstore/java/bin/io/swagger/client/JsonUtil.class b/samples/client/petstore/java/bin/io/swagger/client/JsonUtil.class new file mode 100644 index 000000000000..fd6b69381357 Binary files /dev/null and b/samples/client/petstore/java/bin/io/swagger/client/JsonUtil.class differ diff --git a/samples/client/petstore/java/bin/io/swagger/client/StringUtil.class b/samples/client/petstore/java/bin/io/swagger/client/StringUtil.class new file mode 100644 index 000000000000..5283ccc73c59 Binary files /dev/null and b/samples/client/petstore/java/bin/io/swagger/client/StringUtil.class differ diff --git a/samples/client/petstore/java/bin/io/swagger/client/StringUtilTest.class b/samples/client/petstore/java/bin/io/swagger/client/StringUtilTest.class new file mode 100644 index 000000000000..339bbbf3810b Binary files /dev/null and b/samples/client/petstore/java/bin/io/swagger/client/StringUtilTest.class differ diff --git a/samples/client/petstore/java/bin/io/swagger/client/api/PetApi.class b/samples/client/petstore/java/bin/io/swagger/client/api/PetApi.class new file mode 100644 index 000000000000..dd70c18fdbe9 Binary files /dev/null and b/samples/client/petstore/java/bin/io/swagger/client/api/PetApi.class differ diff --git a/samples/client/petstore/java/bin/io/swagger/client/api/StoreApi.class b/samples/client/petstore/java/bin/io/swagger/client/api/StoreApi.class new file mode 100644 index 000000000000..491a30d46caa Binary files /dev/null and b/samples/client/petstore/java/bin/io/swagger/client/api/StoreApi.class differ diff --git a/samples/client/petstore/java/bin/io/swagger/client/api/UserApi.class b/samples/client/petstore/java/bin/io/swagger/client/api/UserApi.class new file mode 100644 index 000000000000..1c71a2e89fa5 Binary files /dev/null and b/samples/client/petstore/java/bin/io/swagger/client/api/UserApi.class differ diff --git a/samples/client/petstore/java/bin/io/swagger/client/auth/ApiKeyAuth.class b/samples/client/petstore/java/bin/io/swagger/client/auth/ApiKeyAuth.class new file mode 100644 index 000000000000..c829299e9f77 Binary files /dev/null and b/samples/client/petstore/java/bin/io/swagger/client/auth/ApiKeyAuth.class differ diff --git a/samples/client/petstore/java/bin/io/swagger/client/auth/ApiKeyAuthTest.class b/samples/client/petstore/java/bin/io/swagger/client/auth/ApiKeyAuthTest.class new file mode 100644 index 000000000000..ff11956d7915 Binary files /dev/null and b/samples/client/petstore/java/bin/io/swagger/client/auth/ApiKeyAuthTest.class differ diff --git a/samples/client/petstore/java/bin/io/swagger/client/auth/Authentication.class b/samples/client/petstore/java/bin/io/swagger/client/auth/Authentication.class new file mode 100644 index 000000000000..b00bf5b2dcbd Binary files /dev/null and b/samples/client/petstore/java/bin/io/swagger/client/auth/Authentication.class differ diff --git a/samples/client/petstore/java/bin/io/swagger/client/auth/HttpBasicAuth.class b/samples/client/petstore/java/bin/io/swagger/client/auth/HttpBasicAuth.class new file mode 100644 index 000000000000..e80e9dbbe8b2 Binary files /dev/null and b/samples/client/petstore/java/bin/io/swagger/client/auth/HttpBasicAuth.class differ diff --git a/samples/client/petstore/java/bin/io/swagger/client/auth/HttpBasicAuthTest.class b/samples/client/petstore/java/bin/io/swagger/client/auth/HttpBasicAuthTest.class new file mode 100644 index 000000000000..b591b7732d82 Binary files /dev/null and b/samples/client/petstore/java/bin/io/swagger/client/auth/HttpBasicAuthTest.class differ diff --git a/samples/client/petstore/java/bin/io/swagger/client/auth/OAuth.class b/samples/client/petstore/java/bin/io/swagger/client/auth/OAuth.class new file mode 100644 index 000000000000..9ad51aeea6a2 Binary files /dev/null and b/samples/client/petstore/java/bin/io/swagger/client/auth/OAuth.class differ diff --git a/samples/client/petstore/java/bin/io/swagger/client/model/Category.class b/samples/client/petstore/java/bin/io/swagger/client/model/Category.class new file mode 100644 index 000000000000..304329daf7c4 Binary files /dev/null and b/samples/client/petstore/java/bin/io/swagger/client/model/Category.class differ diff --git a/samples/client/petstore/java/bin/io/swagger/client/model/Order$StatusEnum.class b/samples/client/petstore/java/bin/io/swagger/client/model/Order$StatusEnum.class new file mode 100644 index 000000000000..d40e6a0d0a07 Binary files /dev/null and b/samples/client/petstore/java/bin/io/swagger/client/model/Order$StatusEnum.class differ diff --git a/samples/client/petstore/java/bin/io/swagger/client/model/Order.class b/samples/client/petstore/java/bin/io/swagger/client/model/Order.class new file mode 100644 index 000000000000..e777d21105e5 Binary files /dev/null and b/samples/client/petstore/java/bin/io/swagger/client/model/Order.class differ diff --git a/samples/client/petstore/java/bin/io/swagger/client/model/Pet$StatusEnum.class b/samples/client/petstore/java/bin/io/swagger/client/model/Pet$StatusEnum.class new file mode 100644 index 000000000000..c13ccdbb1f2e Binary files /dev/null and b/samples/client/petstore/java/bin/io/swagger/client/model/Pet$StatusEnum.class differ diff --git a/samples/client/petstore/java/bin/io/swagger/client/model/Pet.class b/samples/client/petstore/java/bin/io/swagger/client/model/Pet.class new file mode 100644 index 000000000000..b7f0e5088c76 Binary files /dev/null and b/samples/client/petstore/java/bin/io/swagger/client/model/Pet.class differ diff --git a/samples/client/petstore/java/bin/io/swagger/client/model/Tag.class b/samples/client/petstore/java/bin/io/swagger/client/model/Tag.class new file mode 100644 index 000000000000..e1af348c6308 Binary files /dev/null and b/samples/client/petstore/java/bin/io/swagger/client/model/Tag.class differ diff --git a/samples/client/petstore/java/bin/io/swagger/client/model/User.class b/samples/client/petstore/java/bin/io/swagger/client/model/User.class new file mode 100644 index 000000000000..cf0fe3832802 Binary files /dev/null and b/samples/client/petstore/java/bin/io/swagger/client/model/User.class differ diff --git a/samples/client/petstore/java/bin/io/swagger/petstore/test/PetApiTest.class b/samples/client/petstore/java/bin/io/swagger/petstore/test/PetApiTest.class new file mode 100644 index 000000000000..0ef877a081b1 Binary files /dev/null and b/samples/client/petstore/java/bin/io/swagger/petstore/test/PetApiTest.class differ diff --git a/samples/client/petstore/java/bin/io/swagger/petstore/test/StoreApiTest.class b/samples/client/petstore/java/bin/io/swagger/petstore/test/StoreApiTest.class new file mode 100644 index 000000000000..0d4d9014bdcd Binary files /dev/null and b/samples/client/petstore/java/bin/io/swagger/petstore/test/StoreApiTest.class differ diff --git a/samples/client/petstore/java/bin/io/swagger/petstore/test/UserApiTest.class b/samples/client/petstore/java/bin/io/swagger/petstore/test/UserApiTest.class new file mode 100644 index 000000000000..80864303843c Binary files /dev/null and b/samples/client/petstore/java/bin/io/swagger/petstore/test/UserApiTest.class differ diff --git a/samples/client/petstore/java/default/pom.xml b/samples/client/petstore/java/default/pom.xml index 3cef1c564c91..da49f3b2fb09 100644 --- a/samples/client/petstore/java/default/pom.xml +++ b/samples/client/petstore/java/default/pom.xml @@ -161,7 +161,7 @@ - 1.5.0 + 1.5.4 1.18 2.4.2 2.3 diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java index d468a50f9e32..17709ee88dc8 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java @@ -39,7 +39,7 @@ import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") public class ApiClient { private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java index d4b75ae39de4..c09e4939e94e 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java @@ -3,7 +3,7 @@ package io.swagger.client; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") public class ApiException extends Exception { private int code = 0; private Map> responseHeaders = null; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java index 5ad2bfb9049e..692018a52d3e 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") public class Configuration { private static ApiClient defaultApiClient = new ApiClient(); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java index 13acc71c60c7..1986a6badbf5 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java @@ -6,18 +6,19 @@ import com.fasterxml.jackson.datatype.joda.*; import java.io.IOException; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-21T11:55:29.717+08:00") public class JSON { private ObjectMapper mapper; public JSON() { mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); mapper.registerModule(new JodaModule()); - } + } /** * Serialize the given Java object into JSON string. diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java index 11bed7752c4b..bc45efb5ce0a 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") public class Pair { private String name = ""; private String value = ""; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java index d00d8e4e42ab..c2f943c731f5 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java index 818a1b9cca5d..c30d70add6b5 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java @@ -3,7 +3,7 @@ package io.swagger.client; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") public class TypeRef { private final Type type; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java index 8afd143cd91f..23782e03e72d 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java @@ -11,7 +11,7 @@ import java.io.File; import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-16T10:32:51.872+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-21T11:55:29.717+08:00") public class PetApi { private ApiClient apiClient; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java index 916b16e17ff1..f8c0fc58682a 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java @@ -11,7 +11,7 @@ import io.swagger.client.model.Order; import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:27.235+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-21T11:55:29.717+08:00") public class StoreApi { private ApiClient apiClient; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java index 80ee07041f76..f6ab0ae08143 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java @@ -11,7 +11,7 @@ import java.util.*; import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:27.235+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-21T11:55:29.717+08:00") public class UserApi { private ApiClient apiClient; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 3d081ca0d4ff..bc6e2f87defa 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -5,7 +5,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java index 1c914f25e199..45a92c1323cb 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java @@ -5,7 +5,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") public interface Authentication { /** Apply authentication settings to header and query params. */ void applyToParams(List queryParams, Map headerParams); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 68466d091875..bb14cab5a2c8 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -8,7 +8,7 @@ import java.util.List; import java.io.UnsupportedEncodingException; import javax.xml.bind.DatatypeConverter; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") public class HttpBasicAuth implements Authentication { private String username; private String password; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java index 996922d567ef..3e0fade5e80a 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java @@ -5,7 +5,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") public class OAuth implements Authentication { @Override public void applyToParams(List queryParams, Map headerParams) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuthFlow.java new file mode 100644 index 000000000000..597ec99b48b7 --- /dev/null +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -0,0 +1,5 @@ +package io.swagger.client.auth; + +public enum OAuthFlow { + accessCode, implicit, password, application +} \ No newline at end of file diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java index 8e49fe2f1d37..b12b44dd1c86 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java @@ -9,7 +9,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") public class Category { private Long id = null; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java index 84582f973200..7e4e43420c94 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java @@ -10,7 +10,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:27.235+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") public class Order { private Long id = null; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java index 3076f4a5be90..ba497232881e 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java @@ -2,8 +2,8 @@ package io.swagger.client.model; import io.swagger.client.StringUtil; import io.swagger.client.model.Category; -import java.util.*; import io.swagger.client.model.Tag; +import java.util.*; @@ -12,7 +12,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:27.235+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") public class Pet { private Long id = null; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java index 7d112784c9f8..689185907891 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java @@ -9,7 +9,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") public class Tag { private Long id = null; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java index 2331a90f7d43..271bf3b19d77 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java @@ -9,7 +9,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") public class User { private Long id = null; 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 87838cb85699..4734b5d50771 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 @@ -43,7 +43,7 @@ import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-24T21:52:47.417+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") public class ApiClient { private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); 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 aec34b70511a..7c505d33b96b 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 @@ -3,7 +3,7 @@ package io.swagger.client; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") public class ApiException extends Exception { private int code = 0; private Map> responseHeaders = null; 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 778c303e0ecb..f678452b1a07 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") public class Configuration { private static ApiClient defaultApiClient = new ApiClient(); diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java index 4b14a48b8584..8ce930ce5c1e 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java @@ -6,18 +6,19 @@ import com.fasterxml.jackson.datatype.joda.*; import java.io.IOException; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-21T11:55:20.020+08:00") public class JSON { private ObjectMapper mapper; public JSON() { mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); mapper.registerModule(new JodaModule()); - } + } /** * Serialize the given Java object into JSON string. 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 1695577aff01..a8337005dec7 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") public class Pair { private String name = ""; private String value = ""; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java index f706fb4f9fa2..ac7d51e2497c 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java index cbff07c94700..f2f9d8a31cc2 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java @@ -3,7 +3,7 @@ package io.swagger.client; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") public class TypeRef { private final Type type; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java index 4095cb036330..57c087a7b5fc 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 @@ -11,7 +11,7 @@ import java.io.File; import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-16T10:40:45.419+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-21T11:55:20.020+08:00") public class PetApi { private ApiClient apiClient; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java index d011bca14175..b035cde9658a 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java @@ -11,7 +11,7 @@ import io.swagger.client.model.Order; import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:19.416+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-21T11:55:20.020+08:00") public class StoreApi { private ApiClient apiClient; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java index 1c811a06a3b2..51bac269b535 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java @@ -11,7 +11,7 @@ import java.util.*; import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:19.416+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-21T11:55:20.020+08:00") public class UserApi { private ApiClient apiClient; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 6082e3a6e4ca..60f3aa7c5b50 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 @@ -5,7 +5,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java index 6555e457ee56..ff1fc7320152 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 @@ -5,7 +5,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") public interface Authentication { /** Apply authentication settings to header and query params. */ void applyToParams(List queryParams, Map headerParams); diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 909043e180e7..f3b643a7839f 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 @@ -8,7 +8,7 @@ import java.util.List; import java.io.UnsupportedEncodingException; import javax.xml.bind.DatatypeConverter; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") public class HttpBasicAuth implements Authentication { private String username; private String password; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java index d4f548b14125..e3ec46f0b811 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 @@ -5,7 +5,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") public class OAuth implements Authentication { @Override public void applyToParams(List queryParams, Map headerParams) { 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 new file mode 100644 index 000000000000..597ec99b48b7 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -0,0 +1,5 @@ +package io.swagger.client.auth; + +public enum OAuthFlow { + accessCode, implicit, password, application +} \ No newline at end of file diff --git a/samples/client/petstore/java/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 f09bf60128a7..1e5b0410731c 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 @@ -9,7 +9,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") public class Category { private Long id = null; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java index 2f091e480853..3239bdd4faf2 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 @@ -10,7 +10,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:19.416+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") public class Order { private Long id = null; 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 784478c84f94..2840137e85dd 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 @@ -2,8 +2,8 @@ package io.swagger.client.model; import io.swagger.client.StringUtil; import io.swagger.client.model.Category; -import java.util.*; import io.swagger.client.model.Tag; +import java.util.*; @@ -12,7 +12,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:19.416+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") public class Pet { private Long id = null; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java index 2f7b12a9c2db..e71aacd8011d 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 @@ -9,7 +9,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") public class Tag { private Long id = null; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java index be1089d751d9..2f35e770e038 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 @@ -9,7 +9,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") public class User { private Long id = null; diff --git a/samples/client/petstore/java/okhttp-gson/build.gradle b/samples/client/petstore/java/okhttp-gson/build.gradle index eea46b819d02..ada6a992573a 100644 --- a/samples/client/petstore/java/okhttp-gson/build.gradle +++ b/samples/client/petstore/java/okhttp-gson/build.gradle @@ -1,89 +1,11 @@ -group = 'io.swagger' -version = '1.0.0' +apply plugin: 'java' +apply plugin: 'maven' -buildscript { - repositories { - jcenter() - } - dependencies { - classpath 'com.android.tools.build:gradle:1.2.2' - classpath 'com.github.dcendents:android-maven-plugin:1.2' - } -} +sourceCompatibility = JavaVersion.VERSION_1_7 +targetCompatibility = JavaVersion.VERSION_1_7 repositories { - jcenter() -} - - -if(hasProperty('target') && target == 'android') { - - apply plugin: 'com.android.library' - apply plugin: 'com.github.dcendents.android-maven' - - android { - compileSdkVersion 22 - buildToolsVersion '22.0.0' - defaultConfig { - minSdkVersion 14 - targetSdkVersion 22 - } - compileOptions { - sourceCompatibility JavaVersion.VERSION_1_7 - targetCompatibility JavaVersion.VERSION_1_7 - } - - // Rename the aar correctly - libraryVariants.all { variant -> - variant.outputs.each { output -> - def outputFile = output.outputFile - if (outputFile != null && outputFile.name.endsWith('.aar')) { - def fileName = "${project.name}-${variant.baseName}-${version}.aar" - output.outputFile = new File(outputFile.parent, fileName) - } - } - } - } - - afterEvaluate { - android.libraryVariants.all { variant -> - def task = project.tasks.create "jar${variant.name.capitalize()}", Jar - task.description = "Create jar artifact for ${variant.name}" - task.dependsOn variant.javaCompile - task.from variant.javaCompile.destinationDir - task.destinationDir = project.file("${project.buildDir}/outputs/jar") - task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" - artifacts.add('archives', task); - } - } - - task sourcesJar(type: Jar) { - from android.sourceSets.main.java.srcDirs - classifier = 'sources' - } - - artifacts { - archives sourcesJar - } - -} else { - - apply plugin: 'java' - apply plugin: 'maven' - - sourceCompatibility = JavaVersion.VERSION_1_7 - targetCompatibility = JavaVersion.VERSION_1_7 - - install { - repositories.mavenInstaller { - pom.artifactId = 'swagger-petstore-okhttp-gson' - } - } - - task execute(type:JavaExec) { - main = System.getProperty('mainClass') - classpath = sourceSets.main.runtimeClasspath - } + mavenCentral() } dependencies { @@ -93,3 +15,17 @@ dependencies { compile 'com.brsanthu:migbase64:2.2' testCompile 'junit:junit:4.8.1' } + +group = 'io.swagger' +version = '1.0.0' + +install { + repositories.mavenInstaller { + pom.artifactId = 'swagger-petstore-okhttp-gson' + } +} + +task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath +} 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 a76d5872a900..0bdd5bd17c69 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 @@ -3,7 +3,7 @@ package io.swagger.client; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T13:13:26.059+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:42:25.339-07:00") public class ApiException extends Exception { private int code = 0; private Map> responseHeaders = null; 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 7a4d947d5e5c..a63382fc05be 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,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T13:13:26.059+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:42:25.339-07:00") public class Configuration { private static ApiClient defaultApiClient = new ApiClient(); diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java index f88639b9c82d..d9d0881a153e 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 @@ -23,10 +23,9 @@ public class JSON { public JSON(ApiClient apiClient) { this.apiClient = apiClient; gson = new GsonBuilder() - .serializeNulls() .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) .create(); - } + } public Gson getGson() { return gson; 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 5986bdd0db68..533d318cb5c1 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T13:13:26.059+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:42:25.339-07:00") public class Pair { private String name = ""; private String value = ""; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java index 762f1c611610..42d453c31efc 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T13:13:26.059+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:42:25.339-07:00") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 6bfe672ea939..c072321f457f 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 @@ -5,7 +5,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T13:13:26.059+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:42:25.339-07:00") public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java index 3fa136f64c00..18ca4080c2e6 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 @@ -5,7 +5,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T13:13:26.059+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:42:25.339-07:00") public interface Authentication { /** Apply authentication settings to header and query params. */ void applyToParams(List queryParams, Map headerParams); 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 4e3b5a035bdb..dfa751840141 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 @@ -5,7 +5,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T13:13:26.059+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:42:25.339-07:00") public class OAuth implements Authentication { @Override public void applyToParams(List queryParams, Map headerParams) { diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java new file mode 100644 index 000000000000..597ec99b48b7 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -0,0 +1,5 @@ +package io.swagger.client.auth; + +public enum OAuthFlow { + accessCode, implicit, password, application +} \ No newline at end of file diff --git a/samples/client/petstore/java/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 9ab5457e26ac..d1310e10dedb 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 @@ -2,8 +2,8 @@ package io.swagger.client.model; import io.swagger.client.StringUtil; import io.swagger.client.model.Category; -import java.util.*; import io.swagger.client.model.Tag; +import java.util.*; import com.google.gson.annotations.SerializedName; 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 83ad22c4de8e..343e545e83d0 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 @@ -41,7 +41,7 @@ public class ApiClient { apiAuthorizations = new LinkedHashMap(); createDefaultAdapter(); } - + public ApiClient(String[] authNames) { this(); okClient = new OkHttpClient(); @@ -51,11 +51,10 @@ public class ApiClient { throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations"); } Interceptor auth; - if (authName == "api_key") { - auth = new ApiKeyAuth("header", "api_key"); - } else if (authName == "petstore_auth") { auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); + } else if (authName == "api_key") { + auth = new ApiKeyAuth("header", "api_key"); } else { throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java index 5f09a3edfebf..2f6d6fed42c3 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-11T00:10:38.251+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:42:31.307-07:00") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java index 1746009aa777..cd4dbe866a51 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java @@ -1,16 +1,15 @@ package io.swagger.client.api; -import io.swagger.client.CollectionFormats.*; +import io.swagger.client.model.*; import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; +import java.util.*; import io.swagger.client.model.Pet; import java.io.File; -import java.util.*; - public interface PetApi { /** @@ -21,7 +20,7 @@ public interface PetApi { * @return Void */ - @PUT("/pet") + @PUT("/pet") Void updatePet( @Body Pet body ); @@ -30,14 +29,14 @@ public interface PetApi { * Update an existing pet * Async method * @param body Pet object that needs to be added to the store - * @param cb callback method + * @param cb callback method * @return void */ - @PUT("/pet") + @PUT("/pet") void updatePet( @Body Pet body, Callback cb - ); + ); /** * Add a new pet to the store @@ -47,7 +46,7 @@ public interface PetApi { * @return Void */ - @POST("/pet") + @POST("/pet") Void addPet( @Body Pet body ); @@ -56,14 +55,14 @@ public interface PetApi { * Add a new pet to the store * Async method * @param body Pet object that needs to be added to the store - * @param cb callback method + * @param cb callback method * @return void */ - @POST("/pet") + @POST("/pet") void addPet( @Body Pet body, Callback cb - ); + ); /** * Finds Pets by status @@ -73,7 +72,7 @@ public interface PetApi { * @return List */ - @GET("/pet/findByStatus") + @GET("/pet/findByStatus") List findPetsByStatus( @Query("status") List status ); @@ -82,14 +81,14 @@ public interface PetApi { * Finds Pets by status * Async method * @param status Status values that need to be considered for filter - * @param cb callback method + * @param cb callback method * @return void */ - @GET("/pet/findByStatus") + @GET("/pet/findByStatus") void findPetsByStatus( @Query("status") List status, Callback> cb - ); + ); /** * Finds Pets by tags @@ -99,7 +98,7 @@ public interface PetApi { * @return List */ - @GET("/pet/findByTags") + @GET("/pet/findByTags") List findPetsByTags( @Query("tags") List tags ); @@ -108,14 +107,14 @@ public interface PetApi { * Finds Pets by tags * Async method * @param tags Tags to filter by - * @param cb callback method + * @param cb callback method * @return void */ - @GET("/pet/findByTags") + @GET("/pet/findByTags") void findPetsByTags( @Query("tags") List tags, Callback> cb - ); + ); /** * Find pet by ID @@ -125,7 +124,7 @@ public interface PetApi { * @return Pet */ - @GET("/pet/{petId}") + @GET("/pet/{petId}") Pet getPetById( @Path("petId") Long petId ); @@ -134,14 +133,14 @@ public interface PetApi { * Find pet by ID * Async method * @param petId ID of pet that needs to be fetched - * @param cb callback method + * @param cb callback method * @return void */ - @GET("/pet/{petId}") + @GET("/pet/{petId}") void getPetById( @Path("petId") Long petId, Callback cb - ); + ); /** * Updates a pet in the store with form data @@ -154,7 +153,7 @@ public interface PetApi { */ @FormUrlEncoded - @POST("/pet/{petId}") + @POST("/pet/{petId}") Void updatePetWithForm( @Path("petId") String petId, @Field("name") String name, @Field("status") String status ); @@ -165,15 +164,15 @@ public interface PetApi { * @param petId ID of pet that needs to be updated * @param name Updated name of the pet * @param status Updated status of the pet - * @param cb callback method + * @param cb callback method * @return void */ @FormUrlEncoded - @POST("/pet/{petId}") + @POST("/pet/{petId}") void updatePetWithForm( @Path("petId") String petId, @Field("name") String name, @Field("status") String status, Callback cb - ); + ); /** * Deletes a pet @@ -184,7 +183,7 @@ public interface PetApi { * @return Void */ - @DELETE("/pet/{petId}") + @DELETE("/pet/{petId}") Void deletePet( @Path("petId") Long petId, @Header("api_key") String apiKey ); @@ -194,14 +193,14 @@ public interface PetApi { * Async method * @param petId Pet id to delete * @param apiKey - * @param cb callback method + * @param cb callback method * @return void */ - @DELETE("/pet/{petId}") + @DELETE("/pet/{petId}") void deletePet( @Path("petId") Long petId, @Header("api_key") String apiKey, Callback cb - ); + ); /** * uploads an image @@ -214,7 +213,7 @@ public interface PetApi { */ @Multipart - @POST("/pet/{petId}/uploadImage") + @POST("/pet/{petId}/uploadImage") Void uploadFile( @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file ); @@ -225,14 +224,14 @@ public interface PetApi { * @param petId ID of pet to update * @param additionalMetadata Additional data to pass to server * @param file file to upload - * @param cb callback method + * @param cb callback method * @return void */ @Multipart - @POST("/pet/{petId}/uploadImage") + @POST("/pet/{petId}/uploadImage") void uploadFile( @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file, Callback cb - ); + ); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java index 4d6d3aa7c00c..1c0a8291d020 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java @@ -1,16 +1,15 @@ package io.swagger.client.api; -import io.swagger.client.CollectionFormats.*; +import io.swagger.client.model.*; import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; +import java.util.*; import java.util.Map; import io.swagger.client.model.Order; -import java.util.*; - public interface StoreApi { /** @@ -20,21 +19,21 @@ public interface StoreApi { * @return Map */ - @GET("/store/inventory") + @GET("/store/inventory") Map getInventory(); /** * Returns pet inventories by status * Async method - * @param cb callback method + * @param cb callback method * @return void */ - @GET("/store/inventory") + @GET("/store/inventory") void getInventory( Callback> cb - ); + ); /** * Place an order for a pet @@ -44,7 +43,7 @@ public interface StoreApi { * @return Order */ - @POST("/store/order") + @POST("/store/order") Order placeOrder( @Body Order body ); @@ -53,14 +52,14 @@ public interface StoreApi { * Place an order for a pet * Async method * @param body order placed for purchasing the pet - * @param cb callback method + * @param cb callback method * @return void */ - @POST("/store/order") + @POST("/store/order") void placeOrder( @Body Order body, Callback cb - ); + ); /** * Find purchase order by ID @@ -70,7 +69,7 @@ public interface StoreApi { * @return Order */ - @GET("/store/order/{orderId}") + @GET("/store/order/{orderId}") Order getOrderById( @Path("orderId") String orderId ); @@ -79,14 +78,14 @@ public interface StoreApi { * Find purchase order by ID * Async method * @param orderId ID of pet that needs to be fetched - * @param cb callback method + * @param cb callback method * @return void */ - @GET("/store/order/{orderId}") + @GET("/store/order/{orderId}") void getOrderById( @Path("orderId") String orderId, Callback cb - ); + ); /** * Delete purchase order by ID @@ -96,7 +95,7 @@ public interface StoreApi { * @return Void */ - @DELETE("/store/order/{orderId}") + @DELETE("/store/order/{orderId}") Void deleteOrder( @Path("orderId") String orderId ); @@ -105,13 +104,13 @@ public interface StoreApi { * Delete purchase order by ID * Async method * @param orderId ID of the order that needs to be deleted - * @param cb callback method + * @param cb callback method * @return void */ - @DELETE("/store/order/{orderId}") + @DELETE("/store/order/{orderId}") void deleteOrder( @Path("orderId") String orderId, Callback cb - ); + ); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java index ff4b45629779..162222bc0f1b 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java @@ -1,14 +1,13 @@ package io.swagger.client.api; -import io.swagger.client.CollectionFormats.*; +import io.swagger.client.model.*; import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; - -import io.swagger.client.model.User; import java.util.*; +import io.swagger.client.model.User; import java.util.*; public interface UserApi { @@ -21,7 +20,7 @@ public interface UserApi { * @return Void */ - @POST("/user") + @POST("/user") Void createUser( @Body User body ); @@ -30,14 +29,14 @@ public interface UserApi { * Create user * Async method * @param body Created user object - * @param cb callback method + * @param cb callback method * @return void */ - @POST("/user") + @POST("/user") void createUser( @Body User body, Callback cb - ); + ); /** * Creates list of users with given input array @@ -47,7 +46,7 @@ public interface UserApi { * @return Void */ - @POST("/user/createWithArray") + @POST("/user/createWithArray") Void createUsersWithArrayInput( @Body List body ); @@ -56,14 +55,14 @@ public interface UserApi { * Creates list of users with given input array * Async method * @param body List of user object - * @param cb callback method + * @param cb callback method * @return void */ - @POST("/user/createWithArray") + @POST("/user/createWithArray") void createUsersWithArrayInput( @Body List body, Callback cb - ); + ); /** * Creates list of users with given input array @@ -73,7 +72,7 @@ public interface UserApi { * @return Void */ - @POST("/user/createWithList") + @POST("/user/createWithList") Void createUsersWithListInput( @Body List body ); @@ -82,14 +81,14 @@ public interface UserApi { * Creates list of users with given input array * Async method * @param body List of user object - * @param cb callback method + * @param cb callback method * @return void */ - @POST("/user/createWithList") + @POST("/user/createWithList") void createUsersWithListInput( @Body List body, Callback cb - ); + ); /** * Logs user into the system @@ -100,7 +99,7 @@ public interface UserApi { * @return String */ - @GET("/user/login") + @GET("/user/login") String loginUser( @Query("username") String username, @Query("password") String password ); @@ -110,14 +109,14 @@ public interface UserApi { * Async method * @param username The user name for login * @param password The password for login in clear text - * @param cb callback method + * @param cb callback method * @return void */ - @GET("/user/login") + @GET("/user/login") void loginUser( @Query("username") String username, @Query("password") String password, Callback cb - ); + ); /** * Logs out current logged in user session @@ -126,21 +125,21 @@ public interface UserApi { * @return Void */ - @GET("/user/logout") + @GET("/user/logout") Void logoutUser(); /** * Logs out current logged in user session * Async method - * @param cb callback method + * @param cb callback method * @return void */ - @GET("/user/logout") + @GET("/user/logout") void logoutUser( Callback cb - ); + ); /** * Get user by user name @@ -150,7 +149,7 @@ public interface UserApi { * @return User */ - @GET("/user/{username}") + @GET("/user/{username}") User getUserByName( @Path("username") String username ); @@ -159,14 +158,14 @@ public interface UserApi { * Get user by user name * Async method * @param username The name that needs to be fetched. Use user1 for testing. - * @param cb callback method + * @param cb callback method * @return void */ - @GET("/user/{username}") + @GET("/user/{username}") void getUserByName( @Path("username") String username, Callback cb - ); + ); /** * Updated user @@ -177,7 +176,7 @@ public interface UserApi { * @return Void */ - @PUT("/user/{username}") + @PUT("/user/{username}") Void updateUser( @Path("username") String username, @Body User body ); @@ -187,14 +186,14 @@ public interface UserApi { * Async method * @param username name that need to be deleted * @param body Updated user object - * @param cb callback method + * @param cb callback method * @return void */ - @PUT("/user/{username}") + @PUT("/user/{username}") void updateUser( @Path("username") String username, @Body User body, Callback cb - ); + ); /** * Delete user @@ -204,7 +203,7 @@ public interface UserApi { * @return Void */ - @DELETE("/user/{username}") + @DELETE("/user/{username}") Void deleteUser( @Path("username") String username ); @@ -213,13 +212,13 @@ public interface UserApi { * Delete user * Async method * @param username The name that needs to be deleted - * @param cb callback method + * @param cb callback method * @return void */ - @DELETE("/user/{username}") + @DELETE("/user/{username}") void deleteUser( @Path("username") String username, Callback cb - ); + ); } 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 9ab5457e26ac..d1310e10dedb 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 @@ -2,8 +2,8 @@ package io.swagger.client.model; import io.swagger.client.StringUtil; import io.swagger.client.model.Category; -import java.util.*; import io.swagger.client.model.Tag; +import java.util.*; import com.google.gson.annotations.SerializedName; diff --git a/samples/client/petstore/objc/SwaggerClient.podspec b/samples/client/petstore/objc/SwaggerClient.podspec index 4445bc52ad23..0afb511073c3 100644 --- a/samples/client/petstore/objc/SwaggerClient.podspec +++ b/samples/client/petstore/objc/SwaggerClient.podspec @@ -21,10 +21,10 @@ Pod::Spec.new do |s| s.framework = 'SystemConfiguration' - s.homepage = "" - s.license = "" - s.source = { :git => ".git", :tag => "#{s.version}" } - s.author = { "" => "" } + s.homepage = "https://github.com/swagger-api/swagger-codegen" + s.license = "MIT" + s.source = { :git => "https://github.com/swagger-api/swagger-codegen.git", :tag => "#{s.version}" } + s.author = { "Swagger" => "apiteam@swagger.io" } s.source_files = 'SwaggerClient/**/*' s.public_header_files = 'SwaggerClient/**/*.h' diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m index fc3c79078625..dcd33575fc6f 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m @@ -311,9 +311,10 @@ static void (^reachabilityChangeBlock)(int); range:NSMakeRange(0, [class length])]; if (match) { + NSArray *dataArray = data; innerType = [class substringWithRange:[match rangeAtIndex:1]]; - resultArray = [NSMutableArray arrayWithCapacity:[data count]]; + resultArray = [NSMutableArray arrayWithCapacity:[dataArray count]]; [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { [resultArray addObject:[self deserialize:obj class:innerType]]; } @@ -332,9 +333,10 @@ static void (^reachabilityChangeBlock)(int); range:NSMakeRange(0, [class length])]; if (match) { + NSArray *dataArray = data; innerType = [class substringWithRange:[match rangeAtIndex:1]]; - resultArray = [NSMutableArray arrayWithCapacity:[data count]]; + resultArray = [NSMutableArray arrayWithCapacity:[dataArray count]]; [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { [resultArray addObject:[self deserialize:obj class:innerType]]; }]; @@ -352,9 +354,10 @@ static void (^reachabilityChangeBlock)(int); range:NSMakeRange(0, [class length])]; if (match) { + NSDictionary *dataDict = data; NSString *valueType = [class substringWithRange:[match rangeAtIndex:2]]; - resultDict = [NSMutableDictionary dictionaryWithCapacity:[data count]]; + resultDict = [NSMutableDictionary dictionaryWithCapacity:[dataDict count]]; [data enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { [resultDict setValue:[self deserialize:obj class:valueType] forKey:key]; }]; @@ -728,7 +731,8 @@ static void (^reachabilityChangeBlock)(int); return [object ISO8601String]; } else if ([object isKindOfClass:[NSArray class]]) { - NSMutableArray *sanitizedObjs = [NSMutableArray arrayWithCapacity:[object count]]; + NSArray *objectArray = object; + NSMutableArray *sanitizedObjs = [NSMutableArray arrayWithCapacity:[objectArray count]]; [object enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { if (obj) { [sanitizedObjs addObject:[self sanitizeForSerialization:obj]]; @@ -737,7 +741,8 @@ static void (^reachabilityChangeBlock)(int); return sanitizedObjs; } else if ([object isKindOfClass:[NSDictionary class]]) { - NSMutableDictionary *sanitizedObjs = [NSMutableDictionary dictionaryWithCapacity:[object count]]; + 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]; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPet.h b/samples/client/petstore/objc/SwaggerClient/SWGPet.h index 84f10969e5be..e340e0e2b86a 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPet.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGPet.h @@ -7,8 +7,8 @@ * Do not edit the class manually. */ -#import "SWGCategory.h" #import "SWGTag.h" +#import "SWGCategory.h" @protocol SWGPet diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m index b890e03570fb..156700c9a769 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m @@ -450,7 +450,7 @@ static SWGPetApi* singletonAPI = nil; NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; // Authentication setting - NSArray *authSettings = @[@"petstore_auth", @"api_key"]; + NSArray *authSettings = @[@"api_key", @"petstore_auth"]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h index ec41ecd99078..21f314684fd7 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h @@ -99,7 +99,7 @@ /// Get user by user name /// /// -/// @param username The name that needs to be fetched. Use user1 for testing. +/// @param username The name that needs to be fetched. Use user1 for testing. /// /// /// @return SWGUser* diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m index 5c3c313b2e23..75cf8d51b0ea 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m @@ -470,7 +470,7 @@ static SWGUserApi* singletonAPI = nil; /// /// Get user by user name /// -/// @param username The name that needs to be fetched. Use user1 for testing. +/// @param username The name that needs to be fetched. Use user1 for testing. /// /// @returns SWGUser* /// diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm index 12088eb56cd5..af1ac1c60174 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm @@ -28,7 +28,7 @@ sub to_hash { sub TO_JSON { my $self = shift; my $_data = {}; - foreach my $_key (keys $self->get_attribute_map) { + foreach my $_key (keys %{$self->get_attribute_map}) { if (defined $self->{$_key}) { $_data->{$self->get_attribute_map->{$_key}} = $self->{$_key}; } @@ -40,7 +40,7 @@ sub TO_JSON { sub from_hash { my ($self, $hash) = @_; # loop through attributes and use swagger_types to deserialize the data - while ( my ($_key, $_type) = each $self->get_swagger_types ) { + while ( my ($_key, $_type) = each %{$self->get_swagger_types} ) { if ($_type =~ /^array\[/i) { # array my $_subclass = substr($_type, 6, -1); my @_array = (); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm index bf085889e79d..19a3d88b2994 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm @@ -387,8 +387,8 @@ sub update_pet_with_form { # # Deletes a pet # -# @param string $api_key (optional) # @param int $pet_id Pet id to delete (required) +# @param string $api_key (optional) # @return void # sub delete_pet { diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm index 4c6e293aaaa6..e1088a0839e0 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm @@ -305,7 +305,7 @@ sub logout_user { # # Get user by user name # -# @param string $username The name that needs to be fetched. Use user1 for testing. (required) +# @param string $username The name that needs to be fetched. Use user1 for testing. (required) # @return User # sub get_user_by_name { 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 e8dea97be931..bcd91f4ffb8e 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -424,9 +424,6 @@ class PetApi $httpBody = $formParams; // for HTTP post (form) } - - //TODO support oauth - $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); if (isset($apiKey)) { $headerParams['api_key'] = $apiKey; @@ -509,10 +506,16 @@ class PetApi } // form params if ($name !== null) { + + $formParams['name'] = $this->apiClient->getSerializer()->toFormValue($name); + }// form params if ($status !== null) { + + $formParams['status'] = $this->apiClient->getSerializer()->toFormValue($status); + } @@ -665,10 +668,22 @@ class PetApi } // form params if ($additional_metadata !== null) { + + $formParams['additionalMetadata'] = $this->apiClient->getSerializer()->toFormValue($additional_metadata); + }// form params if ($file !== null) { - $formParams['file'] = '@' . $this->apiClient->getSerializer()->toFormValue($file); + + // PHP 5.5 introduced a CurlFile object that deprecates the old @filename syntax + // See: https://wiki.php.net/rfc/curl-file-upload + if (function_exists('curl_file_create')) { + $formParams['file'] = curl_file_create($this->apiClient->getSerializer()->toFormValue($file)); + } else { + $formParams['file'] = '@' . $this->apiClient->getSerializer()->toFormValue($file); + } + + } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php index 20150b7160bb..982b8955a15c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php @@ -1,11 +1,11 @@ config = $config; $this->serializer = new ObjectSerializer(); } - + /** * Get the config * @return Configuration @@ -87,7 +87,7 @@ class ApiClient { return $this->config; } - + /** * Get the serializer * @return ObjectSerializer @@ -96,7 +96,7 @@ class ApiClient { return $this->serializer; } - + /** * Get API key (with prefix if set) * @param string $apiKeyIdentifier name of apikey @@ -106,20 +106,20 @@ class ApiClient { $prefix = $this->config->getApiKeyPrefix($apiKeyIdentifier); $apiKey = $this->config->getApiKey($apiKeyIdentifier); - + if (!isset($apiKey)) { return null; } - + if (isset($prefix)) { $keyWithPrefix = $prefix." ".$apiKey; } else { $keyWithPrefix = $apiKey; } - + return $keyWithPrefix; } - + /** * Make the HTTP call (Sync) * @param string $resourcePath path to method endpoint @@ -133,28 +133,28 @@ class ApiClient */ public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType=null) { - + $headers = array(); - + // construct the http header $headerParams = array_merge( - (array)$this->config->getDefaultHeaders(), + (array)$this->config->getDefaultHeaders(), (array)$headerParams ); - + foreach ($headerParams as $key => $val) { $headers[] = "$key: $val"; } - + // form data if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers)) { $postData = http_build_query($postData); } else if ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model $postData = json_encode($this->serializer->sanitizeForSerialization($postData)); } - + $url = $this->config->getHost() . $resourcePath; - + $curl = curl_init(); // set timeout, if needed if ($this->config->getCurlTimeout() != 0) { @@ -162,13 +162,19 @@ class ApiClient } // return the result on success, rather than just TRUE curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - + curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); - + + // disable SSL verification, if needed + if ($this->config->getSSLVerification() == false) { + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); + } + if (! empty($queryParams)) { $url = ($url . '?' . http_build_query($queryParams)); } - + if ($method == self::$POST) { curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); @@ -190,57 +196,62 @@ class ApiClient throw new ApiException('Method ' . $method . ' is not recognized.'); } curl_setopt($curl, CURLOPT_URL, $url); - + // Set user agent curl_setopt($curl, CURLOPT_USERAGENT, $this->config->getUserAgent()); - + // debugging for curl if ($this->config->getDebug()) { error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, $this->config->getDebugFile()); - + curl_setopt($curl, CURLOPT_VERBOSE, 1); curl_setopt($curl, CURLOPT_STDERR, fopen($this->config->getDebugFile(), 'a')); } else { curl_setopt($curl, CURLOPT_VERBOSE, 0); } - + // obtain the HTTP response headers curl_setopt($curl, CURLOPT_HEADER, 1); - + // Make the request $response = curl_exec($curl); $http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); $http_header = substr($response, 0, $http_header_size); $http_body = substr($response, $http_header_size); $response_info = curl_getinfo($curl); - + // debug HTTP response body if ($this->config->getDebug()) { error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, $this->config->getDebugFile()); } - + // Handle the response if ($response_info['http_code'] == 0) { throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); } else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { - // return raw body if response is a file + // return raw body if response is a file if ($responseType == '\SplFileObject') { return array($http_body, $http_header); } - + $data = json_decode($http_body); if (json_last_error() > 0) { // if response is a string $data = $http_body; } } else { + $data = json_decode($http_body); + if (json_last_error() > 0) { // if response is a string + $data = $http_body; + } + throw new ApiException( "[".$response_info['http_code']."] Error connecting to the API ($url)", - $response_info['http_code'], $http_header, $http_body + $response_info['http_code'], $http_header, $data ); } return array($data, $http_header); } - + /** * Return the header 'Accept' based on an array of Accept provided * @@ -258,7 +269,7 @@ class ApiClient return implode(',', $accept); } } - + /** * Return the content type based on an array of content-type provided * diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php index ce6c19e245f1..0b8f5892a350 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php @@ -46,30 +46,30 @@ use \Exception; class ApiException extends Exception { - /** - * The HTTP body of the server response. - * @var string + /** + * The HTTP body of the server response either as Json or string. + * @var mixed */ protected $responseBody; - + /** * The HTTP header of the server response. * @var string[] */ protected $responseHeaders; - + /** * The deserialized response object * @var $responseObject; */ protected $responseObject; - + /** * Constructor * @param string $message Error message - * @param string $code HTTP status code + * @param int $code HTTP status code * @param string $responseHeaders HTTP response header - * @param string $responseBody Deseralized response object + * @param mixed $responseBody HTTP body of the server response either as Json or string */ public function __construct($message="", $code=0, $responseHeaders=null, $responseBody=null) { @@ -77,7 +77,7 @@ class ApiException extends Exception $this->responseHeaders = $responseHeaders; $this->responseBody = $responseBody; } - + /** * Gets the HTTP response header * @@ -87,17 +87,17 @@ class ApiException extends Exception { return $this->responseHeaders; } - + /** - * Gets the HTTP response body + * Gets the HTTP body of the server response either as Json or string * - * @return string HTTP response body + * @return mixed HTTP body of the server response either as Json or string */ public function getResponseBody() { return $this->responseBody; } - + /** * Sets the deseralized response object (during deserialization) * @param mixed $obj Deserialized response object diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index fcea7100ae4f..ad715e75994e 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -27,8 +27,8 @@ */ /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * 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. */ @@ -48,70 +48,70 @@ class Configuration { private static $_defaultConfiguration = null; - - /** + + /** * Associate array to store API key(s) * * @var string[] */ protected $apiKeys = array(); - + /** * Associate array to store API prefix (e.g. Bearer) * * @var string[] */ protected $apiKeyPrefixes = array(); - - /** + + /** * Username for HTTP basic authentication * * @var string */ protected $username = ''; - + /** * Password for HTTP basic authentication * * @var string */ protected $password = ''; - + /** * The default instance of ApiClient * * @var \Swagger\Client\ApiClient */ protected $defaultHeaders = array(); - + /** * The host * * @var string */ protected $host = 'http://petstore.swagger.io/v2'; - + /** * Timeout (second) of the HTTP request, by default set to 0, no timeout * - * @var string + * @var string */ protected $curlTimeout = 0; - + /** * User agent of the HTTP request, set to "PHP-Swagger" by default * * @var string */ protected $userAgent = "PHP-Swagger/1.0.0"; - + /** * Debug switch (default set to false) * * @var bool */ protected $debug = false; - + /** * Debug file location (log to STDOUT by default) * @@ -126,6 +126,15 @@ class Configuration */ protected $tempFolderPath; + /** + * Indicates if SSL verification should be enabled or disabled. + * + * This is useful if the host uses a self-signed SSL certificate. + * + * @var boolean True if the certificate should be validated, false otherwise. + */ + protected $sslVerification = true; + /** * Constructor */ @@ -133,7 +142,7 @@ class Configuration { $this->tempFolderPath = sys_get_temp_dir(); } - + /** * Sets API key * @@ -147,7 +156,7 @@ class Configuration $this->apiKeys[$apiKeyIdentifier] = $key; return $this; } - + /** * Gets API key * @@ -159,7 +168,7 @@ class Configuration { return isset($this->apiKeys[$apiKeyIdentifier]) ? $this->apiKeys[$apiKeyIdentifier] : null; } - + /** * Sets the prefix for API key (e.g. Bearer) * @@ -173,7 +182,7 @@ class Configuration $this->apiKeyPrefixes[$apiKeyIdentifier] = $prefix; return $this; } - + /** * Gets API key prefix * @@ -185,7 +194,7 @@ class Configuration { return isset($this->apiKeyPrefixes[$apiKeyIdentifier]) ? $this->apiKeyPrefixes[$apiKeyIdentifier] : null; } - + /** * Sets the username for HTTP basic authentication * @@ -198,7 +207,7 @@ class Configuration $this->username = $username; return $this; } - + /** * Gets the username for HTTP basic authentication * @@ -208,7 +217,7 @@ class Configuration { return $this->username; } - + /** * Sets the password for HTTP basic authentication * @@ -221,7 +230,7 @@ class Configuration $this->password = $password; return $this; } - + /** * Gets the password for HTTP basic authentication * @@ -231,7 +240,7 @@ class Configuration { return $this->password; } - + /** * Adds a default header * @@ -245,11 +254,11 @@ class Configuration if (!is_string($headerName)) { throw new \InvalidArgumentException('Header name must be a string.'); } - + $this->defaultHeaders[$headerName] = $headerValue; return $this; } - + /** * Gets the default header * @@ -259,7 +268,7 @@ class Configuration { return $this->defaultHeaders; } - + /** * Deletes a default header * @@ -271,7 +280,7 @@ class Configuration { unset($this->defaultHeaders[$headerName]); } - + /** * Sets the host * @@ -284,7 +293,7 @@ class Configuration $this->host = $host; return $this; } - + /** * Gets the host * @@ -294,7 +303,7 @@ class Configuration { return $this->host; } - + /** * Sets the user agent of the api client * @@ -307,11 +316,11 @@ class Configuration if (!is_string($userAgent)) { throw new \InvalidArgumentException('User-agent must be a string.'); } - + $this->userAgent = $userAgent; return $this; } - + /** * Gets the user agent of the api client * @@ -321,7 +330,7 @@ class Configuration { return $this->userAgent; } - + /** * Sets the HTTP timeout value * @@ -334,11 +343,11 @@ class Configuration if (!is_numeric($seconds) || $seconds < 0) { throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); } - + $this->curlTimeout = $seconds; return $this; } - + /** * Gets the HTTP timeout value * @@ -348,10 +357,10 @@ class Configuration { return $this->curlTimeout; } - + /** * Sets debug flag - * + * * @param bool $debug Debug flag * * @return Configuration @@ -361,7 +370,7 @@ class Configuration $this->debug = $debug; return $this; } - + /** * Gets the debug flag * @@ -371,7 +380,7 @@ class Configuration { return $this->debug; } - + /** * Sets the debug file * @@ -384,7 +393,7 @@ class Configuration $this->debugFile = $debugFile; return $this; } - + /** * Gets the debug file * @@ -394,7 +403,7 @@ class Configuration { return $this->debugFile; } - + /** * Sets the temp folder path * @@ -407,7 +416,7 @@ class Configuration $this->tempFolderPath = $tempFolderPath; return $this; } - + /** * Gets the temp folder path * @@ -417,7 +426,30 @@ class Configuration { return $this->tempFolderPath; } - + + /** + * Sets if SSL verification should be enabled or disabled + * + * @param boolean $sslVerification True if the certificate should be validated, false otherwise + * + * @return Configuration + */ + public function setSSLVerification($sslVerification) + { + $this->sslVerification = $sslVerification; + return $this; + } + + /** + * Gets if SSL verification should be enabled or disabled + * + * @return boolean True if the certificate should be validated, false otherwise + */ + public function getSSLVerification() + { + return $this->sslVerification; + } + /** * Gets the default configuration instance * @@ -428,10 +460,10 @@ class Configuration if (self::$_defaultConfiguration == null) { self::$_defaultConfiguration = new Configuration(); } - + return self::$_defaultConfiguration; } - + /** * Sets the detault configuration instance * @@ -443,7 +475,7 @@ class Configuration { self::$_defaultConfiguration = $config; } - + /** * Gets the essential information for debugging * @@ -457,8 +489,8 @@ class Configuration $report .= " Swagger Spec Version: 1.0.0\n"; $report .= " SDK Package Version: 1.0.0\n"; $report .= " Temp Folder Path: ".self::getDefaultConfiguration()->getTempFolderPath()."\n"; - + return $report; } - + } diff --git a/samples/client/petstore/python/swagger_client/__init__.py b/samples/client/petstore/python/swagger_client/__init__.py index 6e7b59f36fde..f61c5d55262a 100644 --- a/samples/client/petstore/python/swagger_client/__init__.py +++ b/samples/client/petstore/python/swagger_client/__init__.py @@ -9,8 +9,8 @@ from .models.order import Order # import apis into sdk package from .apis.user_api import UserApi -from .apis.store_api import StoreApi from .apis.pet_api import PetApi +from .apis.store_api import StoreApi # import ApiClient from .api_client import ApiClient diff --git a/samples/client/petstore/python/swagger_client/apis/__init__.py b/samples/client/petstore/python/swagger_client/apis/__init__.py index c0e09458f950..592a56e282d2 100644 --- a/samples/client/petstore/python/swagger_client/apis/__init__.py +++ b/samples/client/petstore/python/swagger_client/apis/__init__.py @@ -2,5 +2,5 @@ from __future__ import absolute_import # import apis into api package from .user_api import UserApi -from .store_api import StoreApi from .pet_api import PetApi +from .store_api import StoreApi diff --git a/samples/client/petstore/python/swagger_client/apis/pet_api.py b/samples/client/petstore/python/swagger_client/apis/pet_api.py index b162cc534c38..ad053a7d72d9 100644 --- a/samples/client/petstore/python/swagger_client/apis/pet_api.py +++ b/samples/client/petstore/python/swagger_client/apis/pet_api.py @@ -409,7 +409,7 @@ class PetApi(object): select_header_content_type([]) # Authentication setting - auth_settings = ['petstore_auth', 'api_key'] + auth_settings = ['api_key', 'petstore_auth'] response = self.api_client.call_api(resource_path, method, path_params, diff --git a/samples/client/petstore/qt5cpp/client/SWGPet.h b/samples/client/petstore/qt5cpp/client/SWGPet.h index 3f9320f15074..e9cb4d082331 100644 --- a/samples/client/petstore/qt5cpp/client/SWGPet.h +++ b/samples/client/petstore/qt5cpp/client/SWGPet.h @@ -10,10 +10,10 @@ #include -#include -#include "SWGCategory.h" -#include #include "SWGTag.h" +#include +#include "SWGCategory.h" +#include #include "SWGObject.h" diff --git a/samples/client/petstore/qt5cpp/client/SWGPetApi.cpp b/samples/client/petstore/qt5cpp/client/SWGPetApi.cpp index 0be3a197cd1f..2171b8ed50ce 100644 --- a/samples/client/petstore/qt5cpp/client/SWGPetApi.cpp +++ b/samples/client/petstore/qt5cpp/client/SWGPetApi.cpp @@ -431,7 +431,7 @@ SWGPetApi::updatePetWithFormCallback(HttpRequestWorker * worker) { emit updatePetWithFormSignal(); } void -SWGPetApi::deletePet(QString* apiKey, qint64 petId) { +SWGPetApi::deletePet(qint64 petId, QString* apiKey) { QString fullPath; fullPath.append(this->host).append(this->basePath).append("/pet/{petId}"); diff --git a/samples/client/petstore/qt5cpp/client/SWGPetApi.h b/samples/client/petstore/qt5cpp/client/SWGPetApi.h index 488865729b94..f74f8f10839f 100644 --- a/samples/client/petstore/qt5cpp/client/SWGPetApi.h +++ b/samples/client/petstore/qt5cpp/client/SWGPetApi.h @@ -28,7 +28,7 @@ public: void findPetsByTags(QList* tags); void getPetById(qint64 petId); void updatePetWithForm(QString* petId, QString* name, QString* status); - void deletePet(QString* apiKey, qint64 petId); + void deletePet(qint64 petId, QString* apiKey); void uploadFile(qint64 petId, QString* additionalMetadata, SWGHttpRequestInputFileElement* file); private: diff --git a/samples/client/petstore/ruby/lib/petstore.rb b/samples/client/petstore/ruby/lib/petstore.rb index c13e99f29fc4..61640d687ac7 100644 --- a/samples/client/petstore/ruby/lib/petstore.rb +++ b/samples/client/petstore/ruby/lib/petstore.rb @@ -14,8 +14,8 @@ require 'petstore/models/order' # APIs require 'petstore/api/user_api' -require 'petstore/api/store_api' require 'petstore/api/pet_api' +require 'petstore/api/store_api' module Petstore class << self diff --git a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb index 26f7482b3848..4b956aeadcc6 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb @@ -237,7 +237,7 @@ module Petstore post_body = nil - auth_names = ['api_key'] + auth_names = ['api_key', 'petstore_auth'] result = @api_client.call_api(:GET, path, :header_params => header_params, :query_params => query_params, diff --git a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb index f4672e2a3585..7f546330f3aa 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb @@ -248,7 +248,7 @@ module Petstore # Get user by user name # - # @param username The name that needs to be fetched. Use user1 for testing. + # @param username The name that needs to be fetched. Use user1 for testing. # @param [Hash] opts the optional parameters # @return [User] def get_user_by_name(username, opts = {}) diff --git a/samples/client/petstore/ruby/lib/petstore/models/base_object.rb b/samples/client/petstore/ruby/lib/petstore/models/base_object.rb index f17eef349e2c..4a9a781ae649 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/base_object.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/base_object.rb @@ -60,14 +60,13 @@ module Petstore # return the object in the form of hash def to_hash hash = {} - self.class.attribute_map.each_pair do |key, value| - if self.send(key).is_a?(Array) - next if self.send(key).empty? - hash[value] = self.send(key).select{|v| !v.nil?}.map{ |v| _to_hash v} unless self.send(key).nil? + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + next if value.nil? + if value.is_a?(Array) + hash[param] = value.compact.map{ |v| _to_hash(v) } else - unless (_tmp_value = _to_hash self.send(key)).nil? - hash[value] = _tmp_value - end + hash[param] = _to_hash(value) end end hash diff --git a/samples/client/petstore/ruby/spec/api_client_spec.rb b/samples/client/petstore/ruby/spec/api_client_spec.rb index b63ec94ccaac..cd9016c9a0ba 100644 --- a/samples/client/petstore/ruby/spec/api_client_spec.rb +++ b/samples/client/petstore/ruby/spec/api_client_spec.rb @@ -102,4 +102,18 @@ describe Petstore::ApiClient do end end + describe "#object_to_hash" do + it "ignores nils and includes empty arrays" do + api_client = Petstore::ApiClient.new + pet = Petstore::Pet.new + pet.id = 1 + pet.name = '' + pet.status = nil + pet.photo_urls = nil + pet.tags = [] + expected = {id: 1, name: '', tags: []} + api_client.object_to_hash(pet).should == expected + end + end + end diff --git a/samples/client/petstore/scala/pom.xml b/samples/client/petstore/scala/pom.xml index 9f39f4e45ce8..ff38920fcdd8 100644 --- a/samples/client/petstore/scala/pom.xml +++ b/samples/client/petstore/scala/pom.xml @@ -210,7 +210,7 @@ 1.2 2.2 1.19 - 1.5.0 + 1.5.4 1.0.5 1.0.0 2.4.2 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 0d0b3c83ed24..a11cab9211b6 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 @@ -325,11 +325,11 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", /** * Deletes a pet * - * @param apiKey * @param petId Pet id to delete + * @param apiKey * @return void */ - def deletePet (apiKey: String, petId: Long) = { + def deletePet (petId: Long, apiKey: String) = { // create path and map variables val path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId)) 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 5a7b38f620aa..802cf01c25bc 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 @@ -263,7 +263,7 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", /** * Get user by user name * - * @param username The name that needs to be fetched. Use user1 for testing. + * @param username The name that needs to be fetched. Use user1 for testing. * @return User */ def getUserByName (username: String) : Option[User] = { diff --git a/samples/client/petstore/swift/Cartfile b/samples/client/petstore/swift/Cartfile index af74617bcf20..fbd9346e4680 100644 --- a/samples/client/petstore/swift/Cartfile +++ b/samples/client/petstore/swift/Cartfile @@ -1,2 +1,2 @@ -github "Alamofire/Alamofire" >= 1.2 +github "Alamofire/Alamofire" >= 2.0.0 github "mxcl/PromiseKit" >=1.5.3 diff --git a/samples/client/petstore/swift/PetstoreClient.podspec b/samples/client/petstore/swift/PetstoreClient.podspec index 00c0ef33e12b..473b130c40c5 100644 --- a/samples/client/petstore/swift/PetstoreClient.podspec +++ b/samples/client/petstore/swift/PetstoreClient.podspec @@ -7,5 +7,5 @@ Pod::Spec.new do |s| s.license = 'Apache License, Version 2.0' s.source_files = 'PetstoreClient/Classes/Swaggers/**/*.swift' s.dependency 'PromiseKit', '~> 2.1' - s.dependency 'Alamofire', '~> 1.3' + s.dependency 'Alamofire', '~> 2.0.0' end diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs.swift index e473915cf245..73c923e6486a 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs.swift @@ -6,19 +6,19 @@ import Foundation -class OneteamAPI { - static let basePath = "http://ec2-52-68-31-200.ap-northeast-1.compute.amazonaws.com/" +public class PetstoreClientAPI { + static let basePath = "http://petstore.swagger.io/v2" static var credential: NSURLCredential? static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() } -class APIBase { +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 enumerate(encoded as! [AnyObject]) { + for (index, item) in (encoded as! [AnyObject]).enumerate() { dictionary["\(index)"] = item } return dictionary @@ -28,7 +28,7 @@ class APIBase { } } -class RequestBuilder { +public class RequestBuilder { var credential: NSURLCredential? var headers: [String:String] = [:] let parameters: [String:AnyObject]? @@ -36,24 +36,24 @@ class RequestBuilder { let method: String let URLString: String - required init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool) { + required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool) { self.method = method self.URLString = URLString self.parameters = parameters self.isBody = isBody } - func execute(completion: (response: Response?, erorr: NSError?) -> Void) { } + public func execute(completion: (response: Response?, erorr: ErrorType?) -> Void) { } - func addHeader(#name: String, value: String) -> Self { + public func addHeader(name name: String, value: String) -> Self { if !value.isEmpty { headers[name] = value } return self } - func addCredential() -> Self { - self.credential = OneteamAPI.credential + public func addCredential() -> Self { + self.credential = PetstoreClientAPI.credential return self } } diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 5202240bbc97..614e70b717ef 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -10,7 +10,7 @@ import PromiseKit extension PetstoreClientAPI { - class PetAPI: APIBase { + public class PetAPI: APIBase { /** @@ -22,19 +22,19 @@ extension PetstoreClientAPI { - type: oauth2 - name: petstore_auth - :param: body (body) Pet object that needs to be added to the store + - parameter body: (body) Pet object that needs to be added to the store - :returns: Promise> + - returns: RequestBuilder */ - func updatePet(#body: Pet?) -> RequestBuilder { + public class func updatePet(body body: Pet?) -> RequestBuilder { let path = "/pet" - let url = PetstoreClientAPI.basePath + path + let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder(method: "PUT", URLString: url, parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: URLString, parameters: parameters, isBody: true) } /** @@ -47,19 +47,19 @@ extension PetstoreClientAPI { - type: oauth2 - name: petstore_auth - :param: body (body) Pet object that needs to be added to the store + - parameter body: (body) Pet object that needs to be added to the store - :returns: Promise> + - returns: RequestBuilder */ - func addPet(#body: Pet?) -> RequestBuilder { + public class func addPet(body body: Pet?) -> RequestBuilder { let path = "/pet" - let url = PetstoreClientAPI.basePath + path + let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder(method: "POST", URLString: url, parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: true) } /** @@ -87,7 +87,11 @@ extension PetstoreClientAPI { } ], contentType=application/json}, {example= 123456 doggie - string + + string + + + string , contentType=application/xml}] - examples: [{example=[ { @@ -106,17 +110,21 @@ extension PetstoreClientAPI { } ], contentType=application/json}, {example= 123456 doggie - string + + string + + + string , contentType=application/xml}] - :param: status (query) Status values that need to be considered for filter + - parameter status: (query) Status values that need to be considered for filter - :returns: Promise> + - returns: RequestBuilder<[Pet]> */ - func findPetsByStatus(#status: [String]?) -> RequestBuilder<[Pet]> { + public class func findPetsByStatus(status status: [String]?) -> RequestBuilder<[Pet]> { let path = "/pet/findByStatus" - let url = PetstoreClientAPI.basePath + path + let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [ "status": status @@ -125,7 +133,7 @@ extension PetstoreClientAPI { let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder(method: "GET", URLString: url, parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: false) } /** @@ -153,7 +161,11 @@ extension PetstoreClientAPI { } ], contentType=application/json}, {example= 123456 doggie - string + + string + + + string , contentType=application/xml}] - examples: [{example=[ { @@ -172,17 +184,21 @@ extension PetstoreClientAPI { } ], contentType=application/json}, {example= 123456 doggie - string + + string + + + string , contentType=application/xml}] - :param: tags (query) Tags to filter by + - parameter tags: (query) Tags to filter by - :returns: Promise> + - returns: RequestBuilder<[Pet]> */ - func findPetsByTags(#tags: [String]?) -> RequestBuilder<[Pet]> { + public class func findPetsByTags(tags tags: [String]?) -> RequestBuilder<[Pet]> { let path = "/pet/findByTags" - let url = PetstoreClientAPI.basePath + path + let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [ "tags": tags @@ -191,7 +207,7 @@ extension PetstoreClientAPI { let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder(method: "GET", URLString: url, parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: false) } /** @@ -222,7 +238,11 @@ extension PetstoreClientAPI { }, contentType=application/json}, {example= 123456 doggie - string + + string + + + string , contentType=application/xml}] - examples: [{example={ @@ -241,25 +261,29 @@ extension PetstoreClientAPI { }, contentType=application/json}, {example= 123456 doggie - string + + string + + + string , contentType=application/xml}] - :param: petId (path) ID of pet that needs to be fetched + - parameter petId: (path) ID of pet that needs to be fetched - :returns: Promise> + - returns: RequestBuilder */ - func getPetById(#petId: Int) -> RequestBuilder { + public class func getPetById(petId petId: Int) -> RequestBuilder { var path = "/pet/{petId}" path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) - let url = PetstoreClientAPI.basePath + path + let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder(method: "GET", URLString: url, parameters: parameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) } /** @@ -272,23 +296,26 @@ extension PetstoreClientAPI { - type: oauth2 - name: petstore_auth - :param: petId (path) ID of pet that needs to be updated - :param: name (form) Updated name of the pet - :param: status (form) Updated status of the pet + - parameter petId: (path) ID of pet that needs to be updated + - parameter name: (form) Updated name of the pet + - parameter status: (form) Updated status of the pet - :returns: Promise> + - returns: RequestBuilder */ - func updatePetWithForm(#petId: String, name: String?, status: String?) -> RequestBuilder { + public class func updatePetWithForm(petId petId: String, name: String?, status: String?) -> RequestBuilder { var path = "/pet/{petId}" path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) - let url = PetstoreClientAPI.basePath + path + let URLString = PetstoreClientAPI.basePath + path - let nillableParameters: [String:AnyObject?] = [:] + let nillableParameters: [String:AnyObject?] = [ + "name": name, + "status": status + ] let parameters = APIHelper.rejectNil(nillableParameters) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder(method: "POST", URLString: url, parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: false) } /** @@ -301,21 +328,21 @@ extension PetstoreClientAPI { - type: oauth2 - name: petstore_auth - :param: petId (path) Pet id to delete + - parameter petId: (path) Pet id to delete - :returns: Promise> + - returns: RequestBuilder */ - func deletePet(#petId: Int) -> RequestBuilder { + public class func deletePet(petId petId: Int) -> RequestBuilder { var path = "/pet/{petId}" path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) - let url = PetstoreClientAPI.basePath + path + let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder(method: "DELETE", URLString: url, parameters: parameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: parameters, isBody: true) } /** @@ -328,23 +355,26 @@ extension PetstoreClientAPI { - type: oauth2 - name: petstore_auth - :param: petId (path) ID of pet to update - :param: additionalMetadata (form) Additional data to pass to server - :param: file (form) file to upload + - parameter petId: (path) ID of pet to update + - parameter additionalMetadata: (form) Additional data to pass to server + - parameter file: (form) file to upload - :returns: Promise> + - returns: RequestBuilder */ - func uploadFile(#petId: Int, additionalMetadata: String?, file: NSData?) -> RequestBuilder { + public class func uploadFile(petId petId: Int, additionalMetadata: String?, file: NSURL?) -> RequestBuilder { var path = "/pet/{petId}/uploadImage" path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) - let url = PetstoreClientAPI.basePath + path + let URLString = PetstoreClientAPI.basePath + path - let nillableParameters: [String:AnyObject?] = [:] + let nillableParameters: [String:AnyObject?] = [ + "additionalMetadata": additionalMetadata, + "file": file + ] let parameters = APIHelper.rejectNil(nillableParameters) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder(method: "POST", URLString: url, parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: false) } } diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index ad122129939a..92cedda725e9 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -10,7 +10,7 @@ import PromiseKit extension PetstoreClientAPI { - class StoreAPI: APIBase { + public class StoreAPI: APIBase { /** @@ -23,23 +23,23 @@ extension PetstoreClientAPI { - name: api_key - examples: [{example={ "key" : 123 -}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@3e, contentType=application/xml}] +}, 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@3e, contentType=application/xml}] +}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] - :returns: Promise> + - returns: RequestBuilder<[String:Int]> */ - func getInventory() -> RequestBuilder<[String:Int]> { + public class func getInventory() -> RequestBuilder<[String:Int]> { let path = "/store/inventory" - let url = PetstoreClientAPI.basePath + path + let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) let requestBuilder: RequestBuilder<[String:Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder(method: "GET", URLString: url, parameters: parameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) } /** @@ -54,12 +54,12 @@ extension PetstoreClientAPI { "complete" : true, "status" : "aeiou", "quantity" : 123, - "shipDate" : "2015-06-27T13:41:28.102+0000" + "shipDate" : "2015-10-20T06:12:32.347+0000" }, contentType=application/json}, {example= 123456 123456 0 - 2015-06-27T22:41:28.105Z + 2015-10-19T23:12:32.350Z string true , contentType=application/xml}] @@ -69,29 +69,29 @@ extension PetstoreClientAPI { "complete" : true, "status" : "aeiou", "quantity" : 123, - "shipDate" : "2015-06-27T13:41:28.102+0000" + "shipDate" : "2015-10-20T06:12:32.347+0000" }, contentType=application/json}, {example= 123456 123456 0 - 2015-06-27T22:41:28.105Z + 2015-10-19T23:12:32.350Z string true , contentType=application/xml}] - :param: body (body) order placed for purchasing the pet + - parameter body: (body) order placed for purchasing the pet - :returns: Promise> + - returns: RequestBuilder */ - func placeOrder(#body: Order?) -> RequestBuilder { + public class func placeOrder(body body: Order?) -> RequestBuilder { let path = "/store/order" - let url = PetstoreClientAPI.basePath + path + let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder(method: "POST", URLString: url, parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: true) } /** @@ -106,12 +106,12 @@ extension PetstoreClientAPI { "complete" : true, "status" : "aeiou", "quantity" : 123, - "shipDate" : "2015-06-27T13:41:28.106+0000" + "shipDate" : "2015-10-20T06:12:32.351+0000" }, contentType=application/json}, {example= 123456 123456 0 - 2015-06-27T22:41:28.106Z + 2015-10-19T23:12:32.351Z string true , contentType=application/xml}] @@ -121,31 +121,31 @@ extension PetstoreClientAPI { "complete" : true, "status" : "aeiou", "quantity" : 123, - "shipDate" : "2015-06-27T13:41:28.106+0000" + "shipDate" : "2015-10-20T06:12:32.351+0000" }, contentType=application/json}, {example= 123456 123456 0 - 2015-06-27T22:41:28.106Z + 2015-10-19T23:12:32.351Z string true , contentType=application/xml}] - :param: orderId (path) ID of pet that needs to be fetched + - parameter orderId: (path) ID of pet that needs to be fetched - :returns: Promise> + - returns: RequestBuilder */ - func getOrderById(#orderId: String) -> RequestBuilder { + public class func getOrderById(orderId orderId: String) -> RequestBuilder { var path = "/store/order/{orderId}" path = path.stringByReplacingOccurrencesOfString("{orderId}", withString: "\(orderId)", options: .LiteralSearch, range: nil) - let url = PetstoreClientAPI.basePath + path + let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder(method: "GET", URLString: url, parameters: parameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) } /** @@ -155,21 +155,21 @@ extension PetstoreClientAPI { - DELETE /store/order/{orderId} - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - :param: orderId (path) ID of the order that needs to be deleted + - parameter orderId: (path) ID of the order that needs to be deleted - :returns: Promise> + - returns: RequestBuilder */ - func deleteOrder(#orderId: String) -> RequestBuilder { + public class func deleteOrder(orderId orderId: String) -> RequestBuilder { var path = "/store/order/{orderId}" path = path.stringByReplacingOccurrencesOfString("{orderId}", withString: "\(orderId)", options: .LiteralSearch, range: nil) - let url = PetstoreClientAPI.basePath + path + let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder(method: "DELETE", URLString: url, parameters: parameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: parameters, isBody: true) } } diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index 9c2833962146..19cf534cea83 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -10,7 +10,7 @@ import PromiseKit extension PetstoreClientAPI { - class UserAPI: APIBase { + public class UserAPI: APIBase { /** @@ -19,19 +19,19 @@ extension PetstoreClientAPI { - POST /user - This can only be done by the logged in user. - :param: body (body) Created user object + - parameter body: (body) Created user object - :returns: Promise> + - returns: RequestBuilder */ - func createUser(#body: User?) -> RequestBuilder { + public class func createUser(body body: User?) -> RequestBuilder { let path = "/user" - let url = PetstoreClientAPI.basePath + path + let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder(method: "POST", URLString: url, parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: true) } /** @@ -41,19 +41,19 @@ extension PetstoreClientAPI { - POST /user/createWithArray - - :param: body (body) List of user object + - parameter body: (body) List of user object - :returns: Promise> + - returns: RequestBuilder */ - func createUsersWithArrayInput(#body: [User]?) -> RequestBuilder { + public class func createUsersWithArrayInput(body body: [User]?) -> RequestBuilder { let path = "/user/createWithArray" - let url = PetstoreClientAPI.basePath + path + let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder(method: "POST", URLString: url, parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: true) } /** @@ -63,19 +63,19 @@ extension PetstoreClientAPI { - POST /user/createWithList - - :param: body (body) List of user object + - parameter body: (body) List of user object - :returns: Promise> + - returns: RequestBuilder */ - func createUsersWithListInput(#body: [User]?) -> RequestBuilder { + public class func createUsersWithListInput(body body: [User]?) -> RequestBuilder { let path = "/user/createWithList" - let url = PetstoreClientAPI.basePath + path + let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder(method: "POST", URLString: url, parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: true) } /** @@ -87,14 +87,14 @@ extension PetstoreClientAPI { - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] - :param: username (query) The user name for login - :param: password (query) The password for login in clear text + - parameter username: (query) The user name for login + - parameter password: (query) The password for login in clear text - :returns: Promise> + - returns: RequestBuilder */ - func loginUser(#username: String?, password: String?) -> RequestBuilder { + public class func loginUser(username username: String?, password: String?) -> RequestBuilder { let path = "/user/login" - let url = PetstoreClientAPI.basePath + path + let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [ "username": username, @@ -104,7 +104,7 @@ extension PetstoreClientAPI { let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder(method: "GET", URLString: url, parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: false) } /** @@ -114,18 +114,18 @@ extension PetstoreClientAPI { - GET /user/logout - - :returns: Promise> + - returns: RequestBuilder */ - func logoutUser() -> RequestBuilder { + public class func logoutUser() -> RequestBuilder { let path = "/user/logout" - let url = PetstoreClientAPI.basePath + path + let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder(method: "GET", URLString: url, parameters: parameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) } /** @@ -145,21 +145,21 @@ extension PetstoreClientAPI { "userStatus" : 0 }, contentType=application/json}] - :param: username (path) The name that needs to be fetched. Use user1 for testing. + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. - :returns: Promise> + - returns: RequestBuilder */ - func getUserByName(#username: String) -> RequestBuilder { + public class func getUserByName(username username: String) -> RequestBuilder { var path = "/user/{username}" path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil) - let url = PetstoreClientAPI.basePath + path + let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder(method: "GET", URLString: url, parameters: parameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) } /** @@ -169,21 +169,21 @@ extension PetstoreClientAPI { - PUT /user/{username} - This can only be done by the logged in user. - :param: username (path) name that need to be deleted - :param: body (body) Updated user object + - parameter username: (path) name that need to be deleted + - parameter body: (body) Updated user object - :returns: Promise> + - returns: RequestBuilder */ - func updateUser(#username: String, body: User?) -> RequestBuilder { + public class func updateUser(username username: String, body: User?) -> RequestBuilder { var path = "/user/{username}" path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil) - let url = PetstoreClientAPI.basePath + path + let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder(method: "PUT", URLString: url, parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: URLString, parameters: parameters, isBody: true) } /** @@ -193,21 +193,21 @@ extension PetstoreClientAPI { - DELETE /user/{username} - This can only be done by the logged in user. - :param: username (path) The name that needs to be deleted + - parameter username: (path) The name that needs to be deleted - :returns: Promise> + - returns: RequestBuilder */ - func deleteUser(#username: String) -> RequestBuilder { + public class func deleteUser(username username: String) -> RequestBuilder { var path = "/user/{username}" path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil) - let url = PetstoreClientAPI.basePath + path + let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder(method: "DELETE", URLString: url, parameters: parameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: parameters, isBody: true) } } diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 61e2bf2886d5..21791168ab2f 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -20,7 +20,7 @@ class AlamofireRequestBuilder: RequestBuilder { super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody) } - override func execute(completion: (response: Response?, erorr: NSError?) -> Void) { + override func execute(completion: (response: Response?, erorr: ErrorType?) -> Void) { let managerId = NSUUID().UUIDString // Create a new manager for each request to customize its request header let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() @@ -29,23 +29,57 @@ class AlamofireRequestBuilder: RequestBuilder { managerStore[managerId] = manager let encoding = isBody ? Alamofire.ParameterEncoding.JSON : Alamofire.ParameterEncoding.URL - let request = manager.request(Alamofire.Method(rawValue: method)!, URLString, parameters: parameters, encoding: encoding) + let xMethod = Alamofire.Method(rawValue: method) + let fileKeys = parameters == nil ? [] : parameters!.filter { $1.isKindOfClass(NSURL) } + .map { $0.0 } + + if fileKeys.count > 0 { + manager.upload( + xMethod!, URLString, headers: nil, + multipartFormData: { mpForm in + for (k, v) in self.parameters! { + switch v { + case let fileURL as NSURL: + mpForm.appendBodyPart(fileURL: fileURL, name: k) + break + case let string as NSString: + mpForm.appendBodyPart(data: string.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) + break + case let number as NSNumber: + mpForm.appendBodyPart(data: number.stringValue.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) + break + default: + fatalError("Unprocessable value \(v) with key \(k)") + break + } + } + }, + encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: { encodingResult in + switch encodingResult { + case .Success(let upload, _, _): + self.processRequest(upload, managerId, completion) + case .Failure(let encodingError): + completion(response: nil, erorr: encodingError) + } + } + ) + } else { + processRequest(manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding), managerId, completion) + } + + } + + private func processRequest(request: Request, _ managerId: String, _ completion: (response: Response?, erorr: ErrorType?) -> Void) { if let credential = self.credential { request.authenticate(usingCredential: credential) } - request.responseJSON(options: .AllowFragments) { (req, res, json, error) in + request.responseJSON(options: .AllowFragments) { (req, res, result) in managerStore.removeValueForKey(managerId) - if let error = error { - completion(response: nil, erorr: error) - return - } - if res!.statusCode >= 400 { - //TODO: Add error entity - let userInfo: [NSObject : AnyObject] = (json != nil) ? ["data": json!] : [:] - let error = NSError(domain: res!.URL!.URLString, code: res!.statusCode, userInfo: userInfo) - completion(response: nil, erorr: error) + if result.isFailure { + completion(response: nil, erorr: result.error) return } @@ -54,7 +88,7 @@ class AlamofireRequestBuilder: RequestBuilder { completion(response: response, erorr: nil) return } - if let json: AnyObject = json { + if let json: AnyObject = result.value { let body = Decoders.decode(clazz: T.self, source: json) let response = Response(response: res!, body: body) completion(response: response, erorr: nil) @@ -66,7 +100,7 @@ class AlamofireRequestBuilder: RequestBuilder { completion(response: response, erorr: nil) return } - + completion(response: nil, erorr: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) } } diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Extensions.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Extensions.swift index 80af4351f048..0a9f74b3e764 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Extensions.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Extensions.swift @@ -65,7 +65,7 @@ extension NSDate: JSONEncodable { } extension RequestBuilder { - func execute() -> Promise> { + public func execute() -> Promise> { let deferred = Promise>.defer() self.execute { (response: Response?, error: NSError?) in if let response = response { diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift index d8ef5b109c22..7ac67ca1b4ad 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift @@ -10,18 +10,18 @@ protocol JSONEncodable { func encodeToJSON() -> AnyObject } -class Response { - let statusCode: Int - let header: [String: String] - let body: T +public class Response { + public let statusCode: Int + public let header: [String: String] + public let body: T - 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 } - 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 { @@ -35,17 +35,17 @@ private var once = dispatch_once_t() class Decoders { static private var decoders = Dictionary AnyObject)>() - static func addDecoder(#clazz: T.Type, decoder: ((AnyObject) -> T)) { + static func addDecoder(clazz clazz: T.Type, decoder: ((AnyObject) -> T)) { let key = "\(T.self)" decoders[key] = { decoder($0) as! AnyObject } } - static func decode(#clazz: [T].Type, source: AnyObject) -> [T] { + 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: [Key:T].Type, source: AnyObject) -> [Key:T] { + static func decode(clazz clazz: [Key:T].Type, source: AnyObject) -> [Key:T] { let sourceDictinoary = source as! [Key: AnyObject] var dictionary = [Key:T]() for (key, value) in sourceDictinoary { @@ -54,7 +54,7 @@ class Decoders { return dictionary } - static func decode(#clazz: T.Type, source: AnyObject) -> T { + static func decode(clazz clazz: T.Type, source: AnyObject) -> T { initialize() if source is T { return source as! T @@ -68,7 +68,7 @@ class Decoders { } } - static func decodeOptional(#clazz: T.Type, source: AnyObject?) -> T? { + static func decodeOptional(clazz clazz: T.Type, source: AnyObject?) -> T? { if source is NSNull { return nil } @@ -77,7 +77,7 @@ class Decoders { } } - static func decodeOptional(#clazz: [T].Type, source: AnyObject?) -> [T]? { + static func decodeOptional(clazz clazz: [T].Type, source: AnyObject?) -> [T]? { if source is NSNull { return nil } @@ -86,7 +86,7 @@ class Decoders { } } - static func decodeOptional(#clazz: [Key:T].Type, source: AnyObject?) -> [Key:T]? { + static func decodeOptional(clazz clazz: [Key:T].Type, source: AnyObject?) -> [Key:T]? { if source is NSNull { return nil } @@ -100,6 +100,7 @@ class Decoders { 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'" ].map { (format: String) -> NSDateFormatter in let formatter = NSDateFormatter() @@ -120,7 +121,7 @@ class Decoders { // Decoder for User Decoders.addDecoder(clazz: User.self) { (source: AnyObject) -> User in let sourceDictionary = source as! [NSObject:AnyObject] - var instance = User() + let instance = User() instance.id = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["id"]) instance.username = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["username"]) instance.firstName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["firstName"]) @@ -136,7 +137,7 @@ class Decoders { // Decoder for Category Decoders.addDecoder(clazz: Category.self) { (source: AnyObject) -> Category in let sourceDictionary = source as! [NSObject:AnyObject] - var instance = Category() + let instance = Category() instance.id = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["id"]) instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"]) return instance @@ -146,7 +147,7 @@ class Decoders { // Decoder for Pet Decoders.addDecoder(clazz: Pet.self) { (source: AnyObject) -> Pet in let sourceDictionary = source as! [NSObject:AnyObject] - var instance = Pet() + let instance = Pet() instance.id = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["id"]) instance.category = Decoders.decodeOptional(clazz: Category.self, source: sourceDictionary["category"]) instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"]) @@ -160,7 +161,7 @@ class Decoders { // Decoder for Tag Decoders.addDecoder(clazz: Tag.self) { (source: AnyObject) -> Tag in let sourceDictionary = source as! [NSObject:AnyObject] - var instance = Tag() + let instance = Tag() instance.id = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["id"]) instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"]) return instance @@ -170,7 +171,7 @@ class Decoders { // Decoder for Order Decoders.addDecoder(clazz: Order.self) { (source: AnyObject) -> Order in let sourceDictionary = source as! [NSObject:AnyObject] - var instance = Order() + let instance = Order() instance.id = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["id"]) instance.petId = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["petId"]) instance.quantity = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["quantity"]) diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Category.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Category.swift index eab3e7b9e012..1356bd1db989 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Category.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Category.swift @@ -8,10 +8,10 @@ import Foundation -class Category: JSONEncodable { +public class Category: JSONEncodable { - var id: Int? - var name: String? + public var id: Int? + public var name: String? // MARK: JSONEncodable diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Order.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Order.swift index 11884502bc1f..25f7745f3068 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Order.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Order.swift @@ -8,21 +8,21 @@ import Foundation -class Order: JSONEncodable { +public class Order: JSONEncodable { - enum Status: String { + public enum Status: String { case Placed = "placed" case Approved = "approved" case Delivered = "delivered" } - var id: Int? - var petId: Int? - var quantity: Int? - var shipDate: NSDate? + public var id: Int? + public var petId: Int? + public var quantity: Int? + public var shipDate: NSDate? /** Order Status */ - var status: Status? - var complete: Bool? + public var status: Status? + public var complete: Bool? // MARK: JSONEncodable diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift index 0baac38a285e..b94e5a7a6de8 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift @@ -8,21 +8,21 @@ import Foundation -class Pet: JSONEncodable { +public class Pet: JSONEncodable { - enum Status: String { + public enum Status: String { case Available = "available" case Pending = "pending" case Sold = "sold" } - var id: Int? - var category: Category? - var name: String? - var photoUrls: [String]? - var tags: [Tag]? + public var id: Int? + public var category: Category? + public var name: String? + public var photoUrls: [String]? + public var tags: [Tag]? /** pet status in the store */ - var status: Status? + public var status: Status? // MARK: JSONEncodable diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Tag.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Tag.swift index 2951506a0dc6..b7ab8a3a0cfe 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Tag.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Tag.swift @@ -8,10 +8,10 @@ import Foundation -class Tag: JSONEncodable { +public class Tag: JSONEncodable { - var id: Int? - var name: String? + public var id: Int? + public var name: String? // MARK: JSONEncodable diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/User.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/User.swift index f2461238dc70..a7592185021d 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/User.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/User.swift @@ -8,17 +8,17 @@ import Foundation -class User: JSONEncodable { +public class User: JSONEncodable { - var id: Int? - var username: String? - var firstName: String? - var lastName: String? - var email: String? - var password: String? - var phone: String? + public var id: Int? + 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 */ - var userStatus: Int? + public var userStatus: Int? // MARK: JSONEncodable diff --git a/samples/client/petstore/tizen/client/SamiOrder.h b/samples/client/petstore/tizen/client/SamiOrder.h index 357812da47c4..08b79cc195c2 100644 --- a/samples/client/petstore/tizen/client/SamiOrder.h +++ b/samples/client/petstore/tizen/client/SamiOrder.h @@ -17,11 +17,11 @@ using namespace Tizen::Web::Json; -using Tizen::Base::Integer; using Tizen::Base::Long; +using Tizen::Base::DateTime; using Tizen::Base::String; using Tizen::Base::Boolean; -using Tizen::Base::DateTime; +using Tizen::Base::Integer; namespace Swagger { diff --git a/samples/client/petstore/tizen/client/SamiPet.h b/samples/client/petstore/tizen/client/SamiPet.h index 5ec3194fb1b3..a16582484364 100644 --- a/samples/client/petstore/tizen/client/SamiPet.h +++ b/samples/client/petstore/tizen/client/SamiPet.h @@ -17,9 +17,9 @@ using namespace Tizen::Web::Json; +#include "SamiCategory.h" using Tizen::Base::Long; using Tizen::Base::String; -#include "SamiCategory.h" #include "SamiTag.h" using Tizen::Base::Collection::IList; diff --git a/samples/client/petstore/tizen/client/SamiPetApi.cpp b/samples/client/petstore/tizen/client/SamiPetApi.cpp index 69997d3cee08..787e79964c28 100644 --- a/samples/client/petstore/tizen/client/SamiPetApi.cpp +++ b/samples/client/petstore/tizen/client/SamiPetApi.cpp @@ -380,7 +380,7 @@ deletePetProcessor(HttpResponse* pHttpResponse, void (* handler)(void*, SamiErro } void -SamiPetApi::deletePetWithCompletion(String* apiKey, Long* petId, void(*success)(SamiError*)) { +SamiPetApi::deletePetWithCompletion(Long* petId, String* apiKey, void(*success)(SamiError*)) { client = new SamiApiClient(); client->success(&deletePetProcessor, (void(*)(void*, SamiError*))success); diff --git a/samples/client/petstore/tizen/client/SamiPetApi.h b/samples/client/petstore/tizen/client/SamiPetApi.h index 05844bd88bd4..a0fc01f08f57 100644 --- a/samples/client/petstore/tizen/client/SamiPetApi.h +++ b/samples/client/petstore/tizen/client/SamiPetApi.h @@ -39,7 +39,7 @@ public: updatePetWithFormWithCompletion(String* petId, String* name, String* status, void(* handler)(SamiError*)); void - deletePetWithCompletion(String* apiKey, Long* petId, void(* handler)(SamiError*)); + deletePetWithCompletion(Long* petId, String* apiKey, void(* handler)(SamiError*)); void uploadFileWithCompletion(Long* petId, String* additionalMetadata, SamiFile* file, void(* handler)(SamiError*)); diff --git a/samples/client/petstore/tizen/client/SamiUser.h b/samples/client/petstore/tizen/client/SamiUser.h index 90b0ede10648..a874f9c62451 100644 --- a/samples/client/petstore/tizen/client/SamiUser.h +++ b/samples/client/petstore/tizen/client/SamiUser.h @@ -17,9 +17,9 @@ using namespace Tizen::Web::Json; -using Tizen::Base::Integer; using Tizen::Base::Long; using Tizen::Base::String; +using Tizen::Base::Integer; namespace Swagger { diff --git a/samples/client/petstore/typescript-angular/API/Client/api.d.ts b/samples/client/petstore/typescript-angular/API/Client/api.d.ts index 46123a07ad33..19c60623dc94 100644 --- a/samples/client/petstore/typescript-angular/API/Client/api.d.ts +++ b/samples/client/petstore/typescript-angular/API/Client/api.d.ts @@ -5,5 +5,5 @@ /// /// -/// /// +/// diff --git a/samples/client/petstore/typescript-node/api.ts b/samples/client/petstore/typescript-node/api.ts index 742169a608e6..148782a4000a 100644 --- a/samples/client/petstore/typescript-node/api.ts +++ b/samples/client/petstore/typescript-node/api.ts @@ -149,6 +149,7 @@ export class UserApi { var headerParams: any = {}; var formParams: any = {}; + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); @@ -194,6 +195,7 @@ export class UserApi { var headerParams: any = {}; var formParams: any = {}; + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); @@ -239,6 +241,7 @@ export class UserApi { var headerParams: any = {}; var formParams: any = {}; + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); @@ -284,6 +287,7 @@ export class UserApi { var headerParams: any = {}; var formParams: any = {}; + if (username !== undefined) { queryParameters['username'] = username; } @@ -336,6 +340,7 @@ export class UserApi { var headerParams: any = {}; var formParams: any = {}; + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); @@ -382,6 +387,7 @@ export class UserApi { var headerParams: any = {}; var formParams: any = {}; + // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling getUserByName'); @@ -433,6 +439,7 @@ export class UserApi { var headerParams: any = {}; var formParams: any = {}; + // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling updateUser'); @@ -485,6 +492,7 @@ export class UserApi { var headerParams: any = {}; var formParams: any = {}; + // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling deleteUser'); @@ -527,224 +535,6 @@ export class UserApi { return deferred.promise; } } -export class StoreApi { - private basePath = 'http://petstore.swagger.io/v2'; - public authentications = { - 'default': new VoidAuth(), - 'api_key': new ApiKeyAuth('header', 'api_key'), - 'petstore_auth': new OAuth(), - } - - constructor(url: string, basePath?: string); - constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { - if (password) { - if (basePath) { - this.basePath = basePath; - } - } else { - if (basePathOrUsername) { - this.basePath = basePathOrUsername - } - } - } - - set apiKey(key: string) { - this.authentications.api_key.apiKey = key; - } - - public getInventory () : Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }> { - var path = this.url + this.basePath + '/store/inventory'; - - var queryParameters: any = {}; - var headerParams: any = {}; - var formParams: any = {}; - - var useFormData = false; - - var deferred = promise.defer<{ response: http.ClientResponse; body: { [key: string]: number; }; }>(); - - var requestOptions: request.Options = { - method: 'GET', - qs: queryParameters, - headers: headerParams, - uri: path, - json: true, - } - - this.authentications.api_key.applyToRequest(requestOptions); - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - public placeOrder (body?: Order) : Promise<{ response: http.ClientResponse; body: Order; }> { - var path = this.url + this.basePath + '/store/order'; - - var queryParameters: any = {}; - var headerParams: any = {}; - var formParams: any = {}; - - var useFormData = false; - - var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); - - var requestOptions: request.Options = { - method: 'POST', - qs: queryParameters, - headers: headerParams, - uri: path, - json: true, - body: body, - } - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - public getOrderById (orderId: string) : Promise<{ response: http.ClientResponse; body: Order; }> { - var path = this.url + this.basePath + '/store/order/{orderId}'; - - path = path.replace('{' + 'orderId' + '}', String(orderId)); - - var queryParameters: any = {}; - var headerParams: any = {}; - var formParams: any = {}; - - // verify required parameter 'orderId' is set - if (!orderId) { - throw new Error('Missing required parameter orderId when calling getOrderById'); - } - - var useFormData = false; - - var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); - - var requestOptions: request.Options = { - method: 'GET', - qs: queryParameters, - headers: headerParams, - uri: path, - json: true, - } - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - public deleteOrder (orderId: string) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/store/order/{orderId}'; - - path = path.replace('{' + 'orderId' + '}', String(orderId)); - - var queryParameters: any = {}; - var headerParams: any = {}; - var formParams: any = {}; - - // verify required parameter 'orderId' is set - if (!orderId) { - throw new Error('Missing required parameter orderId when calling deleteOrder'); - } - - var useFormData = false; - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - var requestOptions: request.Options = { - method: 'DELETE', - qs: queryParameters, - headers: headerParams, - uri: path, - json: true, - } - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } -} export class PetApi { private basePath = 'http://petstore.swagger.io/v2'; public authentications = { @@ -777,6 +567,7 @@ export class PetApi { var headerParams: any = {}; var formParams: any = {}; + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); @@ -824,6 +615,7 @@ export class PetApi { var headerParams: any = {}; var formParams: any = {}; + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); @@ -871,6 +663,7 @@ export class PetApi { var headerParams: any = {}; var formParams: any = {}; + if (status !== undefined) { queryParameters['status'] = status; } @@ -921,6 +714,7 @@ export class PetApi { var headerParams: any = {}; var formParams: any = {}; + if (tags !== undefined) { queryParameters['tags'] = tags; } @@ -973,6 +767,7 @@ export class PetApi { var headerParams: any = {}; var formParams: any = {}; + // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling getPetById'); @@ -990,10 +785,10 @@ export class PetApi { json: true, } - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.api_key.applyToRequest(requestOptions); + this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -1028,6 +823,7 @@ export class PetApi { var headerParams: any = {}; var formParams: any = {}; + // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling updatePetWithForm'); @@ -1089,12 +885,13 @@ export class PetApi { var headerParams: any = {}; var formParams: any = {}; + // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling deletePet'); } - headerParams['apiKey'] = apiKey; + headerParams['api_key'] = apiKey; var useFormData = false; @@ -1144,6 +941,7 @@ export class PetApi { var headerParams: any = {}; var formParams: any = {}; + // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling uploadFile'); @@ -1197,3 +995,225 @@ export class PetApi { return deferred.promise; } } +export class StoreApi { + private basePath = 'http://petstore.swagger.io/v2'; + public authentications = { + 'default': new VoidAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), + } + + constructor(url: string, basePath?: string); + constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + if (basePath) { + this.basePath = basePath; + } + } else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername + } + } + } + + set apiKey(key: string) { + this.authentications.api_key.apiKey = key; + } + + public getInventory () : Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }> { + var path = this.url + this.basePath + '/store/inventory'; + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; body: { [key: string]: number; }; }>(); + + var requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.api_key.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public placeOrder (body?: Order) : Promise<{ response: http.ClientResponse; body: Order; }> { + var path = this.url + this.basePath + '/store/order'; + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); + + var requestOptions: request.Options = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + body: body, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public getOrderById (orderId: string) : Promise<{ response: http.ClientResponse; body: Order; }> { + var path = this.url + this.basePath + '/store/order/{orderId}'; + + path = path.replace('{' + 'orderId' + '}', String(orderId)); + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + + // verify required parameter 'orderId' is set + if (!orderId) { + throw new Error('Missing required parameter orderId when calling getOrderById'); + } + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); + + var requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public deleteOrder (orderId: string) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/store/order/{orderId}'; + + path = path.replace('{' + 'orderId' + '}', String(orderId)); + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + + // verify required parameter 'orderId' is set + if (!orderId) { + throw new Error('Missing required parameter orderId when calling deleteOrder'); + } + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + var requestOptions: request.Options = { + method: 'DELETE', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } +} diff --git a/samples/client/wordnik/android-java/pom.xml b/samples/client/wordnik/android-java/pom.xml index f2a84451d837..4fba0c1bf343 100644 --- a/samples/client/wordnik/android-java/pom.xml +++ b/samples/client/wordnik/android-java/pom.xml @@ -153,7 +153,7 @@ 1.5.3 - 2.1.4 + 2.1.5-SNAPSHOT 4.8.1 1.0.0 4.8.1 diff --git a/samples/client/wordnik/java/pom.xml b/samples/client/wordnik/java/pom.xml index 5fe61d6e0194..f15d9cac6aa0 100644 --- a/samples/client/wordnik/java/pom.xml +++ b/samples/client/wordnik/java/pom.xml @@ -6,11 +6,6 @@ jar swagger-client 1.0.0 - - scm:git:git@github.com:wordnik/swagger-mustache.git - scm:git:git@github.com:wordnik/swagger-codegen.git - https://github.com/wordnik/swagger-codegen - 2.2.0 @@ -159,7 +154,7 @@ 1.5.0-M1 1.7 - 2.1.4 + 2.1.5-SNAPSHOT 2.3 4.8.1 1.0.0 diff --git a/samples/server/petstore/jaxrs/README.md b/samples/server/petstore/jaxrs/README.md index 3ffa01fb2571..00431f63dbc9 100644 --- a/samples/server/petstore/jaxrs/README.md +++ b/samples/server/petstore/jaxrs/README.md @@ -1,10 +1,14 @@ # Swagger generated server ## Overview -This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [swagger-spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This -is an example of building a swagger-enabled scalatra server. +is an example of building a swagger-enabled JAX-RS server. -This example uses the [scalatra](http://scalatra.org/) framework. To see how to make this your own, look here: +This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework. -[README](https://github.com/swagger-api/swagger-codegen/tree/master/samples/server-generator/scalatra) \ No newline at end of file +To run the server, please execute the following: + +``` +mvn clean package jetty:run +``` diff --git a/samples/server/petstore/jaxrs/pom.xml b/samples/server/petstore/jaxrs/pom.xml index ae9f3e06162f..dda5043b7d17 100644 --- a/samples/server/petstore/jaxrs/pom.xml +++ b/samples/server/petstore/jaxrs/pom.xml @@ -168,7 +168,7 @@ - 1.5.3 + 1.5.4 9.2.9.v20150224 1.18.1 1.6.3 diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiException.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiException.java index 300636842ba1..ad8ae3aff94e 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiException.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") public class ApiException extends Exception{ private int code; public ApiException (int code, String msg) { diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiOriginFilter.java index e7ad9b521ac4..3c45b7e282f5 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiOriginFilter.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiOriginFilter.java @@ -5,7 +5,7 @@ import java.io.IOException; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") public class ApiOriginFilter implements javax.servlet.Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiResponseMessage.java index 6d6958c1c907..1bddb4087ae4 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiResponseMessage.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiResponseMessage.java @@ -3,7 +3,7 @@ package io.swagger.api; import javax.xml.bind.annotation.XmlTransient; @javax.xml.bind.annotation.XmlRootElement -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") public class ApiResponseMessage { public static final int ERROR = 1; public static final int WARNING = 2; diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/NotFoundException.java index c3eab326e644..37f7328aaf76 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/NotFoundException.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/NotFoundException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") public class NotFoundException extends ApiException { private int code; public NotFoundException (int code, String msg) { diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java index f583f1e64cfc..260523279cda 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java @@ -22,11 +22,11 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; import javax.ws.rs.*; -@Path("/pet") +@Path("/v2/pet") @io.swagger.annotations.Api(value = "/pet", description = "the pet API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") public class PetApi { private final PetApiService delegate = PetApiServiceFactory.getPetApi(); @@ -35,35 +35,50 @@ public class PetApi { @Consumes({ "application/json", "application/xml" }) @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Update an existing pet", notes = "", response = Void.class) + @io.swagger.annotations.ApiOperation(value = "Update an existing pet", notes = "", response = Void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 405, message = "Validation exception", response = Void.class), + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = Void.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class) }) + @io.swagger.annotations.ApiResponse(code = 405, message = "Validation exception", response = Void.class) }) public Response updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) throws NotFoundException { - return delegate.updatePet(body); + return delegate.updatePet(body); } @POST @Consumes({ "application/json", "application/xml" }) @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class) + @io.swagger.annotations.ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) public Response addPet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) throws NotFoundException { - return delegate.addPet(body); + return delegate.addPet(body); } @GET @Path("/findByStatus") @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma seperated strings", response = Pet.class, responseContainer = "List") + @io.swagger.annotations.ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma seperated strings", response = Pet.class, responseContainer = "List", authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), @@ -71,13 +86,18 @@ public class PetApi { public Response findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", defaultValue="available") @QueryParam("status") List status) throws NotFoundException { - return delegate.findPetsByStatus(status); + return delegate.findPetsByStatus(status); } @GET @Path("/findByTags") @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.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") + @io.swagger.annotations.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 = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), @@ -85,29 +105,36 @@ public class PetApi { public Response findPetsByTags(@ApiParam(value = "Tags to filter by") @QueryParam("tags") List tags) throws NotFoundException { - return delegate.findPetsByTags(tags); + return delegate.findPetsByTags(tags); } @GET @Path("/{petId}") @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Find pet by ID", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = Pet.class) + @io.swagger.annotations.ApiOperation(value = "Find pet by ID", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = Pet.class, authorizations = { + @io.swagger.annotations.Authorization(value = "api_key") + }) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = Pet.class), - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class) }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) public Response getPetById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathParam("petId") Long petId) throws NotFoundException { - return delegate.getPetById(petId); + return delegate.getPetById(petId); } @POST @Path("/{petId}") @Consumes({ "application/x-www-form-urlencoded" }) @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class) + @io.swagger.annotations.ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) @@ -115,26 +142,36 @@ public class PetApi { @ApiParam(value = "Updated name of the pet" )@FormParam("name") String name, @ApiParam(value = "Updated status of the pet" )@FormParam("status") String status) throws NotFoundException { - return delegate.updatePetWithForm(petId,name,status); + return delegate.updatePetWithForm(petId,name,status); } @DELETE @Path("/{petId}") @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Deletes a pet", notes = "", response = Void.class) + @io.swagger.annotations.ApiOperation(value = "Deletes a pet", notes = "", response = Void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) public Response deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathParam("petId") Long petId, @ApiParam(value = "" )@HeaderParam("api_key") String apiKey) throws NotFoundException { - return delegate.deletePet(petId,apiKey); + return delegate.deletePet(petId,apiKey); } @POST @Path("/{petId}/uploadImage") @Consumes({ "multipart/form-data" }) @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = Void.class) + @io.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = Void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @@ -143,7 +180,7 @@ public class PetApi { @FormDataParam("file") InputStream inputStream, @FormDataParam("file") FormDataContentDisposition fileDetail) throws NotFoundException { - return delegate.uploadFile(petId,additionalMetadata,fileDetail); + return delegate.uploadFile(petId,additionalMetadata,fileDetail); } } diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApiService.java index 708dc647f911..8171555b0d08 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApiService.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApiService.java @@ -18,7 +18,7 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") public abstract class PetApiService { public abstract Response updatePet(Pet body) diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java index a487439cb3f9..63fac7c2b34f 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java @@ -22,11 +22,11 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; import javax.ws.rs.*; -@Path("/store") +@Path("/v2/store") @io.swagger.annotations.Api(value = "/store", description = "the store API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") public class StoreApi { private final StoreApiService delegate = StoreApiServiceFactory.getStoreApi(); @@ -35,13 +35,15 @@ public class StoreApi { @Path("/inventory") @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map") + @io.swagger.annotations.ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { + @io.swagger.annotations.Authorization(value = "api_key") + }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Integer.class, responseContainer = "Map") }) public Response getInventory() throws NotFoundException { - return delegate.getInventory(); + return delegate.getInventory(); } @POST @Path("/order") @@ -55,7 +57,7 @@ public class StoreApi { public Response placeOrder(@ApiParam(value = "order placed for purchasing the pet" ) Order body) throws NotFoundException { - return delegate.placeOrder(body); + return delegate.placeOrder(body); } @GET @Path("/order/{orderId}") @@ -63,15 +65,15 @@ public class StoreApi { @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = Order.class), - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class) }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = Order.class) }) public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathParam("orderId") String orderId) throws NotFoundException { - return delegate.getOrderById(orderId); + return delegate.getOrderById(orderId); } @DELETE @Path("/order/{orderId}") @@ -79,13 +81,13 @@ public class StoreApi { @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = Void.class), + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class) }) + @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = Void.class) }) public Response deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathParam("orderId") String orderId) throws NotFoundException { - return delegate.deleteOrder(orderId); + return delegate.deleteOrder(orderId); } } diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApiService.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApiService.java index 955d640d1b5f..dc8274ce7399 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApiService.java @@ -18,7 +18,7 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") public abstract class StoreApiService { public abstract Response getInventory() diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java index d7bde1b17534..cade9a3b2f16 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java @@ -22,11 +22,11 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; import javax.ws.rs.*; -@Path("/user") +@Path("/v2/user") @io.swagger.annotations.Api(value = "/user", description = "the user API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") public class UserApi { private final UserApiService delegate = UserApiServiceFactory.getUserApi(); @@ -41,7 +41,7 @@ public class UserApi { public Response createUser(@ApiParam(value = "Created user object" ) User body) throws NotFoundException { - return delegate.createUser(body); + return delegate.createUser(body); } @POST @Path("/createWithArray") @@ -53,7 +53,7 @@ public class UserApi { public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ) List body) throws NotFoundException { - return delegate.createUsersWithArrayInput(body); + return delegate.createUsersWithArrayInput(body); } @POST @Path("/createWithList") @@ -65,7 +65,7 @@ public class UserApi { public Response createUsersWithListInput(@ApiParam(value = "List of user object" ) List body) throws NotFoundException { - return delegate.createUsersWithListInput(body); + return delegate.createUsersWithListInput(body); } @GET @Path("/login") @@ -80,7 +80,7 @@ public class UserApi { public Response loginUser(@ApiParam(value = "The user name for login") @QueryParam("username") String username, @ApiParam(value = "The password for login in clear text") @QueryParam("password") String password) throws NotFoundException { - return delegate.loginUser(username,password); + return delegate.loginUser(username,password); } @GET @Path("/logout") @@ -92,7 +92,7 @@ public class UserApi { public Response logoutUser() throws NotFoundException { - return delegate.logoutUser(); + return delegate.logoutUser(); } @GET @Path("/{username}") @@ -100,15 +100,15 @@ public class UserApi { @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Get user by user name", notes = "", response = User.class) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = User.class), - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = User.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = User.class) }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = User.class) }) - public Response getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathParam("username") String username) + public Response getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing.",required=true ) @PathParam("username") String username) throws NotFoundException { - return delegate.getUserByName(username); + return delegate.getUserByName(username); } @PUT @Path("/{username}") @@ -116,14 +116,14 @@ public class UserApi { @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = Void.class), + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class) }) + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = Void.class) }) public Response updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathParam("username") String username, @ApiParam(value = "Updated user object" ) User body) throws NotFoundException { - return delegate.updateUser(username,body); + return delegate.updateUser(username,body); } @DELETE @Path("/{username}") @@ -131,13 +131,13 @@ public class UserApi { @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = Void.class), + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class) }) + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = Void.class) }) public Response deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathParam("username") String username) throws NotFoundException { - return delegate.deleteUser(username); + return delegate.deleteUser(username); } } diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApiService.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApiService.java index e838a00e2829..175aa32757af 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApiService.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApiService.java @@ -18,7 +18,7 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") public abstract class UserApiService { public abstract Response createUser(User body) diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java index 57666c8444b8..9aed596a7680 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java @@ -6,7 +6,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") public class Category { private Long id = null; diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java index 99b3c758473e..8a5c22a38ac3 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java @@ -7,7 +7,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") public class Order { private Long id = null; diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java index 0b01a065022e..f3e1cfa17f20 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java @@ -9,7 +9,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") public class Pet { private Long id = null; diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java index 935e04025c87..fe723eea4d85 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java @@ -6,7 +6,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") public class Tag { private Long id = null; diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java index 6d6fb0c1d94e..ea890100a74f 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java @@ -6,7 +6,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") public class User { private Long id = null; diff --git a/samples/server/petstore/nodejs/api/swagger.json b/samples/server/petstore/nodejs/api/swagger.json index 4f091973cf2d..4c0ad6ea42f8 100644 --- a/samples/server/petstore/nodejs/api/swagger.json +++ b/samples/server/petstore/nodejs/api/swagger.json @@ -97,10 +97,6 @@ ], "responses": { - "404": { - "description" : "User not found" -} - , "200": { "description" : "successful operation", "schema" : { @@ -123,6 +119,10 @@ "400": { "description" : "Invalid username supplied" } + , + "404": { + "description" : "User not found" +} } @@ -154,13 +154,13 @@ ], "responses": { - "404": { - "description" : "User not found" -} - , "400": { "description" : "Invalid user supplied" } + , + "404": { + "description" : "User not found" +} } @@ -183,13 +183,13 @@ ], "responses": { - "404": { - "description" : "User not found" -} - , "400": { "description" : "Invalid username supplied" } + , + "404": { + "description" : "User not found" +} } @@ -312,16 +312,16 @@ ], "responses": { - "405": { - "description" : "Validation exception" + "400": { + "description" : "Invalid ID supplied" } , "404": { "description" : "Pet not found" } , - "400": { - "description" : "Invalid ID supplied" + "405": { + "description" : "Validation exception" } @@ -416,9 +416,6 @@ "description" : "Status values that need to be considered for filter", "required" : false, "type" : "array", - "items" : { - "type" : "string" - }, "collectionFormat" : "multi", "default" : "available" } @@ -460,9 +457,6 @@ "description" : "Tags to filter by", "required" : false, "type" : "array", - "items" : { - "type" : "string" - }, "collectionFormat" : "multi" } @@ -508,10 +502,6 @@ ], "responses": { - "404": { - "description" : "Pet not found" -} - , "200": { "description" : "successful operation", "schema" : { @@ -522,6 +512,10 @@ "400": { "description" : "Invalid ID supplied" } + , + "404": { + "description" : "Pet not found" +} } @@ -621,10 +615,6 @@ ], "responses": { - "404": { - "description" : "Order not found" -} - , "200": { "description" : "successful operation", "schema" : { @@ -635,6 +625,10 @@ "400": { "description" : "Invalid ID supplied" } + , + "404": { + "description" : "Order not found" +} } @@ -657,13 +651,13 @@ ], "responses": { - "404": { - "description" : "Order not found" -} - , "400": { "description" : "Invalid ID supplied" } + , + "404": { + "description" : "Order not found" +} } diff --git a/samples/server/petstore/nodejs/controllers/StoreService.js b/samples/server/petstore/nodejs/controllers/StoreService.js index 27c18517ff55..e00a6aee9b9b 100644 --- a/samples/server/petstore/nodejs/controllers/StoreService.js +++ b/samples/server/petstore/nodejs/controllers/StoreService.js @@ -24,7 +24,7 @@ exports.placeOrder = function(body) { "complete" : true, "status" : "aeiou", "quantity" : 123, - "shipDate" : "2015-10-08T15:56:08.367+0000" + "shipDate" : "2015-10-20T06:12:23.907+0000" }; @@ -43,7 +43,7 @@ exports.getOrderById = function(orderId) { "complete" : true, "status" : "aeiou", "quantity" : 123, - "shipDate" : "2015-10-08T15:56:08.371+0000" + "shipDate" : "2015-10-20T06:12:23.911+0000" }; diff --git a/samples/server/petstore/scalatra/README.md b/samples/server/petstore/scalatra/README.md index f8a560b776f5..3ffa01fb2571 100644 --- a/samples/server/petstore/scalatra/README.md +++ b/samples/server/petstore/scalatra/README.md @@ -1,10 +1,10 @@ # Swagger generated server ## Overview -This server was generated by the [swagger-codegen](https://github.com/wordnik/swagger-codegen) project. By using the -[swagger-spec](https://github.com/wordnik/swagger-core/wiki) from a remote server, you can easily generate a server stub. This +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the +[swagger-spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This is an example of building a swagger-enabled scalatra server. This example uses the [scalatra](http://scalatra.org/) framework. To see how to make this your own, look here: -[README](https://github.com/wordnik/swagger-codegen/tree/master/samples/server-generator/scalatra) \ No newline at end of file +[README](https://github.com/swagger-api/swagger-codegen/tree/master/samples/server-generator/scalatra) \ No newline at end of file diff --git a/samples/server/petstore/scalatra/build.sbt b/samples/server/petstore/scalatra/build.sbt index eaa098f07fab..00575312d853 100644 --- a/samples/server/petstore/scalatra/build.sbt +++ b/samples/server/petstore/scalatra/build.sbt @@ -1,6 +1,4 @@ - - -// put this at the top of the file +import AssemblyKeys._ // put this at the top of the file import NativePackagerKeys._ @@ -10,9 +8,9 @@ assemblySettings scalariformSettings -organization := "com.wordnik" +organization := "io.swagger" -seq(webSettings: _*) +seq(webSettings :_*) mainClass in assembly := Some("JettyMain") @@ -25,40 +23,40 @@ scalaVersion := "2.11.2" scalacOptions += "-language:postfixOps" libraryDependencies ++= Seq( - "org.scalatest" %% "scalatest" % "2.2.1" % "test", - "org.scalatra" %% "scalatra" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-scalate" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-json" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-swagger" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-swagger-ext" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-slf4j" % "2.3.0.RC3", - "org.json4s" %% "json4s-jackson" % "3.2.10", - "org.json4s" %% "json4s-ext" % "3.2.10", - "commons-codec" % "commons-codec" % "1.7", - "net.databinder.dispatch" %% "dispatch-core" % "0.11.2", + "org.scalatest" %% "scalatest" % "2.2.1" % "test", + "org.scalatra" %% "scalatra" % "2.3.0.RC3", + "org.scalatra" %% "scalatra-scalate" % "2.3.0.RC3", + "org.scalatra" %% "scalatra-json" % "2.3.0.RC3", + "org.scalatra" %% "scalatra-swagger" % "2.3.0.RC3", + "org.scalatra" %% "scalatra-swagger-ext" % "2.3.0.RC3", + "org.scalatra" %% "scalatra-slf4j" % "2.3.0.RC3", + "org.json4s" %% "json4s-jackson" % "3.2.10", + "org.json4s" %% "json4s-ext" % "3.2.10", + "commons-codec" % "commons-codec" % "1.7", + "net.databinder.dispatch" %% "dispatch-core" % "0.11.2", //"net.databinder.dispatch" %% "json4s-jackson" % "0.11.2", - "net.databinder.dispatch" %% "dispatch-json4s-jackson" % "0.11.2", - "com.typesafe.akka" %% "akka-actor" % "2.3.6", - "org.eclipse.jetty" % "jetty-server" % "9.2.3.v20140905" % "container;compile;test", - "org.eclipse.jetty" % "jetty-webapp" % "9.2.3.v20140905" % "container;compile;test", - "org.eclipse.jetty.orbit" % "javax.servlet" % "3.0.0.v201112011016" % "container;compile;provided;test" artifacts (Artifact("javax.servlet", "jar", "jar")) + "net.databinder.dispatch" %% "dispatch-json4s-jackson" % "0.11.2", + "com.typesafe.akka" %% "akka-actor" % "2.3.6", + "org.eclipse.jetty" % "jetty-server" % "9.2.3.v20140905" % "container;compile;test", + "org.eclipse.jetty" % "jetty-webapp" % "9.2.3.v20140905" % "container;compile;test", + "org.eclipse.jetty.orbit" % "javax.servlet" % "3.0.0.v201112011016" % "container;compile;provided;test" artifacts (Artifact("javax.servlet", "jar", "jar")) ) -resolvers += "Local Maven Repository" at "file://" + Path.userHome.absolutePath + "/.m2/repository" +resolvers += "Local Maven Repository" at "file://"+Path.userHome.absolutePath+"/.m2/repository" resolvers += "Sonatype OSS Snapshots" at "http://oss.sonatype.org/content/repositories/snapshots/" resolvers += "Sonatype OSS Releases" at "http://oss.sonatype.org/content/repositories/releases/" ivyXML := - - - - + + + + mergeStrategy in assembly <<= (mergeStrategy in assembly) { (old) => { - case "about.html" => MergeStrategy.discard + case "about.html" => MergeStrategy.discard case x => old(x) } } diff --git a/samples/server/petstore/scalatra/sbt b/samples/server/petstore/scalatra/sbt old mode 100644 new mode 100755 diff --git a/samples/server/petstore/scalatra/src/main/scala/JettyMain.scala b/samples/server/petstore/scalatra/src/main/scala/JettyMain.scala index 69ca43c0e1f8..e25f16ba3929 100644 --- a/samples/server/petstore/scalatra/src/main/scala/JettyMain.scala +++ b/samples/server/petstore/scalatra/src/main/scala/JettyMain.scala @@ -1,7 +1,17 @@ - +import org.eclipse.jetty.server._ +import org.eclipse.jetty.webapp.WebAppContext +import org.scalatra.servlet.ScalatraListener object JettyMain { + object conf { + val port = sys.env.get("PORT") map (_.toInt) getOrElse (8080) + val stopTimeout = sys.env.get("STOP_TIMEOUT") map (_.toInt) getOrElse (5000) + val connectorIdleTimeout = sys.env.get("CONNECTOR_IDLE_TIMEOUT") map (_.toInt) getOrElse (90000) + val webapp = sys.env.get("PUBLIC") getOrElse "webapp" + val contextPath = sys.env.get("CONTEXT_PATH") getOrElse "/" + } + def main(args: Array[String]) = { val server: Server = new Server println("starting jetty") @@ -30,12 +40,4 @@ object JettyMain { server.start() } - - object conf { - val port = sys.env.get("PORT") map (_.toInt) getOrElse (8080) - val stopTimeout = sys.env.get("STOP_TIMEOUT") map (_.toInt) getOrElse (5000) - val connectorIdleTimeout = sys.env.get("CONNECTOR_IDLE_TIMEOUT") map (_.toInt) getOrElse (90000) - val webapp = sys.env.get("PUBLIC") getOrElse "webapp" - val contextPath = sys.env.get("CONTEXT_PATH") getOrElse "/" - } } diff --git a/samples/server/petstore/scalatra/src/main/scala/ScalatraBootstrap.scala b/samples/server/petstore/scalatra/src/main/scala/ScalatraBootstrap.scala index a8a16d0b1f9c..1129a77d3c8a 100644 --- a/samples/server/petstore/scalatra/src/main/scala/ScalatraBootstrap.scala +++ b/samples/server/petstore/scalatra/src/main/scala/ScalatraBootstrap.scala @@ -1,4 +1,8 @@ - +import com.wordnik.client.api._ +import akka.actor.ActorSystem +import io.swagger.app.{ResourcesApp, SwaggerApp} +import javax.servlet.ServletContext +import org.scalatra.LifeCycle class ScalatraBootstrap extends LifeCycle { implicit val swagger = new SwaggerApp @@ -6,11 +10,11 @@ class ScalatraBootstrap extends LifeCycle { override def init(context: ServletContext) { implicit val system = ActorSystem("appActorSystem") try { - context mount(new UserApi, "/User/*") - context mount(new PetApi, "/Pet/*") - context mount(new StoreApi, "/Store/*") - - context mount(new ResourcesApp, "/api-docs/*") + context mount (new UserApi, "/User/*") + context mount (new PetApi, "/Pet/*") + context mount (new StoreApi, "/Store/*") + + 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 212fbbb94b7c..6631eb98cc1e 100644 --- a/samples/server/petstore/scalatra/src/main/scala/ServletApp.scala +++ b/samples/server/petstore/scalatra/src/main/scala/ServletApp.scala @@ -1,4 +1,11 @@ -package com.wordnik.swagger.app +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.ScalatraServlet +import org.json4s.{DefaultFormats, Formats} class ResourcesApp(implicit protected val system: ActorSystem, val swagger: SwaggerApp) extends ScalatraServlet with JacksonSwaggerBase { @@ -6,17 +13,16 @@ class ResourcesApp(implicit protected val system: ActorSystem, val swagger: Swag 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) + 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) } } @@ -25,7 +31,7 @@ class SwaggerApp extends Swagger(apiInfo = ApiSwagger.apiInfo, apiVersion = "1.0 object ApiSwagger { val apiInfo = ApiInfo( """Swagger Petstore""", - """This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://webchat.freenode.net/?channels=swagger). For this sample, you can use the api key `special-key` to test the authorization filters""", + """This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters""", """""", """apiteam@swagger.io""", """Apache 2.0""", 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 b9c9b5bb2331..7e0a438db1e4 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 @@ -1,7 +1,23 @@ -package com.wordnik.client.apiass PetApi(implicit val swagger: Swagger) extends ScalatraServlet -with FileUploadSupport -with JacksonJsonSupport -with SwaggerSupport { +package com.wordnik.client.api + +import com.wordnik.client.model.Pet +import java.io.File + +import java.io.File + +import org.scalatra.{ TypedParamSupport, ScalatraServlet } +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 scala.collection.JavaConverters._ + +class PetApi (implicit val swagger: Swagger) extends ScalatraServlet + with FileUploadSupport + with JacksonJsonSupport + with SwaggerSupport { protected implicit val jsonFormats: Formats = DefaultFormats protected val applicationDescription: String = "PetApi" @@ -11,268 +27,221 @@ with SwaggerSupport { contentType = formats("json") response.headers += ("Access-Control-Allow-Origin" -> "*") } - + val updatePetOperation = (apiOperation[Unit]("updatePet") - summary "Update an existing pet" - parameters ( - - - bodyParam[Pet]("body").description("").optional - - - ) - ) - - put("/pet", operation(updatePetOperation)) { - - - val body = parsedBody.extract[Pet] - + summary "Update an existing pet" + parameters(bodyParam[Pet]("body").description("").optional) + ) + put("/pet",operation(updatePetOperation)) { + + + + +bodyParam[Pet]("body").description("").optional + println("body: " + body) - + } + val addPetOperation = (apiOperation[Unit]("addPet") - summary "Add a new pet to the store" - parameters ( - - - bodyParam[Pet]("body").description("").optional - - - ) - ) - - post("/pet", operation(addPetOperation)) { - - - val body = parsedBody.extract[Pet] - + summary "Add a new pet to the store" + parameters(bodyParam[Pet]("body").description("").optional) + ) + post("/pet",operation(addPetOperation)) { + + + + +bodyParam[Pet]("body").description("").optional + println("body: " + body) - + } + val findPetsByStatusOperation = (apiOperation[List[Pet]]("findPetsByStatus") - summary "Finds Pets by status" - parameters ( - queryParam[List[String]]("status").description("").optional + summary "Finds Pets by status" + parameters(queryParam[List[String]]("status").description("").optional.defaultValue(available)) + ) - - ) - ) - - 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("multi".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("").optional + summary "Finds Pets by tags" + parameters(queryParam[List[String]]("tags").description("").optional) + ) - - ) - ) - - 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("multi".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("") - - - ) - ) - - get("/pet/{petId}", operation(getPetByIdOperation)) { - - - val petId = params.getOrElse("petId", halt(400)) - - - - - - - - + summary "Find pet by ID" + parameters(pathParam[Long]("petId").description("")) + ) + get("/pet/{petId}",operation(getPetByIdOperation)) { + + + + val petId = params.getOrElse("petId", halt(400)) + + println("petId: " + petId) - + } + val updatePetWithFormOperation = (apiOperation[Unit]("updatePetWithForm") - summary "Updates a pet in the store with form data" - parameters( - - pathParam[String]("petId").description("") - - - , - - - formParam[String]("name").description("").optional - - , - - - formParam[String]("status").description("").optional - - ) - ) - - post("/pet/{petId}", operation(updatePetWithFormOperation)) { - - - val petId = params.getOrElse("petId", halt(400)) - - - - - - - - + summary "Updates a pet in the store with form data" + parameters(pathParam[String]("petId").description(""), + formParam[String]("name").description("").optional, + formParam[String]("status").description("").optional) + ) + 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 deletePetOperation = (apiOperation[Unit]("deletePet") - summary "Deletes a pet" - parameters( - - headerParam[String]("api_key").description("").optional - - - , - - pathParam[Long]("petId").description("") - - ) - ) - - delete("/pet/{petId}", operation(deletePetOperation)) { - - - val api_key = request.getHeader("api_key") - - - - - - - println("api_key: " + api_key) - - - - - val petId = params.getOrElse("petId", halt(400)) - - - - - - - - + summary "Deletes a pet" + parameters(pathParam[Long]("petId").description(""), + ) + ) + delete("/pet/{petId}",operation(deletePetOperation)) { + + + + val petId = params.getOrElse("petId", halt(400)) + + println("petId: " + petId) + + + + + val apiKey = request.getHeader("apiKey") + + + println("apiKey: " + apiKey) + + } + + + + val uploadFileOperation = (apiOperation[Unit]("uploadFile") + 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)) + + + + println("petId: " + petId) + + + + + val additionalMetadata = params.getAs[String]("additionalMetadata") + + + + println("additionalMetadata: " + additionalMetadata) + + val file = fileParams("file") + + println("file: " + file) + } } \ No newline at end of file diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala index 3e31c93743ce..27fbc08e2c24 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 @@ -1,99 +1,96 @@ package com.wordnik.client.api -class StoreApi(implicit val swagger: Swagger) extends ScalatraServlet -with FileUploadSupport -with JacksonJsonSupport -with SwaggerSupport { +import com.wordnik.client.model.Order + +import java.io.File + +import org.scalatra.{ TypedParamSupport, ScalatraServlet } +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 scala.collection.JavaConverters._ + +class StoreApi (implicit val swagger: Swagger) extends ScalatraServlet + with FileUploadSupport + with JacksonJsonSupport + with SwaggerSupport { + protected implicit val jsonFormats: Formats = DefaultFormats + + protected val applicationDescription: String = "StoreApi" override protected val applicationName: Option[String] = Some("Store") - val getInventoryOperation = (apiOperation[Map[String, Int]]("getInventory") - summary "Returns pet inventories by status" - parameters( - ) - ) - val placeOrderOperation = (apiOperation[Order]("placeOrder") - summary "Place an order for a pet" - parameters ( - - - bodyParam[Order]("body").description("").optional - - - ) - ) before() { contentType = formats("json") response.headers += ("Access-Control-Allow-Origin" -> "*") } - val getOrderByIdOperation = (apiOperation[Order]("getOrderById") - summary "Find purchase order by ID" - parameters ( + - pathParam[String]("orderId").description("") - - - ) - ) - - get("/store/inventory", operation(getInventoryOperation)) { + val getInventoryOperation = (apiOperation[Map[String, Int]]("getInventory") + summary "Returns pet inventories by status" + parameters() + ) + get("/store/inventory",operation(getInventoryOperation)) { + } - val deleteOrderOperation = (apiOperation[Unit]("deleteOrder") - summary "Delete purchase order by ID" - parameters ( - pathParam[String]("orderId").description("") - - - ) - ) - - post("/store/order", operation(placeOrderOperation)) { - - - val body = parsedBody.extract[Order] + + val placeOrderOperation = (apiOperation[Order]("placeOrder") + summary "Place an order for a pet" + parameters(bodyParam[Order]("body").description("").optional) + ) + post("/store/order",operation(placeOrderOperation)) { + + + + +bodyParam[Order]("body").description("").optional + println("body: " + body) - + } - protected implicit val jsonFormats: Formats = DefaultFormats - - get("/store/order/{orderId}", operation(getOrderByIdOperation)) { - - - val orderId = params.getOrElse("orderId", halt(400)) - - - - - - + + val getOrderByIdOperation = (apiOperation[Order]("getOrderById") + summary "Find purchase order by ID" + parameters(pathParam[String]("orderId").description("")) + ) + get("/store/order/{orderId}",operation(getOrderByIdOperation)) { + + + + val orderId = params.getOrElse("orderId", halt(400)) + + println("orderId: " + orderId) - + } - protected val applicationDescription: String = "StoreApi" - - delete("/store/order/{orderId}", operation(deleteOrderOperation)) { - - - val orderId = params.getOrElse("orderId", halt(400)) - - - - - - + + val deleteOrderOperation = (apiOperation[Unit]("deleteOrder") + summary "Delete purchase order by ID" + parameters(pathParam[String]("orderId").description("")) + ) + delete("/store/order/{orderId}",operation(deleteOrderOperation)) { + + + + val orderId = params.getOrElse("orderId", halt(400)) + + println("orderId: " + orderId) - + } } \ 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 ab493b4bfac0..c63151a8d388 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 @@ -1,7 +1,22 @@ -package com.wordnik.client.apiass UserApi(implicit val swagger: Swagger) extends ScalatraServlet -with FileUploadSupport -with JacksonJsonSupport -with SwaggerSupport { +package com.wordnik.client.api + +import com.wordnik.client.model.User + +import java.io.File + +import org.scalatra.{ TypedParamSupport, ScalatraServlet } +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 scala.collection.JavaConverters._ + +class UserApi (implicit val swagger: Swagger) extends ScalatraServlet + with FileUploadSupport + with JacksonJsonSupport + with SwaggerSupport { protected implicit val jsonFormats: Formats = DefaultFormats protected val applicationDescription: String = "UserApi" @@ -11,238 +26,166 @@ with SwaggerSupport { contentType = formats("json") response.headers += ("Access-Control-Allow-Origin" -> "*") } - + val createUserOperation = (apiOperation[Unit]("createUser") - summary "Create user" - parameters ( - - - bodyParam[User]("body").description("").optional - - - ) - ) - - post("/user", operation(createUserOperation)) { - - - val body = parsedBody.extract[User] - + summary "Create user" + parameters(bodyParam[User]("body").description("").optional) + ) + post("/user",operation(createUserOperation)) { + + + + +bodyParam[User]("body").description("").optional + println("body: " + body) - + } + val createUsersWithArrayInputOperation = (apiOperation[Unit]("createUsersWithArrayInput") - summary "Creates list of users with given input array" - parameters ( - - - bodyParam[List[User]]("body").description("").optional - - - ) - ) - - post("/user/createWithArray", operation(createUsersWithArrayInputOperation)) { - - - val body = parsedBody.extract[List[User]] - + summary "Creates list of users with given input array" + parameters(bodyParam[List[User]]("body").description("").optional) + ) + post("/user/createWithArray",operation(createUsersWithArrayInputOperation)) { + + + + +bodyParam[List[User]]("body").description("").optional + println("body: " + body) - + } + val createUsersWithListInputOperation = (apiOperation[Unit]("createUsersWithListInput") - summary "Creates list of users with given input array" - parameters ( - - - bodyParam[List[User]]("body").description("").optional - - - ) - ) - - post("/user/createWithList", operation(createUsersWithListInputOperation)) { - - - val body = parsedBody.extract[List[User]] - + summary "Creates list of users with given input array" + parameters(bodyParam[List[User]]("body").description("").optional) + ) + post("/user/createWithList",operation(createUsersWithListInputOperation)) { + + + + +bodyParam[List[User]]("body").description("").optional + println("body: " + body) - + } + val loginUserOperation = (apiOperation[String]("loginUser") - summary "Logs user into the system" - parameters( - queryParam[String]("username").description("").optional - - - , - queryParam[String]("password").description("").optional - - ) - ) - - get("/user/login", operation(loginUserOperation)) { - - - val username = params.getAs[String]("username") - - - - - - - + summary "Logs user into the system" + parameters(queryParam[String]("username").description("").optional, + queryParam[String]("password").description("").optional) + ) + 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( - ) - ) - - get("/user/logout", operation(logoutUserOperation)) { + summary "Logs out current logged in user session" + parameters() + ) + get("/user/logout",operation(logoutUserOperation)) { + } + val getUserByNameOperation = (apiOperation[User]("getUserByName") - summary "Get user by user name" - parameters ( - - pathParam[String]("username").description("") - - - ) - ) - - get("/user/{username}", operation(getUserByNameOperation)) { - - - val username = params.getOrElse("username", halt(400)) - - - - - - - - + summary "Get user by user name" + parameters(pathParam[String]("username").description("")) + ) + get("/user/{username}",operation(getUserByNameOperation)) { + + + + val username = params.getOrElse("username", halt(400)) + + println("username: " + username) - + } + val updateUserOperation = (apiOperation[Unit]("updateUser") - summary "Updated user" - parameters( - - pathParam[String]("username").description("") - - - , - - - bodyParam[User]("body").description("").optional - - ) - ) - - put("/user/{username}", operation(updateUserOperation)) { - - - val username = params.getOrElse("username", halt(400)) - - - - - - - - + summary "Updated user" + parameters(pathParam[String]("username").description(""), + bodyParam[User]("body").description("").optional) + ) + put("/user/{username}",operation(updateUserOperation)) { + + + + val username = params.getOrElse("username", halt(400)) + + println("username: " + username) - - - - - - - - - - - - - val body = parsedBody.extract[User] - - + + + + +bodyParam[User]("body").description("").optional + println("body: " + body) - + } + val deleteUserOperation = (apiOperation[Unit]("deleteUser") - summary "Delete user" - parameters ( - - pathParam[String]("username").description("") - - - ) - ) - - delete("/user/{username}", operation(deleteUserOperation)) { - - - val username = params.getOrElse("username", halt(400)) - - - - - - - - + summary "Delete user" + parameters(pathParam[String]("username").description("")) + ) + delete("/user/{username}",operation(deleteUserOperation)) { + + + + val username = params.getOrElse("username", halt(400)) + + println("username: " + username) - + } } \ No newline at end of file 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 fccd9bb21fd9..d4ee7a692e66 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 @@ -1,7 +1,8 @@ package com.wordnik.client.model -case class Category( - id: Long, - name: String - ) + +case class Category ( + id: Long, + name: 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 39a4cc297cba..918cf132d2cd 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 @@ -3,11 +3,11 @@ package com.wordnik.client.model import java.util.Date -case class Order( - id: Long, - petId: Long, - quantity: Int, - shipDate: Date, - status: String, - complete: Boolean - ) +case class Order ( + id: Long, + petId: Long, + quantity: Int, + shipDate: Date, + status: String, + complete: 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 47ecf5f29c9b..cea17dedae7b 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 @@ -1,11 +1,14 @@ package com.wordnik.client.model +import com.wordnik.client.model.Category +import com.wordnik.client.model.Tag -case class Pet( - id: Long, - category: Category, - name: String, - photoUrls: List[String], - tags: List[Tag], - status: String - ) + +case class Pet ( + id: Long, + category: Category, + name: String, + photoUrls: List[String], + tags: List[Tag], + status: 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 c38e6c1561a7..bd28dd4d44dc 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 @@ -1,7 +1,8 @@ package com.wordnik.client.model -case class Tag( - id: Long, - name: String - ) + +case class Tag ( + id: Long, + name: 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 506e1453493c..acadf78f7a1c 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 @@ -1,13 +1,14 @@ package com.wordnik.client.model -case class User( - id: Long, - username: String, - firstName: String, - lastName: String, - email: String, - password: String, - phone: String, - userStatus: Int - ) + +case class User ( + id: Long, + username: String, + firstName: String, + lastName: String, + email: String, + password: String, + phone: String, + userStatus: Int +) diff --git a/samples/server/petstore/scalatra/src/main/webapp/WEB-INF/web.xml b/samples/server/petstore/scalatra/src/main/webapp/WEB-INF/web.xml index a6e529e4aecb..2a08440458ea 100644 --- a/samples/server/petstore/scalatra/src/main/webapp/WEB-INF/web.xml +++ b/samples/server/petstore/scalatra/src/main/webapp/WEB-INF/web.xml @@ -1,17 +1,17 @@ - - - org.scalatra.servlet.ScalatraListener - + + + org.scalatra.servlet.ScalatraListener + - - default - /*.html - /css/* - /js/*.js - /images/* - + + default + /*.html + /css/* + /js/*.js + /images/* + diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiException.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiException.java index f761d3871daf..84da91d8af54 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiException.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-20T10:58:42.063-07:00") public class ApiException extends Exception{ private int code; public ApiException (int code, String msg) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiOriginFilter.java index 432c49d5d5cd..96462ca5e6da 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiOriginFilter.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiOriginFilter.java @@ -5,7 +5,7 @@ import java.io.IOException; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-20T10:58:42.063-07:00") public class ApiOriginFilter implements javax.servlet.Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiResponseMessage.java index c606c9398f49..722f8b75578d 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiResponseMessage.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiResponseMessage.java @@ -3,7 +3,7 @@ package io.swagger.api; import javax.xml.bind.annotation.XmlTransient; @javax.xml.bind.annotation.XmlRootElement -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-20T10:58:42.063-07:00") public class ApiResponseMessage { public static final int ERROR = 1; public static final int WARNING = 2; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/NotFoundException.java index 9c93b025ef93..97d31b90eeae 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/NotFoundException.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/NotFoundException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-20T10:58:42.063-07:00") public class NotFoundException extends ApiException { private int code; public NotFoundException (int code, String msg) { 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 ae731880a173..61bb041119a3 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 @@ -10,6 +10,8 @@ import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.Authorization; +import io.swagger.annotations.AuthorizationScope; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -30,15 +32,15 @@ import static org.springframework.http.MediaType.*; @Controller @RequestMapping(value = "/pet", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/pet", description = "the pet API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-20T10:58:42.063-07:00") public class PetApi { @ApiOperation(value = "Update an existing pet", notes = "", response = Void.class) @ApiResponses(value = { - @ApiResponse(code = 405, message = "Validation exception"), + @ApiResponse(code = 400, message = "Invalid ID supplied"), @ApiResponse(code = 404, message = "Pet not found"), - @ApiResponse(code = 400, message = "Invalid ID supplied") }) + @ApiResponse(code = 405, message = "Validation exception") }) @RequestMapping(value = "", produces = { "application/json", "application/xml" }, consumes = { "application/json", "application/xml" }, @@ -112,9 +114,9 @@ public class PetApi { @ApiOperation(value = "Find pet by ID", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = Pet.class) @ApiResponses(value = { - @ApiResponse(code = 404, message = "Pet not found"), @ApiResponse(code = 200, message = "successful operation"), - @ApiResponse(code = 400, message = "Invalid ID supplied") }) + @ApiResponse(code = 400, message = "Invalid ID supplied"), + @ApiResponse(code = 404, message = "Pet not found") }) @RequestMapping(value = "/{petId}", produces = { "application/json", "application/xml" }, diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java index 577052883c0e..3759544dc7ba 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java @@ -10,6 +10,8 @@ import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.Authorization; +import io.swagger.annotations.AuthorizationScope; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -30,7 +32,7 @@ import static org.springframework.http.MediaType.*; @Controller @RequestMapping(value = "/store", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/store", description = "the store API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-20T10:58:42.063-07:00") public class StoreApi { @@ -70,9 +72,9 @@ public class StoreApi { @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class) @ApiResponses(value = { - @ApiResponse(code = 404, message = "Order not found"), @ApiResponse(code = 200, message = "successful operation"), - @ApiResponse(code = 400, message = "Invalid ID supplied") }) + @ApiResponse(code = 400, message = "Invalid ID supplied"), + @ApiResponse(code = 404, message = "Order not found") }) @RequestMapping(value = "/order/{orderId}", produces = { "application/json", "application/xml" }, @@ -90,8 +92,8 @@ public class StoreApi { @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) @ApiResponses(value = { - @ApiResponse(code = 404, message = "Order not found"), - @ApiResponse(code = 400, message = "Invalid ID supplied") }) + @ApiResponse(code = 400, message = "Invalid ID supplied"), + @ApiResponse(code = 404, message = "Order not found") }) @RequestMapping(value = "/order/{orderId}", produces = { "application/json", "application/xml" }, diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java index 6a68c27ae39f..5ba8a139fa82 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java @@ -10,6 +10,8 @@ import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.Authorization; +import io.swagger.annotations.AuthorizationScope; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -30,7 +32,7 @@ import static org.springframework.http.MediaType.*; @Controller @RequestMapping(value = "/user", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/user", description = "the user API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-20T10:58:42.063-07:00") public class UserApi { @@ -128,9 +130,9 @@ public class UserApi { @ApiOperation(value = "Get user by user name", notes = "", response = User.class) @ApiResponses(value = { - @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 200, message = "successful operation"), - @ApiResponse(code = 400, message = "Invalid username supplied") }) + @ApiResponse(code = 400, message = "Invalid username supplied"), + @ApiResponse(code = 404, message = "User not found") }) @RequestMapping(value = "/{username}", produces = { "application/json", "application/xml" }, @@ -148,8 +150,8 @@ public class UserApi { @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class) @ApiResponses(value = { - @ApiResponse(code = 404, message = "User not found"), - @ApiResponse(code = 400, message = "Invalid user supplied") }) + @ApiResponse(code = 400, message = "Invalid user supplied"), + @ApiResponse(code = 404, message = "User not found") }) @RequestMapping(value = "/{username}", produces = { "application/json", "application/xml" }, @@ -171,8 +173,8 @@ public class UserApi { @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class) @ApiResponses(value = { - @ApiResponse(code = 404, message = "User not found"), - @ApiResponse(code = 400, message = "Invalid username supplied") }) + @ApiResponse(code = 400, message = "Invalid username supplied"), + @ApiResponse(code = 404, message = "User not found") }) @RequestMapping(value = "/{username}", produces = { "application/json", "application/xml" }, diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerConfig.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerConfig.java index 58564e526261..5f1671629eb4 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerConfig.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerConfig.java @@ -18,7 +18,7 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2; @EnableSwagger2 //Loads the spring beans required by the framework @PropertySource("classpath:swagger.properties") @Import(SwaggerUiConfiguration.class) -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-20T10:58:42.063-07:00") public class SwaggerConfig { @Bean ApiInfo apiInfo() { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java index ead813573312..a0674c36b7ad 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java @@ -8,7 +8,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter @Configuration @EnableWebMvc -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-20T10:58:42.063-07:00") public class SwaggerUiConfiguration extends WebMvcConfigurerAdapter { private static final String[] SERVLET_RESOURCE_LOCATIONS = { "/" }; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebApplication.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebApplication.java index 3c42b3f838ae..ad9844b1028f 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebApplication.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebApplication.java @@ -2,7 +2,7 @@ package io.swagger.configuration; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-20T10:58:42.063-07:00") public class WebApplication extends AbstractAnnotationConfigDispatcherServletInitializer { @Override diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebMvcConfiguration.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebMvcConfiguration.java index 4c973c218889..170237eb3373 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebMvcConfiguration.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebMvcConfiguration.java @@ -3,7 +3,7 @@ package io.swagger.configuration; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-20T10:58:42.063-07:00") public class WebMvcConfiguration extends WebMvcConfigurationSupport { @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { 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 d023688b5e50..132aa0a9b8c7 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 @@ -6,7 +6,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-20T10:58:42.063-07:00") public class Category { private Long id = null; 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 87b8633767a5..4a1470a9a9ab 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 @@ -7,7 +7,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-20T10:58:42.063-07:00") public class Order { private Long id = null; 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 5f4de45616e0..16d100faab49 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 @@ -9,7 +9,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-20T10:58:42.063-07:00") public class Pet { private Long id = null; 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 6b2b0e6c1163..d41ca620da41 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 @@ -6,7 +6,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-20T10:58:42.063-07:00") public class Tag { private Long id = null; 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 97044d2a1e7b..f805888214d0 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 @@ -6,7 +6,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-20T10:58:42.063-07:00") public class User { private Long id = null;