Refactor code to make it more readable. (#4224)

This commit is contained in:
Sreenidhi Sreesha 2016-11-22 23:13:15 -08:00 committed by wing328
parent 4c05d5f098
commit 2f80568658
3 changed files with 686 additions and 705 deletions

View File

@ -217,7 +217,6 @@ public class DefaultCodegen {
// for enum model
if (Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) {
Map<String, Object> allowableValues = cm.allowableValues;
List<Object> values = (List<Object>) allowableValues.get("values");
List<Map<String, String>> enumVars = new ArrayList<Map<String, String>>();
String commonPrefix = findCommonPrefixOfVars(values);
@ -259,7 +258,6 @@ public class DefaultCodegen {
public String findCommonPrefixOfVars(List<Object> vars) {
try {
String[] listStr = vars.toArray(new String[vars.size()]);
String prefix = StringUtils.getCommonPrefix(listStr);
// exclude trailing characters that should be part of a valid variable
// e.g. ["status-on", "status-off"] => "status-" (not "status-o")
@ -362,7 +360,13 @@ public class DefaultCodegen {
// replace " with \"
// outter unescape to retain the original multi-byte characters
// finally escalate characters avoiding code injection
return escapeUnsafeCharacters(StringEscapeUtils.unescapeJava(StringEscapeUtils.escapeJava(input).replace("\\/", "/")).replaceAll("[\\t\\n\\r]"," ").replace("\\", "\\\\").replace("\"", "\\\""));
return escapeUnsafeCharacters(
StringEscapeUtils.unescapeJava(
StringEscapeUtils.escapeJava(input)
.replace("\\/", "/"))
.replaceAll("[\\t\\n\\r]"," ")
.replace("\\", "\\\\")
.replace("\"", "\\\""));
}
/**
@ -372,7 +376,8 @@ public class DefaultCodegen {
* @return string with unsafe characters removed or escaped
*/
public String escapeUnsafeCharacters(String input) {
LOGGER.warn("escapeUnsafeCharacters should be overridden in the code generator with proper logic to escape unsafe characters");
LOGGER.warn("escapeUnsafeCharacters should be overridden in the code generator with proper logic to escape " +
"unsafe characters");
// doing nothing by default and code generator should implement
// the logic to prevent code injection
// later we'll make this method abstract to make sure
@ -386,7 +391,8 @@ public class DefaultCodegen {
* @return string with quotation mark removed or escaped
*/
public String escapeQuotationMark(String input) {
LOGGER.warn("escapeQuotationMark should be overridden in the code generator with proper logic to escape single/double quote");
LOGGER.warn("escapeQuotationMark should be overridden in the code generator with proper logic to escape " +
"single/double quote");
return input.replace("\"", "\\\"");
}
@ -1232,7 +1238,6 @@ public class DefaultCodegen {
m.discriminator = ((ModelImpl) model).getDiscriminator();
}
if (model instanceof ArrayModel) {
ArrayModel am = (ArrayModel) model;
ArrayProperty arrayProperty = new ArrayProperty(am.getItems());
@ -1319,7 +1324,7 @@ public class DefaultCodegen {
addVars(m, properties, required, allProperties, allRequired);
} else {
ModelImpl impl = (ModelImpl) model;
if (m != null && impl.getType() != null) {
if (impl.getType() != null) {
Property p = PropertyBuilder.build(impl.getType(), impl.getFormat(), null);
m.dataType = getSwaggerType(p);
}
@ -1350,7 +1355,7 @@ public class DefaultCodegen {
if (model == null || allDefinitions == null)
return false;
Model child = ((ComposedModel) model).getChild();
Model child = model.getChild();
if (child instanceof ModelImpl && ((ModelImpl) child).getDiscriminator() != null) {
return true;
}
@ -1372,7 +1377,9 @@ public class DefaultCodegen {
addParentContainer(codegenModel, codegenModel.name, mapProperty);
}
protected void addProperties(Map<String, Property> properties, List<String> required, Model model, Map<String, Model> allDefinitions) {
protected void addProperties(Map<String, Property> properties,
List<String> required, Model model,
Map<String, Model> allDefinitions) {
if (model instanceof ModelImpl) {
ModelImpl mi = (ModelImpl) model;
@ -1403,9 +1410,7 @@ public class DefaultCodegen {
if (name == null || name.length() == 0) {
return name;
}
return camelize(toVarName(name));
}
/**
@ -1422,7 +1427,6 @@ public class DefaultCodegen {
}
CodegenProperty property = CodegenModelFactory.newInstance(CodegenModelType.PROPERTY);
property.name = toVarName(name);
property.baseName = name;
property.nameInCamelCase = camelize(property.name, false);
@ -1504,7 +1508,6 @@ public class DefaultCodegen {
property.allowableValues = allowableValues;
}*/
}
if (p instanceof IntegerProperty) {
IntegerProperty sp = (IntegerProperty) p;
property.isInteger = true;
@ -1522,7 +1525,6 @@ public class DefaultCodegen {
property.allowableValues = allowableValues;
}
}
if (p instanceof LongProperty) {
LongProperty sp = (LongProperty) p;
property.isLong = true;
@ -1540,11 +1542,9 @@ public class DefaultCodegen {
property.allowableValues = allowableValues;
}
}
if (p instanceof BooleanProperty) {
property.isBoolean = true;
}
if (p instanceof BinaryProperty) {
property.isBinary = true;
}
@ -1554,7 +1554,6 @@ public class DefaultCodegen {
if (p instanceof ByteArrayProperty) {
property.isByteArray = true;
}
// type is number and without format
if (p instanceof DecimalProperty && !(p instanceof DoubleProperty) && !(p instanceof FloatProperty)) {
DecimalProperty sp = (DecimalProperty) p;
@ -1573,7 +1572,6 @@ public class DefaultCodegen {
property.allowableValues = allowableValues;
}*/
}
if (p instanceof DoubleProperty) {
DoubleProperty sp = (DoubleProperty) p;
property.isDouble = true;
@ -1591,7 +1589,6 @@ public class DefaultCodegen {
property.allowableValues = allowableValues;
}
}
if (p instanceof FloatProperty) {
FloatProperty sp = (FloatProperty) p;
property.isFloat = true;
@ -1627,7 +1624,6 @@ public class DefaultCodegen {
property.allowableValues = allowableValues;
}
}
if (p instanceof DateTimeProperty) {
DateTimeProperty sp = (DateTimeProperty) p;
property.isDateTime = true;
@ -1690,25 +1686,26 @@ public class DefaultCodegen {
protected void updatePropertyForArray(CodegenProperty property, CodegenProperty innerProperty) {
if (innerProperty == null) {
LOGGER.warn("skipping invalid array property " + Json.pretty(property));
} else {
if (!languageSpecificPrimitives.contains(innerProperty.baseType)) {
property.complexType = innerProperty.baseType;
} else {
property.isPrimitiveType = true;
}
property.items = innerProperty;
// inner item is Enum
if (isPropertyInnerMostEnum(property)) {
// isEnum is set to true when the type is an enum
// or the inner type of an array/map is an enum
property.isEnum = true;
// update datatypeWithEnum and default value for array
// e.g. List<string> => List<StatusEnum>
updateDataTypeWithEnumForArray(property);
// set allowable values to enum values (including array/map of enum)
property.allowableValues = getInnerEnumAllowableValues(property);
}
return;
}
if (!languageSpecificPrimitives.contains(innerProperty.baseType)) {
property.complexType = innerProperty.baseType;
} else {
property.isPrimitiveType = true;
}
property.items = innerProperty;
// inner item is Enum
if (isPropertyInnerMostEnum(property)) {
// isEnum is set to true when the type is an enum
// or the inner type of an array/map is an enum
property.isEnum = true;
// update datatypeWithEnum and default value for array
// e.g. List<string> => List<StatusEnum>
updateDataTypeWithEnumForArray(property);
// set allowable values to enum values (including array/map of enum)
property.allowableValues = getInnerEnumAllowableValues(property);
}
}
/**
@ -1720,24 +1717,23 @@ public class DefaultCodegen {
if (innerProperty == null) {
LOGGER.warn("skipping invalid map property " + Json.pretty(property));
return;
}
if (!languageSpecificPrimitives.contains(innerProperty.baseType)) {
property.complexType = innerProperty.baseType;
} else {
if (!languageSpecificPrimitives.contains(innerProperty.baseType)) {
property.complexType = innerProperty.baseType;
} else {
property.isPrimitiveType = true;
}
property.items = innerProperty;
// inner item is Enum
if (isPropertyInnerMostEnum(property)) {
// isEnum is set to true when the type is an enum
// or the inner type of an array/map is an enum
property.isEnum = true;
// update datatypeWithEnum and default value for map
// e.g. Dictionary<string, string> => Dictionary<string, StatusEnum>
updateDataTypeWithEnumForMap(property);
// set allowable values to enum values (including array/map of enum)
property.allowableValues = getInnerEnumAllowableValues(property);
}
property.isPrimitiveType = true;
}
property.items = innerProperty;
// inner item is Enum
if (isPropertyInnerMostEnum(property)) {
// isEnum is set to true when the type is an enum
// or the inner type of an array/map is an enum
property.isEnum = true;
// update datatypeWithEnum and default value for map
// e.g. Dictionary<string, string> => Dictionary<string, StatusEnum>
updateDataTypeWithEnumForMap(property);
// set allowable values to enum values (including array/map of enum)
property.allowableValues = getInnerEnumAllowableValues(property);
}
}
@ -1867,7 +1863,11 @@ public class DefaultCodegen {
* @param swagger a Swagger object representing the spec
* @return Codegen Operation object
*/
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Model> definitions, Swagger swagger) {
public CodegenOperation fromOperation(String path,
String httpMethod,
Operation operation,
Map<String, Model> definitions,
Swagger swagger) {
CodegenOperation op = CodegenModelFactory.newInstance(CodegenModelType.OPERATION);
Set<String> imports = new HashSet<String>();
op.vendorExtensions = operation.getVendorExtensions();
@ -1936,7 +1936,7 @@ public class DefaultCodegen {
}
// if "produces" is defined (per operation or using global definition)
if (produces != null && produces.size() > 0) {
if (produces != null && !produces.isEmpty()) {
List<Map<String, String>> c = new ArrayList<Map<String, String>>();
int count = 0;
for (String key : produces) {
@ -2228,7 +2228,7 @@ public class DefaultCodegen {
if (param instanceof SerializableParameter) {
SerializableParameter qp = (SerializableParameter) param;
Property property = null;
Property property;
String collectionFormat = null;
String type = qp.getType();
if (null == type) {
@ -3345,7 +3345,6 @@ public class DefaultCodegen {
if (pattern != null && !pattern.matches("^/.*")) {
return "/" + pattern + "/";
}
return pattern;
}

View File

@ -449,7 +449,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "<String, " + getTypeDeclaration(inner) + ">";
}
return super.getTypeDeclaration(p);
@ -639,7 +638,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel);
codegenModel = AbstractJavaCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel);
}
return codegenModel;
}
@ -667,7 +665,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
model.imports.add("ApiModelProperty");
model.imports.add("ApiModel");
}
return;
}
@Override
@ -712,26 +709,27 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
@Override
public void preprocessSwagger(Swagger swagger) {
if (swagger != null && swagger.getPaths() != null) {
for (String pathname : swagger.getPaths().keySet()) {
Path path = swagger.getPath(pathname);
if (path.getOperations() != null) {
for (Operation operation : path.getOperations()) {
boolean hasFormParameters = false;
for (Parameter parameter : operation.getParameters()) {
if (parameter instanceof FormParameter) {
hasFormParameters = true;
}
}
String defaultContentType = hasFormParameters ? "application/x-www-form-urlencoded" : "application/json";
String contentType = operation.getConsumes() == null || operation.getConsumes().isEmpty()
? defaultContentType : operation.getConsumes().get(0);
String accepts = getAccept(operation);
operation.setVendorExtension("x-contentType", contentType);
operation.setVendorExtension("x-accepts", accepts);
if (swagger == null || swagger.getPaths() == null){
return;
}
for (String pathname : swagger.getPaths().keySet()) {
Path path = swagger.getPath(pathname);
if (path.getOperations() == null){
continue;
}
for (Operation operation : path.getOperations()) {
boolean hasFormParameters = false;
for (Parameter parameter : operation.getParameters()) {
if (parameter instanceof FormParameter) {
hasFormParameters = true;
}
}
String defaultContentType = hasFormParameters ? "application/x-www-form-urlencoded" : "application/json";
String contentType = operation.getConsumes() == null || operation.getConsumes().isEmpty()
? defaultContentType : operation.getConsumes().get(0);
String accepts = getAccept(operation);
operation.setVendorExtension("x-contentType", contentType);
operation.setVendorExtension("x-accepts", accepts);
}
}
}
@ -820,9 +818,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Model> definitions, Swagger swagger) {
CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger);
op.path = sanitizePath(op.path);
return op;
}
@ -834,43 +830,43 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
// Because the child models extend the parents, the enums will be available via the parent.
// Only bother with reconciliation if the parent model has enums.
if (parentCodegenModel.hasEnums) {
if (!parentCodegenModel.hasEnums) {
return codegenModel;
}
// Get the properties for the parent and child models
final List<CodegenProperty> parentModelCodegenProperties = parentCodegenModel.vars;
List<CodegenProperty> codegenProperties = codegenModel.vars;
// Get the properties for the parent and child models
final List<CodegenProperty> parentModelCodegenProperties = parentCodegenModel.vars;
List<CodegenProperty> codegenProperties = codegenModel.vars;
// Iterate over all of the parent model properties
boolean removedChildEnum = false;
for (CodegenProperty parentModelCodegenPropery : parentModelCodegenProperties) {
// Look for enums
if (parentModelCodegenPropery.isEnum) {
// Now that we have found an enum in the parent class,
// and search the child class for the same enum.
Iterator<CodegenProperty> iterator = codegenProperties.iterator();
while (iterator.hasNext()) {
CodegenProperty codegenProperty = iterator.next();
if (codegenProperty.isEnum && codegenProperty.equals(parentModelCodegenPropery)) {
// 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;
}
// Iterate over all of the parent model properties
boolean removedChildEnum = false;
for (CodegenProperty parentModelCodegenPropery : parentModelCodegenProperties) {
// Look for enums
if (parentModelCodegenPropery.isEnum) {
// Now that we have found an enum in the parent class,
// and search the child class for the same enum.
Iterator<CodegenProperty> iterator = codegenProperties.iterator();
while (iterator.hasNext()) {
CodegenProperty codegenProperty = iterator.next();
if (codegenProperty.isEnum && codegenProperty.equals(parentModelCodegenPropery)) {
// 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;
}
}
}
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;
}
}
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;
}