From bf9d015fc7c79684303711a3518a5e2f96fb45dc Mon Sep 17 00:00:00 2001 From: tao Date: Sun, 19 Jun 2016 20:58:47 -0700 Subject: [PATCH 1/5] failing test --- .../swagger/codegen/java/JavaModelTest.java | 26 ++++++++++++------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java index d69b2361db1..7927bc2b7ea 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java @@ -1,5 +1,6 @@ package io.swagger.codegen.java; +import com.google.common.collect.Sets; import io.swagger.codegen.CodegenModel; import io.swagger.codegen.CodegenParameter; import io.swagger.codegen.CodegenProperty; @@ -9,16 +10,7 @@ import io.swagger.models.ArrayModel; import io.swagger.models.Model; import io.swagger.models.ModelImpl; import io.swagger.models.parameters.QueryParameter; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.ByteArrayProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.IntegerProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.RefProperty; -import io.swagger.models.properties.StringProperty; - -import com.google.common.collect.Sets; +import io.swagger.models.properties.*; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -458,6 +450,20 @@ public class JavaModelTest { Assert.assertNull(cm.allowableValues); } + @Test(description = "model with Map> should import BigDecimal") + public void mapWithAnListOfBigDecimalTest() { + final Model model = new ModelImpl() + .description("model with Map>") + .property("map", new MapProperty().additionalProperties(new ArrayProperty(new DecimalProperty()))); + + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + final CodegenProperty property = cm.vars.get(0); + Assert.assertEquals(property.datatype, "Map>"); + Assert.assertTrue(cm.imports.contains("BigDecimal")); + } + @DataProvider(name = "modelNames") public static Object[][] primeNumbers() { return new Object[][] { From a4eca5b05c3bc8492212d834baa4637b09ac18ab Mon Sep 17 00:00:00 2001 From: tao Date: Sun, 19 Jun 2016 21:19:21 -0700 Subject: [PATCH 2/5] add import for types used by inner CodegenProperties --- .../io/swagger/codegen/DefaultCodegen.java | 75 ++++--------------- 1 file changed, 14 insertions(+), 61 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index fceb69ac8db..096fffc39fc 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 @@ -2,76 +2,25 @@ package io.swagger.codegen; import com.google.common.base.Function; import com.google.common.collect.Lists; - +import io.swagger.codegen.examples.ExampleGenerator; +import io.swagger.models.*; +import io.swagger.models.auth.*; +import io.swagger.models.parameters.*; +import io.swagger.models.properties.*; +import io.swagger.models.properties.PropertyBuilder.PropertyId; +import io.swagger.util.Json; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nullable; import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.Objects; -import java.util.Set; -import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; -import javax.annotation.Nullable; - -import io.swagger.codegen.examples.ExampleGenerator; -import io.swagger.models.ArrayModel; -import io.swagger.models.ComposedModel; -import io.swagger.models.Model; -import io.swagger.models.ModelImpl; -import io.swagger.models.Operation; -import io.swagger.models.RefModel; -import io.swagger.models.Response; -import io.swagger.models.Swagger; -import io.swagger.models.auth.ApiKeyAuthDefinition; -import io.swagger.models.auth.BasicAuthDefinition; -import io.swagger.models.auth.In; -import io.swagger.models.auth.OAuth2Definition; -import io.swagger.models.auth.SecuritySchemeDefinition; -import io.swagger.models.parameters.BodyParameter; -import io.swagger.models.parameters.CookieParameter; -import io.swagger.models.parameters.FormParameter; -import io.swagger.models.parameters.HeaderParameter; -import io.swagger.models.parameters.Parameter; -import io.swagger.models.parameters.PathParameter; -import io.swagger.models.parameters.QueryParameter; -import io.swagger.models.parameters.SerializableParameter; -import io.swagger.models.properties.AbstractNumericProperty; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.BaseIntegerProperty; -import io.swagger.models.properties.BinaryProperty; -import io.swagger.models.properties.BooleanProperty; -import io.swagger.models.properties.ByteArrayProperty; -import io.swagger.models.properties.DateProperty; -import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.DecimalProperty; -import io.swagger.models.properties.DoubleProperty; -import io.swagger.models.properties.FloatProperty; -import io.swagger.models.properties.IntegerProperty; -import io.swagger.models.properties.LongProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.PropertyBuilder; -import io.swagger.models.properties.PropertyBuilder.PropertyId; -import io.swagger.models.properties.RefProperty; -import io.swagger.models.properties.StringProperty; -import io.swagger.models.properties.UUIDProperty; -import io.swagger.util.Json; - public class DefaultCodegen { protected static final Logger LOGGER = LoggerFactory.getLogger(DefaultCodegen.class); @@ -2597,7 +2546,11 @@ public class DefaultCodegen { } addImport(m, cp.baseType); - addImport(m, cp.complexType); + CodegenProperty innerCp = cp; + while(innerCp != null) { + addImport(m, innerCp.complexType); + innerCp = innerCp.items; + } vars.add(cp); // if required, add to the list "requiredVars" From 4e45ef954d3f31d35372e9a5a17fce9c9e21295d Mon Sep 17 00:00:00 2001 From: tao Date: Sun, 19 Jun 2016 21:29:14 -0700 Subject: [PATCH 3/5] better tests --- .../swagger/codegen/java/JavaModelTest.java | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java index 7927bc2b7ea..11db4afc3ca 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java @@ -450,18 +450,19 @@ public class JavaModelTest { Assert.assertNull(cm.allowableValues); } - @Test(description = "model with Map> should import BigDecimal") + @Test(description = "types used by inner properties should be imported") public void mapWithAnListOfBigDecimalTest() { - final Model model = new ModelImpl() + final CodegenModel cm1 = new JavaClientCodegen().fromModel("sample", new ModelImpl() .description("model with Map>") - .property("map", new MapProperty().additionalProperties(new ArrayProperty(new DecimalProperty()))); + .property("map", new MapProperty().additionalProperties(new ArrayProperty(new DecimalProperty())))); + Assert.assertEquals(cm1.vars.get(0).datatype, "Map>"); + Assert.assertTrue(cm1.imports.contains("BigDecimal")); - final DefaultCodegen codegen = new JavaClientCodegen(); - final CodegenModel cm = codegen.fromModel("sample", model); - - final CodegenProperty property = cm.vars.get(0); - Assert.assertEquals(property.datatype, "Map>"); - Assert.assertTrue(cm.imports.contains("BigDecimal")); + final CodegenModel cm2 = new JavaClientCodegen().fromModel("sample", new ModelImpl() + .description("model with Map>>") + .property("map", new MapProperty().additionalProperties(new MapProperty().additionalProperties(new ArrayProperty(new DecimalProperty()))))); + Assert.assertEquals(cm2.vars.get(0).datatype, "Map>>"); + Assert.assertTrue(cm2.imports.contains("BigDecimal")); } @DataProvider(name = "modelNames") From 6ac27fcafc1772739472b3874c93fa8c6553f180 Mon Sep 17 00:00:00 2001 From: tao Date: Sun, 19 Jun 2016 21:36:08 -0700 Subject: [PATCH 4/5] revert changes to imports --- .../io/swagger/codegen/DefaultCodegen.java | 365 ++++++++++-------- .../swagger/codegen/java/JavaModelTest.java | 12 +- 2 files changed, 216 insertions(+), 161 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 096fffc39fc..79ffc3540f4 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 @@ -3,11 +3,47 @@ package io.swagger.codegen; import com.google.common.base.Function; import com.google.common.collect.Lists; import io.swagger.codegen.examples.ExampleGenerator; -import io.swagger.models.*; -import io.swagger.models.auth.*; -import io.swagger.models.parameters.*; -import io.swagger.models.properties.*; +import io.swagger.models.ArrayModel; +import io.swagger.models.ComposedModel; +import io.swagger.models.Model; +import io.swagger.models.ModelImpl; +import io.swagger.models.Operation; +import io.swagger.models.RefModel; +import io.swagger.models.Response; +import io.swagger.models.Swagger; +import io.swagger.models.auth.ApiKeyAuthDefinition; +import io.swagger.models.auth.BasicAuthDefinition; +import io.swagger.models.auth.In; +import io.swagger.models.auth.OAuth2Definition; +import io.swagger.models.auth.SecuritySchemeDefinition; +import io.swagger.models.parameters.BodyParameter; +import io.swagger.models.parameters.CookieParameter; +import io.swagger.models.parameters.FormParameter; +import io.swagger.models.parameters.HeaderParameter; +import io.swagger.models.parameters.Parameter; +import io.swagger.models.parameters.PathParameter; +import io.swagger.models.parameters.QueryParameter; +import io.swagger.models.parameters.SerializableParameter; +import io.swagger.models.properties.AbstractNumericProperty; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.BaseIntegerProperty; +import io.swagger.models.properties.BinaryProperty; +import io.swagger.models.properties.BooleanProperty; +import io.swagger.models.properties.ByteArrayProperty; +import io.swagger.models.properties.DateProperty; +import io.swagger.models.properties.DateTimeProperty; +import io.swagger.models.properties.DecimalProperty; +import io.swagger.models.properties.DoubleProperty; +import io.swagger.models.properties.FloatProperty; +import io.swagger.models.properties.IntegerProperty; +import io.swagger.models.properties.LongProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; +import io.swagger.models.properties.PropertyBuilder; import io.swagger.models.properties.PropertyBuilder.PropertyId; +import io.swagger.models.properties.RefProperty; +import io.swagger.models.properties.StringProperty; +import io.swagger.models.properties.UUIDProperty; import io.swagger.util.Json; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; @@ -16,12 +52,23 @@ import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.File; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; +import java.util.Objects; +import java.util.Set; +import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; - public class DefaultCodegen { protected static final Logger LOGGER = LoggerFactory.getLogger(DefaultCodegen.class); @@ -88,18 +135,18 @@ public class DefaultCodegen { .get(CodegenConstants.ENSURE_UNIQUE_PARAMS).toString())); } - if(additionalProperties.containsKey(CodegenConstants.MODEL_NAME_PREFIX)){ + if (additionalProperties.containsKey(CodegenConstants.MODEL_NAME_PREFIX)) { this.setModelNamePrefix((String) additionalProperties.get(CodegenConstants.MODEL_NAME_PREFIX)); } - if(additionalProperties.containsKey(CodegenConstants.MODEL_NAME_SUFFIX)){ + if (additionalProperties.containsKey(CodegenConstants.MODEL_NAME_SUFFIX)) { this.setModelNameSuffix((String) additionalProperties.get(CodegenConstants.MODEL_NAME_SUFFIX)); } } // override with any special post-processing for all models - @SuppressWarnings({ "static-method", "unchecked" }) + @SuppressWarnings({"static-method", "unchecked"}) public Map postProcessAllModels(Map objs) { if (supportsInheritance) { // Index all CodegenModels by model name. @@ -140,7 +187,7 @@ public class DefaultCodegen { /** * post process enum defined in model's properties - * + * * @param objs Map of models * @return maps of models with better enum support */ @@ -234,7 +281,7 @@ public class DefaultCodegen { /** * Returns the common prefix of variables for enum naming - * + * * @param vars List of variable names * @return the common prefix for naming */ @@ -250,11 +297,11 @@ public class DefaultCodegen { return ""; } } - + /** * Return the enum default value in the language specifed format - * - * @param value enum variable name + * + * @param value enum variable name * @param datatype data type * @return the default value for the enum */ @@ -265,8 +312,8 @@ public class DefaultCodegen { /** * Return the enum value in the language specifed format * e.g. status becomes "status" - * - * @param value enum variable name + * + * @param value enum variable name * @param datatype data type * @return the sanitized value for enum */ @@ -277,11 +324,11 @@ public class DefaultCodegen { return "\"" + escapeText(value) + "\""; } } - + /** * Return the sanitized variable name for enum - * - * @param value enum variable name + * + * @param value enum variable name * @param datatype data type * @return the sanitized variable name for enum */ @@ -308,12 +355,12 @@ public class DefaultCodegen { // override to post-process any model properties @SuppressWarnings("unused") - public void postProcessModelProperty(CodegenModel model, CodegenProperty property){ + public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { } // override to post-process any parameters @SuppressWarnings("unused") - public void postProcessParameter(CodegenParameter parameter){ + public void postProcessParameter(CodegenParameter parameter) { } //override with any special handling of the entire swagger spec @@ -334,7 +381,7 @@ public class DefaultCodegen { // repalce \ with \\ // repalce " with \" // outter unescape to retain the original multi-byte characters - return StringEscapeUtils.unescapeJava(StringEscapeUtils.escapeJava(input).replace("\\/", "/")).replaceAll("[\\t\\n\\r]"," ").replace("\\", "\\\\").replace("\"", "\\\""); + return StringEscapeUtils.unescapeJava(StringEscapeUtils.escapeJava(input).replace("\\/", "/")).replaceAll("[\\t\\n\\r]", " ").replace("\\", "\\\\").replace("\"", "\\\""); } return input; } @@ -479,11 +526,11 @@ public class DefaultCodegen { this.modelPackage = modelPackage; } - public void setModelNamePrefix(String modelNamePrefix){ + public void setModelNamePrefix(String modelNamePrefix) { this.modelNamePrefix = modelNamePrefix; } - public void setModelNameSuffix(String modelNameSuffix){ + public void setModelNameSuffix(String modelNameSuffix) { this.modelNameSuffix = modelNameSuffix; } @@ -520,8 +567,8 @@ public class DefaultCodegen { } /** - * Return the file name of the Api Documentation - * + * Return the file name of the Api Documentation + * * @param name the file name of the Api * @return the file name of the Api */ @@ -571,14 +618,14 @@ public class DefaultCodegen { /** * Return the capitalized file name of the model documentation - * + * * @param name the model name * @return the file name of the model */ public String toModelDocFilename(String name) { return initialCaps(name); } - + /** * Return the operation ID (method name) * @@ -641,7 +688,7 @@ public class DefaultCodegen { * * @param name the name to be escaped * @return the escaped reserved word - * + *

* throws Runtime exception as reserved word is not allowed (default behavior) */ @SuppressWarnings("static-method") @@ -678,8 +725,8 @@ public class DefaultCodegen { * 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. - * - * + *

+ *

* returns string presentation of the example path (it's a constructor) */ public DefaultCodegen() { @@ -777,7 +824,7 @@ public class DefaultCodegen { /** * Return the example path * - * @param path the path of the operation + * @param path the path of the operation * @param operation Swagger operation object * @return string presentation of the example path */ @@ -845,7 +892,7 @@ public class DefaultCodegen { String type = additionalProperties2.getType(); if (null == type) { LOGGER.error("No Type defined for Additional Property " + additionalProperties2 + "\n" // - + "\tIn Property: " + p); + + "\tIn Property: " + p); } String inner = getSwaggerType(additionalProperties2); return instantiationTypes.get("map") + ""; @@ -859,7 +906,7 @@ public class DefaultCodegen { } /** - * Return the example value of the parameter. + * Return the example value of the parameter. * * @param p Swagger property object */ @@ -874,7 +921,7 @@ public class DefaultCodegen { * @return string presentation of the example value of the property */ public String toExampleValue(Property p) { - if(p.getExample() != null) { + if (p.getExample() != null) { return p.getExample().toString(); } if (p instanceof StringProperty) { @@ -964,7 +1011,7 @@ public class DefaultCodegen { * Useful for initialization with a plain object in Javascript * * @param name Name of the property object - * @param p Swagger property object + * @param p Swagger property object * @return string presentation of the default value of the property */ @SuppressWarnings("static-method") @@ -974,6 +1021,7 @@ public class DefaultCodegen { /** * returns the swagger type for the property + * * @param p Swagger property object * @return string presentation of the type **/ @@ -1006,7 +1054,7 @@ public class DefaultCodegen { datatype = "map"; } else if (p instanceof DecimalProperty) { datatype = "number"; - } else if ( p instanceof UUIDProperty) { + } else if (p instanceof UUIDProperty) { datatype = "UUID"; } else if (p instanceof RefProperty) { try { @@ -1102,7 +1150,7 @@ public class DefaultCodegen { /** * Convert Swagger Model object to Codegen Model object without providing all model definitions * - * @param name the name of the model + * @param name the name of the model * @param model Swagger Model object * @return Codegen Model object */ @@ -1113,8 +1161,8 @@ public class DefaultCodegen { /** * Convert Swagger Model object to Codegen Model object * - * @param name the name of the model - * @param model Swagger 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 */ @@ -1209,7 +1257,7 @@ public class DefaultCodegen { addVars(m, properties, required, allProperties, allRequired); } else { ModelImpl impl = (ModelImpl) model; - if(impl.getEnum() != null && impl.getEnum().size() > 0) { + if (impl.getEnum() != null && impl.getEnum().size() > 0) { m.isEnum = true; // comment out below as allowableValues is not set in post processing model enum m.allowableValues = new HashMap(); @@ -1224,7 +1272,7 @@ public class DefaultCodegen { } if (m.vars != null) { - for(CodegenProperty prop : m.vars) { + for (CodegenProperty prop : m.vars) { postProcessModelProperty(m, prop); } } @@ -1251,7 +1299,7 @@ public class DefaultCodegen { Model interfaceModel = allDefinitions.get(interfaceRef); addProperties(properties, required, interfaceModel, allDefinitions); } else if (model instanceof ComposedModel) { - for (Model component :((ComposedModel) model).getAllOf()) { + for (Model component : ((ComposedModel) model).getAllOf()) { addProperties(properties, required, component, allDefinitions); } } @@ -1276,7 +1324,7 @@ public class DefaultCodegen { * Convert Swagger Property object to Codegen Property object * * @param name name of the property - * @param p Swagger property object + * @param p Swagger property object * @return Codegen Property object */ public CodegenProperty fromProperty(String name, Property p) { @@ -1320,8 +1368,8 @@ public class DefaultCodegen { if (np.getMaximum() != null) { allowableValues.put("max", np.getMaximum()); } - if(allowableValues.size() > 0) { - property.allowableValues = allowableValues; + if (allowableValues.size() > 0) { + property.allowableValues = allowableValues; } } @@ -1373,8 +1421,8 @@ public class DefaultCodegen { if (sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = new ArrayList(); - for(Integer i : _enum) { - property._enum.add(i.toString()); + for (Integer i : _enum) { + property._enum.add(i.toString()); } property.isEnum = true; @@ -1391,8 +1439,8 @@ public class DefaultCodegen { if (sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = new ArrayList(); - for(Long i : _enum) { - property._enum.add(i.toString()); + for (Long i : _enum) { + property._enum.add(i.toString()); } property.isEnum = true; @@ -1440,8 +1488,8 @@ public class DefaultCodegen { if (sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = new ArrayList(); - for(Double i : _enum) { - property._enum.add(i.toString()); + for (Double i : _enum) { + property._enum.add(i.toString()); } property.isEnum = true; @@ -1458,8 +1506,8 @@ public class DefaultCodegen { if (sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = new ArrayList(); - for(Float i : _enum) { - property._enum.add(i.toString()); + for (Float i : _enum) { + property._enum.add(i.toString()); } property.isEnum = true; @@ -1476,8 +1524,8 @@ public class DefaultCodegen { if (sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = new ArrayList(); - for(String i : _enum) { - property._enum.add(i.toString()); + for (String i : _enum) { + property._enum.add(i.toString()); } property.isEnum = true; @@ -1494,8 +1542,8 @@ public class DefaultCodegen { if (sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = new ArrayList(); - for(String i : _enum) { - property._enum.add(i.toString()); + for (String i : _enum) { + property._enum.add(i.toString()); } property.isEnum = true; @@ -1516,30 +1564,30 @@ public class DefaultCodegen { property.baseType = getSwaggerType(p); - if (p instanceof ArrayProperty) { - property.isContainer = true; - property.isListContainer = true; - property.containerType = "array"; - ArrayProperty ap = (ArrayProperty) p; - CodegenProperty cp = fromProperty(property.name, ap.getItems()); - if (cp == null) { - LOGGER.warn("skipping invalid property " + Json.pretty(p)); - } else { - property.baseType = getSwaggerType(p); - if (!languageSpecificPrimitives.contains(cp.baseType)) { - property.complexType = cp.baseType; - } else { - property.isPrimitiveType = true; - } - property.items = cp; - if (property.items.isEnum) { - property.datatypeWithEnum = property.datatypeWithEnum.replace(property.items.baseType, - property.items.datatypeWithEnum); - if(property.defaultValue != null) - property.defaultValue = property.defaultValue.replace(property.items.baseType, property.items.datatypeWithEnum); - } - } - } else if (p instanceof MapProperty) { + if (p instanceof ArrayProperty) { + property.isContainer = true; + property.isListContainer = true; + property.containerType = "array"; + ArrayProperty ap = (ArrayProperty) p; + CodegenProperty cp = fromProperty(property.name, ap.getItems()); + if (cp == null) { + LOGGER.warn("skipping invalid property " + Json.pretty(p)); + } else { + property.baseType = getSwaggerType(p); + if (!languageSpecificPrimitives.contains(cp.baseType)) { + property.complexType = cp.baseType; + } else { + property.isPrimitiveType = true; + } + property.items = cp; + if (property.items.isEnum) { + property.datatypeWithEnum = property.datatypeWithEnum.replace(property.items.baseType, + property.items.datatypeWithEnum); + if (property.defaultValue != null) + property.defaultValue = property.defaultValue.replace(property.items.baseType, property.items.datatypeWithEnum); + } + } + } else if (p instanceof MapProperty) { property.isContainer = true; property.isMapContainer = true; property.containerType = "map"; @@ -1570,6 +1618,7 @@ public class DefaultCodegen { /** * Override with any special handling of response codes + * * @param responses Swagger Operation's responses * @return default method response or null if not found */ @@ -1592,24 +1641,24 @@ public class DefaultCodegen { /** * 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 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); + 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 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 + * @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) { @@ -1708,7 +1757,7 @@ public class DefaultCodegen { } r.isDefault = response == methodResponse; op.responses.add(r); - if (r.isBinary && r.isDefault){ + if (r.isBinary && r.isDefault) { op.isResponseBinary = Boolean.TRUE; } } @@ -1835,16 +1884,16 @@ public class DefaultCodegen { // move "required" parameters in front of "optional" parameters if (sortParamsByRequiredFlag) { - Collections.sort(allParams, new Comparator() { - @Override - public int compare(CodegenParameter one, CodegenParameter another) { - boolean oneRequired = one.required == null ? false : one.required; - boolean anotherRequired = another.required == null ? false : another.required; - if (oneRequired == anotherRequired) return 0; - else if (oneRequired) return -1; - else return 1; - } - }); + Collections.sort(allParams, new Comparator() { + @Override + public int compare(CodegenParameter one, CodegenParameter another) { + boolean oneRequired = one.required == null ? false : one.required; + boolean anotherRequired = another.required == null ? false : another.required; + if (oneRequired == anotherRequired) return 0; + else if (oneRequired) return -1; + else return 1; + } + }); } op.allParams = addHasMore(allParams); op.bodyParams = addHasMore(bodyParams); @@ -1876,7 +1925,7 @@ public class DefaultCodegen { * Convert Swagger Response object to Codegen Response object * * @param responseCode HTTP response code - * @param response Swagger Response object + * @param response Swagger Response object * @return Codegen Response object */ public CodegenResponse fromResponse(String responseCode, Response response) { @@ -1932,7 +1981,7 @@ public class DefaultCodegen { /** * Convert Swagger Parameter object to Codegen Parameter object * - * @param param Swagger parameter object + * @param param Swagger parameter object * @param imports set of imports for library/package/module * @return Codegen Parameter object */ @@ -2016,18 +2065,18 @@ public class DefaultCodegen { setParameterBooleanFlagWithCodegenProperty(p, model); p.dataType = model.datatype; - if(model.isEnum) { + if (model.isEnum) { p.datatypeWithEnum = model.datatypeWithEnum; } p.isEnum = model.isEnum; p._enum = model._enum; p.allowableValues = model.allowableValues; - if(model.items != null && model.items.isEnum) { + if (model.items != null && model.items.isEnum) { p.datatypeWithEnum = model.datatypeWithEnum; p.items = model.items; } p.collectionFormat = collectionFormat; - if(collectionFormat != null && collectionFormat.equals("multi")) { + if (collectionFormat != null && collectionFormat.equals("multi")) { p.isCollectionFormatMulti = true; } p.paramName = toParamName(qp.getName()); @@ -2151,7 +2200,7 @@ public class DefaultCodegen { p.example = new String("2013-10-20T19:20:30+01:00"); } else if (param instanceof FormParameter && ("file".equalsIgnoreCase(((FormParameter) param).getType()) || - "file".equals(p.baseType))) { + "file".equals(p.baseType))) { p.isFile = true; p.example = new String("/path/to/file.txt"); } @@ -2179,7 +2228,7 @@ public class DefaultCodegen { } else if (param instanceof FormParameter) { if ("file".equalsIgnoreCase(((FormParameter) param).getType())) { p.isFile = true; - } else if("file".equals(p.baseType)){ + } else if ("file".equals(p.baseType)) { p.isFile = true; } else { p.notFile = true; @@ -2200,7 +2249,7 @@ public class DefaultCodegen { @SuppressWarnings("static-method") public List fromSecurity(Map schemes) { if (schemes == null) { - return Collections.emptyList(); + return Collections.emptyList(); } List secs = new ArrayList(schemes.size()); @@ -2219,12 +2268,12 @@ public class DefaultCodegen { sec.keyParamName = apiKeyDefinition.getName(); sec.isKeyInHeader = apiKeyDefinition.getIn() == In.HEADER; sec.isKeyInQuery = !sec.isKeyInHeader; - } else if(schemeDefinition instanceof BasicAuthDefinition) { + } else if (schemeDefinition instanceof BasicAuthDefinition) { sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = sec.isOAuth = false; sec.isBasic = true; } else { - final OAuth2Definition oauth2Definition = (OAuth2Definition) schemeDefinition; - sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = sec.isBasic = false; + final OAuth2Definition oauth2Definition = (OAuth2Definition) schemeDefinition; + sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = sec.isBasic = false; sec.isOAuth = true; sec.flow = oauth2Definition.getFlow(); sec.authorizationUrl = oauth2Definition.getAuthorizationUrl(); @@ -2232,7 +2281,7 @@ public class DefaultCodegen { if (oauth2Definition.getScopes() != null) { List> scopes = new ArrayList>(); int count = 0, numScopes = oauth2Definition.getScopes().size(); - for(Map.Entry scopeEntry : oauth2Definition.getScopes().entrySet()) { + for (Map.Entry scopeEntry : oauth2Definition.getScopes().entrySet()) { Map scope = new HashMap(); scope.put("scope", scopeEntry.getKey()); scope.put("description", scopeEntry.getValue()); @@ -2257,10 +2306,10 @@ public class DefaultCodegen { } protected void setReservedWordsLowerCase(List words) { - reservedWords = new HashSet(); - for (String word : words) { - reservedWords.add(word.toLowerCase()); - } + reservedWords = new HashSet(); + for (String word : words) { + reservedWords.add(word.toLowerCase()); + } } protected boolean isReservedWord(String word) { @@ -2270,8 +2319,8 @@ public class DefaultCodegen { /** * Get operationId from the operation object, and if it's blank, generate a new one from the given parameters. * - * @param operation the operation object - * @param path the path of the operation + * @param operation the operation object + * @param path the path of the operation * @param httpMethod the HTTP method of the operation * @return the (generated) operationId */ @@ -2312,7 +2361,7 @@ public class DefaultCodegen { */ protected boolean needToImport(String type) { return !defaultIncludes.contains(type) - && !languageSpecificPrimitives.contains(type); + && !languageSpecificPrimitives.contains(type); } @SuppressWarnings("static-method") @@ -2370,11 +2419,11 @@ public class DefaultCodegen { /** * Add operation to group * - * @param tag name of the tag + * @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 + * @param operation Swagger Operation object + * @param co Codegen Operation object + * @param operations map of Codegen operations */ @SuppressWarnings("static-method") public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { @@ -2387,13 +2436,13 @@ public class DefaultCodegen { String uniqueName = co.operationId; int counter = 0; - for(CodegenOperation op : opList) { - if(uniqueName.equals(op.operationId)) { + for (CodegenOperation op : opList) { + if (uniqueName.equals(op.operationId)) { uniqueName = co.operationId + "_" + counter; - counter ++; + counter++; } } - if(!co.operationId.equals(uniqueName)) { + if (!co.operationId.equals(uniqueName)) { LOGGER.warn("generated unique operationId `" + uniqueName + "`"); } co.operationId = uniqueName; @@ -2455,9 +2504,9 @@ public class DefaultCodegen { /** * Generate the next name for the given name, i.e. append "2" to the base name if not ending with a number, * otherwise increase the number by 1. For example: - * status => status2 - * status2 => status3 - * myName100 => myName101 + * status => status2 + * status2 => status3 + * myName100 => myName101 * * @param name The base name * @return The next name for the base name @@ -2485,7 +2534,7 @@ public class DefaultCodegen { } private void addVars(CodegenModel m, Map properties, List required, - Map allProperties, List allRequired) { + Map allProperties, List allRequired) { m.hasRequired = false; if (properties != null && !properties.isEmpty()) { @@ -2493,7 +2542,7 @@ public class DefaultCodegen { m.hasEnums = false; - Set mandatory = required == null ? Collections. emptySet() + Set mandatory = required == null ? Collections.emptySet() : new TreeSet(required); addVars(m, m.vars, properties, mandatory); m.allMandatory = m.mandatory = mandatory; @@ -2504,7 +2553,7 @@ public class DefaultCodegen { } if (allProperties != null) { - Set allMandatory = allRequired == null ? Collections. emptySet() + Set allMandatory = allRequired == null ? Collections.emptySet() : new TreeSet(allRequired); addVars(m, m.allVars, allProperties, allMandatory); m.allMandatory = allMandatory; @@ -2517,7 +2566,7 @@ public class DefaultCodegen { final int totalCount = propertyList.size(); for (int i = 0; i < totalCount; i++) { Map.Entry entry = propertyList.get(i); - + final String key = entry.getKey(); final Property prop = entry.getValue(); @@ -2533,10 +2582,10 @@ public class DefaultCodegen { m.hasEnums = true; } - if (i+1 != totalCount) { + if (i + 1 != totalCount) { cp.hasMore = true; // check the next entry to see if it's read only - if (!Boolean.TRUE.equals(propertyList.get(i+1).getValue().getReadOnly())) { + if (!Boolean.TRUE.equals(propertyList.get(i + 1).getValue().getReadOnly())) { cp.hasMoreNonReadOnly = true; // next entry is not ready only } } @@ -2547,7 +2596,7 @@ public class DefaultCodegen { addImport(m, cp.baseType); CodegenProperty innerCp = cp; - while(innerCp != null) { + while (innerCp != null) { addImport(m, innerCp.complexType); innerCp = innerCp.items; } @@ -2584,7 +2633,7 @@ public class DefaultCodegen { /** * Remove characters that is not good to be included in method name from the input and camelize it * - * @param name string to be camelize + * @param name string to be camelize * @param nonNameElementPattern a regex pattern of the characters that is not good to be included in name * @return camelized string */ @@ -2617,7 +2666,7 @@ public class DefaultCodegen { /** * Camelize name (parameter, property, method, etc) * - * @param word string to be camelize + * @param word string to be camelize * @param lowercaseFirstLetter lower case for first letter if set to true * @return camelized string */ @@ -2679,8 +2728,7 @@ public class DefaultCodegen { * Return the full path and API documentation file * * @param templateName template name - * @param tag tag - * + * @param tag tag * @return the API documentation file name with full path */ public String apiDocFilename(String templateName, String tag) { @@ -2692,8 +2740,7 @@ public class DefaultCodegen { * Return the full path and API test file * * @param templateName template name - * @param tag tag - * + * @param tag tag * @return the API test file name with full path */ public String apiTestFilename(String templateName, String tag) { @@ -2716,6 +2763,7 @@ public class DefaultCodegen { /** * All library templates supported. * (key: library name, value: library description) + * * @return the supported libraries */ public Map supportedLibraries() { @@ -2725,7 +2773,7 @@ public class DefaultCodegen { /** * Set library template (sub-template). * - * @param library Library template + * @param library Library template */ public void setLibrary(String library) { if (library != null && !supportedLibraries.containsKey(library)) @@ -2745,7 +2793,7 @@ public class DefaultCodegen { /** * Set Git user ID. * - * @param gitUserId Git user ID + * @param gitUserId Git user ID */ public void setGitUserId(String gitUserId) { this.gitUserId = gitUserId; @@ -2763,7 +2811,7 @@ public class DefaultCodegen { /** * Set Git repo ID. * - * @param gitRepoId Git repo ID + * @param gitRepoId Git repo ID */ public void setGitRepoId(String gitRepoId) { this.gitRepoId = gitRepoId; @@ -2806,7 +2854,7 @@ public class DefaultCodegen { } /** - * HTTP user agent + * HTTP user agent * * @return HTTP user agent */ @@ -2836,11 +2884,11 @@ public class DefaultCodegen { // encountered so far and hopefully make it easier for others to add more special // cases in the future. - // better error handling when map/array type is invalid - if (name == null) { - LOGGER.error("String to be sanitized is null. Default to ERROR_UNKNOWN"); - return "ERROR_UNKNOWN"; - } + // better error handling when map/array type is invalid + if (name == null) { + LOGGER.error("String to be sanitized is null. Default to ERROR_UNKNOWN"); + return "ERROR_UNKNOWN"; + } // if the name is just '$', map it to 'value' for the time being. if ("$".equals(name)) { @@ -2888,23 +2936,22 @@ public class DefaultCodegen { /** * Only write if the file doesn't exist * - * @param outputFolder Output folder + * @param outputFolder Output folder * @param supportingFile Supporting file */ public void writeOptional(String outputFolder, SupportingFile supportingFile) { String folder = ""; - if(outputFolder != null && !"".equals(outputFolder)) { + if (outputFolder != null && !"".equals(outputFolder)) { folder += outputFolder + File.separator; } folder += supportingFile.folder; - if(!"".equals(folder)) { + if (!"".equals(folder)) { folder += File.separator + supportingFile.destinationFilename; - } - else { + } else { folder = supportingFile.destinationFilename; } - if(!new File(folder).exists()) { + if (!new File(folder).exists()) { supportingFiles.add(supportingFile); } else { LOGGER.info("Skipped overwriting " + supportingFile.destinationFilename + " as the file already exists in " + folder); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java index 11db4afc3ca..50474d84ae2 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java @@ -10,7 +10,15 @@ import io.swagger.models.ArrayModel; import io.swagger.models.Model; import io.swagger.models.ModelImpl; import io.swagger.models.parameters.QueryParameter; -import io.swagger.models.properties.*; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.ByteArrayProperty; +import io.swagger.models.properties.DateTimeProperty; +import io.swagger.models.properties.DecimalProperty; +import io.swagger.models.properties.IntegerProperty; +import io.swagger.models.properties.LongProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.RefProperty; +import io.swagger.models.properties.StringProperty; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -467,7 +475,7 @@ public class JavaModelTest { @DataProvider(name = "modelNames") public static Object[][] primeNumbers() { - return new Object[][] { + return new Object[][]{ {"sample", "Sample"}, {"sample_name", "SampleName"}, {"sample__name", "SampleName"}, From 90d61578d0e202c7b569d2a22f6145f71d206e64 Mon Sep 17 00:00:00 2001 From: tao Date: Sun, 19 Jun 2016 21:39:06 -0700 Subject: [PATCH 5/5] remove reformat --- .../io/swagger/codegen/DefaultCodegen.java | 306 +++++++++--------- .../swagger/codegen/java/JavaModelTest.java | 2 +- 2 files changed, 154 insertions(+), 154 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 79ffc3540f4..040b25293e1 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 @@ -135,18 +135,18 @@ public class DefaultCodegen { .get(CodegenConstants.ENSURE_UNIQUE_PARAMS).toString())); } - if (additionalProperties.containsKey(CodegenConstants.MODEL_NAME_PREFIX)) { + if(additionalProperties.containsKey(CodegenConstants.MODEL_NAME_PREFIX)){ this.setModelNamePrefix((String) additionalProperties.get(CodegenConstants.MODEL_NAME_PREFIX)); } - if (additionalProperties.containsKey(CodegenConstants.MODEL_NAME_SUFFIX)) { + if(additionalProperties.containsKey(CodegenConstants.MODEL_NAME_SUFFIX)){ this.setModelNameSuffix((String) additionalProperties.get(CodegenConstants.MODEL_NAME_SUFFIX)); } } // override with any special post-processing for all models - @SuppressWarnings({"static-method", "unchecked"}) + @SuppressWarnings({ "static-method", "unchecked" }) public Map postProcessAllModels(Map objs) { if (supportsInheritance) { // Index all CodegenModels by model name. @@ -187,7 +187,7 @@ public class DefaultCodegen { /** * post process enum defined in model's properties - * + * * @param objs Map of models * @return maps of models with better enum support */ @@ -281,7 +281,7 @@ public class DefaultCodegen { /** * Returns the common prefix of variables for enum naming - * + * * @param vars List of variable names * @return the common prefix for naming */ @@ -297,11 +297,11 @@ public class DefaultCodegen { return ""; } } - + /** * Return the enum default value in the language specifed format - * - * @param value enum variable name + * + * @param value enum variable name * @param datatype data type * @return the default value for the enum */ @@ -312,8 +312,8 @@ public class DefaultCodegen { /** * Return the enum value in the language specifed format * e.g. status becomes "status" - * - * @param value enum variable name + * + * @param value enum variable name * @param datatype data type * @return the sanitized value for enum */ @@ -324,11 +324,11 @@ public class DefaultCodegen { return "\"" + escapeText(value) + "\""; } } - + /** * Return the sanitized variable name for enum - * - * @param value enum variable name + * + * @param value enum variable name * @param datatype data type * @return the sanitized variable name for enum */ @@ -355,12 +355,12 @@ public class DefaultCodegen { // override to post-process any model properties @SuppressWarnings("unused") - public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { + public void postProcessModelProperty(CodegenModel model, CodegenProperty property){ } // override to post-process any parameters @SuppressWarnings("unused") - public void postProcessParameter(CodegenParameter parameter) { + public void postProcessParameter(CodegenParameter parameter){ } //override with any special handling of the entire swagger spec @@ -381,7 +381,7 @@ public class DefaultCodegen { // repalce \ with \\ // repalce " with \" // outter unescape to retain the original multi-byte characters - return StringEscapeUtils.unescapeJava(StringEscapeUtils.escapeJava(input).replace("\\/", "/")).replaceAll("[\\t\\n\\r]", " ").replace("\\", "\\\\").replace("\"", "\\\""); + return StringEscapeUtils.unescapeJava(StringEscapeUtils.escapeJava(input).replace("\\/", "/")).replaceAll("[\\t\\n\\r]"," ").replace("\\", "\\\\").replace("\"", "\\\""); } return input; } @@ -526,11 +526,11 @@ public class DefaultCodegen { this.modelPackage = modelPackage; } - public void setModelNamePrefix(String modelNamePrefix) { + public void setModelNamePrefix(String modelNamePrefix){ this.modelNamePrefix = modelNamePrefix; } - public void setModelNameSuffix(String modelNameSuffix) { + public void setModelNameSuffix(String modelNameSuffix){ this.modelNameSuffix = modelNameSuffix; } @@ -567,8 +567,8 @@ public class DefaultCodegen { } /** - * Return the file name of the Api Documentation - * + * Return the file name of the Api Documentation + * * @param name the file name of the Api * @return the file name of the Api */ @@ -618,14 +618,14 @@ public class DefaultCodegen { /** * Return the capitalized file name of the model documentation - * + * * @param name the model name * @return the file name of the model */ public String toModelDocFilename(String name) { return initialCaps(name); } - + /** * Return the operation ID (method name) * @@ -688,7 +688,7 @@ public class DefaultCodegen { * * @param name the name to be escaped * @return the escaped reserved word - *

+ * * throws Runtime exception as reserved word is not allowed (default behavior) */ @SuppressWarnings("static-method") @@ -725,8 +725,8 @@ public class DefaultCodegen { * 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. - *

- *

+ * + * * returns string presentation of the example path (it's a constructor) */ public DefaultCodegen() { @@ -824,7 +824,7 @@ public class DefaultCodegen { /** * Return the example path * - * @param path the path of the operation + * @param path the path of the operation * @param operation Swagger operation object * @return string presentation of the example path */ @@ -892,7 +892,7 @@ public class DefaultCodegen { String type = additionalProperties2.getType(); if (null == type) { LOGGER.error("No Type defined for Additional Property " + additionalProperties2 + "\n" // - + "\tIn Property: " + p); + + "\tIn Property: " + p); } String inner = getSwaggerType(additionalProperties2); return instantiationTypes.get("map") + ""; @@ -906,7 +906,7 @@ public class DefaultCodegen { } /** - * Return the example value of the parameter. + * Return the example value of the parameter. * * @param p Swagger property object */ @@ -921,7 +921,7 @@ public class DefaultCodegen { * @return string presentation of the example value of the property */ public String toExampleValue(Property p) { - if (p.getExample() != null) { + if(p.getExample() != null) { return p.getExample().toString(); } if (p instanceof StringProperty) { @@ -1011,7 +1011,7 @@ public class DefaultCodegen { * Useful for initialization with a plain object in Javascript * * @param name Name of the property object - * @param p Swagger property object + * @param p Swagger property object * @return string presentation of the default value of the property */ @SuppressWarnings("static-method") @@ -1021,7 +1021,6 @@ public class DefaultCodegen { /** * returns the swagger type for the property - * * @param p Swagger property object * @return string presentation of the type **/ @@ -1054,7 +1053,7 @@ public class DefaultCodegen { datatype = "map"; } else if (p instanceof DecimalProperty) { datatype = "number"; - } else if (p instanceof UUIDProperty) { + } else if ( p instanceof UUIDProperty) { datatype = "UUID"; } else if (p instanceof RefProperty) { try { @@ -1150,7 +1149,7 @@ public class DefaultCodegen { /** * Convert Swagger Model object to Codegen Model object without providing all model definitions * - * @param name the name of the model + * @param name the name of the model * @param model Swagger Model object * @return Codegen Model object */ @@ -1161,8 +1160,8 @@ public class DefaultCodegen { /** * Convert Swagger Model object to Codegen Model object * - * @param name the name of the model - * @param model Swagger 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 */ @@ -1257,7 +1256,7 @@ public class DefaultCodegen { addVars(m, properties, required, allProperties, allRequired); } else { ModelImpl impl = (ModelImpl) model; - if (impl.getEnum() != null && impl.getEnum().size() > 0) { + if(impl.getEnum() != null && impl.getEnum().size() > 0) { m.isEnum = true; // comment out below as allowableValues is not set in post processing model enum m.allowableValues = new HashMap(); @@ -1272,7 +1271,7 @@ public class DefaultCodegen { } if (m.vars != null) { - for (CodegenProperty prop : m.vars) { + for(CodegenProperty prop : m.vars) { postProcessModelProperty(m, prop); } } @@ -1299,7 +1298,7 @@ public class DefaultCodegen { Model interfaceModel = allDefinitions.get(interfaceRef); addProperties(properties, required, interfaceModel, allDefinitions); } else if (model instanceof ComposedModel) { - for (Model component : ((ComposedModel) model).getAllOf()) { + for (Model component :((ComposedModel) model).getAllOf()) { addProperties(properties, required, component, allDefinitions); } } @@ -1324,7 +1323,7 @@ public class DefaultCodegen { * Convert Swagger Property object to Codegen Property object * * @param name name of the property - * @param p Swagger property object + * @param p Swagger property object * @return Codegen Property object */ public CodegenProperty fromProperty(String name, Property p) { @@ -1368,8 +1367,8 @@ public class DefaultCodegen { if (np.getMaximum() != null) { allowableValues.put("max", np.getMaximum()); } - if (allowableValues.size() > 0) { - property.allowableValues = allowableValues; + if(allowableValues.size() > 0) { + property.allowableValues = allowableValues; } } @@ -1421,8 +1420,8 @@ public class DefaultCodegen { if (sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = new ArrayList(); - for (Integer i : _enum) { - property._enum.add(i.toString()); + for(Integer i : _enum) { + property._enum.add(i.toString()); } property.isEnum = true; @@ -1439,8 +1438,8 @@ public class DefaultCodegen { if (sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = new ArrayList(); - for (Long i : _enum) { - property._enum.add(i.toString()); + for(Long i : _enum) { + property._enum.add(i.toString()); } property.isEnum = true; @@ -1488,8 +1487,8 @@ public class DefaultCodegen { if (sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = new ArrayList(); - for (Double i : _enum) { - property._enum.add(i.toString()); + for(Double i : _enum) { + property._enum.add(i.toString()); } property.isEnum = true; @@ -1506,8 +1505,8 @@ public class DefaultCodegen { if (sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = new ArrayList(); - for (Float i : _enum) { - property._enum.add(i.toString()); + for(Float i : _enum) { + property._enum.add(i.toString()); } property.isEnum = true; @@ -1524,8 +1523,8 @@ public class DefaultCodegen { if (sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = new ArrayList(); - for (String i : _enum) { - property._enum.add(i.toString()); + for(String i : _enum) { + property._enum.add(i.toString()); } property.isEnum = true; @@ -1542,8 +1541,8 @@ public class DefaultCodegen { if (sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = new ArrayList(); - for (String i : _enum) { - property._enum.add(i.toString()); + for(String i : _enum) { + property._enum.add(i.toString()); } property.isEnum = true; @@ -1564,30 +1563,30 @@ public class DefaultCodegen { property.baseType = getSwaggerType(p); - if (p instanceof ArrayProperty) { - property.isContainer = true; - property.isListContainer = true; - property.containerType = "array"; - ArrayProperty ap = (ArrayProperty) p; - CodegenProperty cp = fromProperty(property.name, ap.getItems()); - if (cp == null) { - LOGGER.warn("skipping invalid property " + Json.pretty(p)); - } else { - property.baseType = getSwaggerType(p); - if (!languageSpecificPrimitives.contains(cp.baseType)) { - property.complexType = cp.baseType; - } else { - property.isPrimitiveType = true; - } - property.items = cp; - if (property.items.isEnum) { - property.datatypeWithEnum = property.datatypeWithEnum.replace(property.items.baseType, - property.items.datatypeWithEnum); - if (property.defaultValue != null) - property.defaultValue = property.defaultValue.replace(property.items.baseType, property.items.datatypeWithEnum); - } - } - } else if (p instanceof MapProperty) { + if (p instanceof ArrayProperty) { + property.isContainer = true; + property.isListContainer = true; + property.containerType = "array"; + ArrayProperty ap = (ArrayProperty) p; + CodegenProperty cp = fromProperty(property.name, ap.getItems()); + if (cp == null) { + LOGGER.warn("skipping invalid property " + Json.pretty(p)); + } else { + property.baseType = getSwaggerType(p); + if (!languageSpecificPrimitives.contains(cp.baseType)) { + property.complexType = cp.baseType; + } else { + property.isPrimitiveType = true; + } + property.items = cp; + if (property.items.isEnum) { + property.datatypeWithEnum = property.datatypeWithEnum.replace(property.items.baseType, + property.items.datatypeWithEnum); + if(property.defaultValue != null) + property.defaultValue = property.defaultValue.replace(property.items.baseType, property.items.datatypeWithEnum); + } + } + } else if (p instanceof MapProperty) { property.isContainer = true; property.isMapContainer = true; property.containerType = "map"; @@ -1618,7 +1617,6 @@ public class DefaultCodegen { /** * Override with any special handling of response codes - * * @param responses Swagger Operation's responses * @return default method response or null if not found */ @@ -1641,24 +1639,24 @@ public class DefaultCodegen { /** * 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 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); + 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 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 + * @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) { @@ -1757,7 +1755,7 @@ public class DefaultCodegen { } r.isDefault = response == methodResponse; op.responses.add(r); - if (r.isBinary && r.isDefault) { + if (r.isBinary && r.isDefault){ op.isResponseBinary = Boolean.TRUE; } } @@ -1884,16 +1882,16 @@ public class DefaultCodegen { // move "required" parameters in front of "optional" parameters if (sortParamsByRequiredFlag) { - Collections.sort(allParams, new Comparator() { - @Override - public int compare(CodegenParameter one, CodegenParameter another) { - boolean oneRequired = one.required == null ? false : one.required; - boolean anotherRequired = another.required == null ? false : another.required; - if (oneRequired == anotherRequired) return 0; - else if (oneRequired) return -1; - else return 1; - } - }); + Collections.sort(allParams, new Comparator() { + @Override + public int compare(CodegenParameter one, CodegenParameter another) { + boolean oneRequired = one.required == null ? false : one.required; + boolean anotherRequired = another.required == null ? false : another.required; + if (oneRequired == anotherRequired) return 0; + else if (oneRequired) return -1; + else return 1; + } + }); } op.allParams = addHasMore(allParams); op.bodyParams = addHasMore(bodyParams); @@ -1925,7 +1923,7 @@ public class DefaultCodegen { * Convert Swagger Response object to Codegen Response object * * @param responseCode HTTP response code - * @param response Swagger Response object + * @param response Swagger Response object * @return Codegen Response object */ public CodegenResponse fromResponse(String responseCode, Response response) { @@ -1981,7 +1979,7 @@ public class DefaultCodegen { /** * Convert Swagger Parameter object to Codegen Parameter object * - * @param param Swagger parameter object + * @param param Swagger parameter object * @param imports set of imports for library/package/module * @return Codegen Parameter object */ @@ -2065,18 +2063,18 @@ public class DefaultCodegen { setParameterBooleanFlagWithCodegenProperty(p, model); p.dataType = model.datatype; - if (model.isEnum) { + if(model.isEnum) { p.datatypeWithEnum = model.datatypeWithEnum; } p.isEnum = model.isEnum; p._enum = model._enum; p.allowableValues = model.allowableValues; - if (model.items != null && model.items.isEnum) { + if(model.items != null && model.items.isEnum) { p.datatypeWithEnum = model.datatypeWithEnum; p.items = model.items; } p.collectionFormat = collectionFormat; - if (collectionFormat != null && collectionFormat.equals("multi")) { + if(collectionFormat != null && collectionFormat.equals("multi")) { p.isCollectionFormatMulti = true; } p.paramName = toParamName(qp.getName()); @@ -2200,7 +2198,7 @@ public class DefaultCodegen { p.example = new String("2013-10-20T19:20:30+01:00"); } else if (param instanceof FormParameter && ("file".equalsIgnoreCase(((FormParameter) param).getType()) || - "file".equals(p.baseType))) { + "file".equals(p.baseType))) { p.isFile = true; p.example = new String("/path/to/file.txt"); } @@ -2228,7 +2226,7 @@ public class DefaultCodegen { } else if (param instanceof FormParameter) { if ("file".equalsIgnoreCase(((FormParameter) param).getType())) { p.isFile = true; - } else if ("file".equals(p.baseType)) { + } else if("file".equals(p.baseType)){ p.isFile = true; } else { p.notFile = true; @@ -2249,7 +2247,7 @@ public class DefaultCodegen { @SuppressWarnings("static-method") public List fromSecurity(Map schemes) { if (schemes == null) { - return Collections.emptyList(); + return Collections.emptyList(); } List secs = new ArrayList(schemes.size()); @@ -2268,12 +2266,12 @@ public class DefaultCodegen { sec.keyParamName = apiKeyDefinition.getName(); sec.isKeyInHeader = apiKeyDefinition.getIn() == In.HEADER; sec.isKeyInQuery = !sec.isKeyInHeader; - } else if (schemeDefinition instanceof BasicAuthDefinition) { + } else if(schemeDefinition instanceof BasicAuthDefinition) { sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = sec.isOAuth = false; sec.isBasic = true; } else { - final OAuth2Definition oauth2Definition = (OAuth2Definition) schemeDefinition; - sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = sec.isBasic = false; + final OAuth2Definition oauth2Definition = (OAuth2Definition) schemeDefinition; + sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = sec.isBasic = false; sec.isOAuth = true; sec.flow = oauth2Definition.getFlow(); sec.authorizationUrl = oauth2Definition.getAuthorizationUrl(); @@ -2281,7 +2279,7 @@ public class DefaultCodegen { if (oauth2Definition.getScopes() != null) { List> scopes = new ArrayList>(); int count = 0, numScopes = oauth2Definition.getScopes().size(); - for (Map.Entry scopeEntry : oauth2Definition.getScopes().entrySet()) { + for(Map.Entry scopeEntry : oauth2Definition.getScopes().entrySet()) { Map scope = new HashMap(); scope.put("scope", scopeEntry.getKey()); scope.put("description", scopeEntry.getValue()); @@ -2306,10 +2304,10 @@ public class DefaultCodegen { } protected void setReservedWordsLowerCase(List words) { - reservedWords = new HashSet(); - for (String word : words) { - reservedWords.add(word.toLowerCase()); - } + reservedWords = new HashSet(); + for (String word : words) { + reservedWords.add(word.toLowerCase()); + } } protected boolean isReservedWord(String word) { @@ -2319,8 +2317,8 @@ public class DefaultCodegen { /** * Get operationId from the operation object, and if it's blank, generate a new one from the given parameters. * - * @param operation the operation object - * @param path the path of the operation + * @param operation the operation object + * @param path the path of the operation * @param httpMethod the HTTP method of the operation * @return the (generated) operationId */ @@ -2361,7 +2359,7 @@ public class DefaultCodegen { */ protected boolean needToImport(String type) { return !defaultIncludes.contains(type) - && !languageSpecificPrimitives.contains(type); + && !languageSpecificPrimitives.contains(type); } @SuppressWarnings("static-method") @@ -2419,11 +2417,11 @@ public class DefaultCodegen { /** * Add operation to group * - * @param tag name of the tag + * @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 + * @param operation Swagger Operation object + * @param co Codegen Operation object + * @param operations map of Codegen operations */ @SuppressWarnings("static-method") public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { @@ -2436,13 +2434,13 @@ public class DefaultCodegen { String uniqueName = co.operationId; int counter = 0; - for (CodegenOperation op : opList) { - if (uniqueName.equals(op.operationId)) { + for(CodegenOperation op : opList) { + if(uniqueName.equals(op.operationId)) { uniqueName = co.operationId + "_" + counter; - counter++; + counter ++; } } - if (!co.operationId.equals(uniqueName)) { + if(!co.operationId.equals(uniqueName)) { LOGGER.warn("generated unique operationId `" + uniqueName + "`"); } co.operationId = uniqueName; @@ -2504,9 +2502,9 @@ public class DefaultCodegen { /** * Generate the next name for the given name, i.e. append "2" to the base name if not ending with a number, * otherwise increase the number by 1. For example: - * status => status2 - * status2 => status3 - * myName100 => myName101 + * status => status2 + * status2 => status3 + * myName100 => myName101 * * @param name The base name * @return The next name for the base name @@ -2534,7 +2532,7 @@ public class DefaultCodegen { } private void addVars(CodegenModel m, Map properties, List required, - Map allProperties, List allRequired) { + Map allProperties, List allRequired) { m.hasRequired = false; if (properties != null && !properties.isEmpty()) { @@ -2542,7 +2540,7 @@ public class DefaultCodegen { m.hasEnums = false; - Set mandatory = required == null ? Collections.emptySet() + Set mandatory = required == null ? Collections. emptySet() : new TreeSet(required); addVars(m, m.vars, properties, mandatory); m.allMandatory = m.mandatory = mandatory; @@ -2553,7 +2551,7 @@ public class DefaultCodegen { } if (allProperties != null) { - Set allMandatory = allRequired == null ? Collections.emptySet() + Set allMandatory = allRequired == null ? Collections. emptySet() : new TreeSet(allRequired); addVars(m, m.allVars, allProperties, allMandatory); m.allMandatory = allMandatory; @@ -2566,7 +2564,7 @@ public class DefaultCodegen { final int totalCount = propertyList.size(); for (int i = 0; i < totalCount; i++) { Map.Entry entry = propertyList.get(i); - + final String key = entry.getKey(); final Property prop = entry.getValue(); @@ -2582,10 +2580,10 @@ public class DefaultCodegen { m.hasEnums = true; } - if (i + 1 != totalCount) { + if (i+1 != totalCount) { cp.hasMore = true; // check the next entry to see if it's read only - if (!Boolean.TRUE.equals(propertyList.get(i + 1).getValue().getReadOnly())) { + if (!Boolean.TRUE.equals(propertyList.get(i+1).getValue().getReadOnly())) { cp.hasMoreNonReadOnly = true; // next entry is not ready only } } @@ -2596,7 +2594,7 @@ public class DefaultCodegen { addImport(m, cp.baseType); CodegenProperty innerCp = cp; - while (innerCp != null) { + while(innerCp != null) { addImport(m, innerCp.complexType); innerCp = innerCp.items; } @@ -2633,7 +2631,7 @@ public class DefaultCodegen { /** * Remove characters that is not good to be included in method name from the input and camelize it * - * @param name string to be camelize + * @param name string to be camelize * @param nonNameElementPattern a regex pattern of the characters that is not good to be included in name * @return camelized string */ @@ -2666,7 +2664,7 @@ public class DefaultCodegen { /** * Camelize name (parameter, property, method, etc) * - * @param word string to be camelize + * @param word string to be camelize * @param lowercaseFirstLetter lower case for first letter if set to true * @return camelized string */ @@ -2728,7 +2726,8 @@ public class DefaultCodegen { * Return the full path and API documentation file * * @param templateName template name - * @param tag tag + * @param tag tag + * * @return the API documentation file name with full path */ public String apiDocFilename(String templateName, String tag) { @@ -2740,7 +2739,8 @@ public class DefaultCodegen { * Return the full path and API test file * * @param templateName template name - * @param tag tag + * @param tag tag + * * @return the API test file name with full path */ public String apiTestFilename(String templateName, String tag) { @@ -2763,7 +2763,6 @@ public class DefaultCodegen { /** * All library templates supported. * (key: library name, value: library description) - * * @return the supported libraries */ public Map supportedLibraries() { @@ -2773,7 +2772,7 @@ public class DefaultCodegen { /** * Set library template (sub-template). * - * @param library Library template + * @param library Library template */ public void setLibrary(String library) { if (library != null && !supportedLibraries.containsKey(library)) @@ -2793,7 +2792,7 @@ public class DefaultCodegen { /** * Set Git user ID. * - * @param gitUserId Git user ID + * @param gitUserId Git user ID */ public void setGitUserId(String gitUserId) { this.gitUserId = gitUserId; @@ -2811,7 +2810,7 @@ public class DefaultCodegen { /** * Set Git repo ID. * - * @param gitRepoId Git repo ID + * @param gitRepoId Git repo ID */ public void setGitRepoId(String gitRepoId) { this.gitRepoId = gitRepoId; @@ -2854,7 +2853,7 @@ public class DefaultCodegen { } /** - * HTTP user agent + * HTTP user agent * * @return HTTP user agent */ @@ -2884,11 +2883,11 @@ public class DefaultCodegen { // encountered so far and hopefully make it easier for others to add more special // cases in the future. - // better error handling when map/array type is invalid - if (name == null) { - LOGGER.error("String to be sanitized is null. Default to ERROR_UNKNOWN"); - return "ERROR_UNKNOWN"; - } + // better error handling when map/array type is invalid + if (name == null) { + LOGGER.error("String to be sanitized is null. Default to ERROR_UNKNOWN"); + return "ERROR_UNKNOWN"; + } // if the name is just '$', map it to 'value' for the time being. if ("$".equals(name)) { @@ -2936,22 +2935,23 @@ public class DefaultCodegen { /** * Only write if the file doesn't exist * - * @param outputFolder Output folder + * @param outputFolder Output folder * @param supportingFile Supporting file */ public void writeOptional(String outputFolder, SupportingFile supportingFile) { String folder = ""; - if (outputFolder != null && !"".equals(outputFolder)) { + if(outputFolder != null && !"".equals(outputFolder)) { folder += outputFolder + File.separator; } folder += supportingFile.folder; - if (!"".equals(folder)) { + if(!"".equals(folder)) { folder += File.separator + supportingFile.destinationFilename; - } else { + } + else { folder = supportingFile.destinationFilename; } - if (!new File(folder).exists()) { + if(!new File(folder).exists()) { supportingFiles.add(supportingFile); } else { LOGGER.info("Skipped overwriting " + supportingFile.destinationFilename + " as the file already exists in " + folder); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java index 50474d84ae2..12784d6e92c 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java @@ -475,7 +475,7 @@ public class JavaModelTest { @DataProvider(name = "modelNames") public static Object[][] primeNumbers() { - return new Object[][]{ + return new Object[][] { {"sample", "Sample"}, {"sample_name", "SampleName"}, {"sample__name", "SampleName"},