format code, add helper function to check body/form param

This commit is contained in:
wing328 2018-04-01 22:25:22 +08:00
parent 240d1fe7eb
commit b0fc3e94a3
3 changed files with 201 additions and 177 deletions

View File

@ -143,11 +143,11 @@ public class DefaultCodegen implements CodegenConfig {
.get(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS).toString())); .get(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS).toString()));
} }
if(additionalProperties.containsKey(CodegenConstants.MODEL_NAME_PREFIX)){ if (additionalProperties.containsKey(CodegenConstants.MODEL_NAME_PREFIX)) {
this.setModelNamePrefix((String) additionalProperties.get(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)); this.setModelNameSuffix((String) additionalProperties.get(CodegenConstants.MODEL_NAME_SUFFIX));
} }
@ -158,7 +158,7 @@ public class DefaultCodegen implements CodegenConfig {
} }
// override with any special post-processing for all models // override with any special post-processing for all models
@SuppressWarnings({ "static-method", "unchecked" }) @SuppressWarnings({"static-method", "unchecked"})
public Map<String, Object> postProcessAllModels(Map<String, Object> objs) { public Map<String, Object> postProcessAllModels(Map<String, Object> objs) {
if (supportsInheritance) { if (supportsInheritance) {
// Index all CodegenModels by model name. // Index all CodegenModels by model name.
@ -351,12 +351,12 @@ public class DefaultCodegen implements CodegenConfig {
// override to post-process any model properties // override to post-process any model properties
@SuppressWarnings("unused") @SuppressWarnings("unused")
public void postProcessModelProperty(CodegenModel model, CodegenProperty property){ public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
} }
// override to post-process any parameters // override to post-process any parameters
@SuppressWarnings("unused") @SuppressWarnings("unused")
public void postProcessParameter(CodegenParameter parameter){ public void postProcessParameter(CodegenParameter parameter) {
} }
//override with any special handling of the entire swagger spec //override with any special handling of the entire swagger spec
@ -391,7 +391,7 @@ public class DefaultCodegen implements CodegenConfig {
StringEscapeUtils.unescapeJava( StringEscapeUtils.unescapeJava(
StringEscapeUtils.escapeJava(input) StringEscapeUtils.escapeJava(input)
.replace("\\/", "/")) .replace("\\/", "/"))
.replaceAll("[\\t\\n\\r]"," ") .replaceAll("[\\t\\n\\r]", " ")
.replace("\\", "\\\\") .replace("\\", "\\\\")
.replace("\"", "\\\"")); .replace("\"", "\\\""));
} }
@ -399,6 +399,7 @@ public class DefaultCodegen implements CodegenConfig {
/** /**
* override with any special text escaping logic to handle unsafe * override with any special text escaping logic to handle unsafe
* characters so as to avoid code injection * characters so as to avoid code injection
*
* @param input String to be cleaned up * @param input String to be cleaned up
* @return string with unsafe characters removed or escaped * @return string with unsafe characters removed or escaped
*/ */
@ -414,6 +415,7 @@ public class DefaultCodegen implements CodegenConfig {
/** /**
* Escape single and/or double quote to avoid code injection * Escape single and/or double quote to avoid code injection
*
* @param input String to be cleaned up * @param input String to be cleaned up
* @return string with quotation mark removed or escaped * @return string with quotation mark removed or escaped
*/ */
@ -575,11 +577,11 @@ public class DefaultCodegen implements CodegenConfig {
this.modelPackage = modelPackage; this.modelPackage = modelPackage;
} }
public void setModelNamePrefix(String modelNamePrefix){ public void setModelNamePrefix(String modelNamePrefix) {
this.modelNamePrefix = modelNamePrefix; this.modelNamePrefix = modelNamePrefix;
} }
public void setModelNameSuffix(String modelNameSuffix){ public void setModelNameSuffix(String modelNameSuffix) {
this.modelNameSuffix = modelNameSuffix; this.modelNameSuffix = modelNameSuffix;
} }
@ -745,7 +747,7 @@ public class DefaultCodegen implements CodegenConfig {
* *
* @param name the name to be escaped * @param name the name to be escaped
* @return the escaped reserved word * @return the escaped reserved word
* * <p>
* throws Runtime exception as reserved word is not allowed (default behavior) * throws Runtime exception as reserved word is not allowed (default behavior)
*/ */
@SuppressWarnings("static-method") @SuppressWarnings("static-method")
@ -782,8 +784,8 @@ public class DefaultCodegen implements CodegenConfig {
* This method will map between OAS type and language-specified type, as well as mapping * This method will map between OAS type and language-specified type, as well as mapping
* between OAS type and the corresponding import statement for the language. This will * between OAS type and the corresponding import statement for the language. This will
* also add some language specified CLI options, if any. * also add some language specified CLI options, if any.
* * <p>
* * <p>
* returns string presentation of the example path (it's a constructor) * returns string presentation of the example path (it's a constructor)
*/ */
public DefaultCodegen() { public DefaultCodegen() {
@ -963,11 +965,9 @@ public class DefaultCodegen implements CodegenConfig {
paramPart.append("&").append(param.getName()).append("="); paramPart.append("&").append(param.getName()).append("=");
paramPart.append(param.getName()).append("2"); paramPart.append(param.getName()).append("2");
} }
} } else if (Parameter.StyleEnum.PIPEDELIMITED.equals(qp.getStyle())) {
else if (Parameter.StyleEnum.PIPEDELIMITED.equals(qp.getStyle())) {
paramPart.append("|"); paramPart.append("|");
} } else if (Parameter.StyleEnum.SPACEDELIMITED.equals(qp.getStyle())) {
else if (Parameter.StyleEnum.SPACEDELIMITED.equals(qp.getStyle())) {
paramPart.append("%20"); paramPart.append("%20");
} else { } else {
LOGGER.warn("query parameter '" + param.getName() + "style not support: " + qp.getStyle()); LOGGER.warn("query parameter '" + param.getName() + "style not support: " + qp.getStyle());
@ -1094,6 +1094,7 @@ public class DefaultCodegen implements CodegenConfig {
/** /**
* returns the OpenAPI type for the property * returns the OpenAPI type for the property
*
* @param schema property schema * @param schema property schema
* @return string presentation of the type * @return string presentation of the type
**/ **/
@ -1135,7 +1136,7 @@ public class DefaultCodegen implements CodegenConfig {
} else if (schema instanceof NumberSchema) { } else if (schema instanceof NumberSchema) {
if (SchemaTypeUtil.FLOAT_FORMAT.equals(schema.getFormat())) { if (SchemaTypeUtil.FLOAT_FORMAT.equals(schema.getFormat())) {
datatype = SchemaTypeUtil.FLOAT_FORMAT; datatype = SchemaTypeUtil.FLOAT_FORMAT;
} else if(SchemaTypeUtil.DOUBLE_FORMAT.equals(schema.getFormat())) { } else if (SchemaTypeUtil.DOUBLE_FORMAT.equals(schema.getFormat())) {
datatype = SchemaTypeUtil.DOUBLE_FORMAT; datatype = SchemaTypeUtil.DOUBLE_FORMAT;
} else { } else {
datatype = "BigDecimal"; datatype = "BigDecimal";
@ -1148,7 +1149,7 @@ public class DefaultCodegen implements CodegenConfig {
} }
} else if (schema instanceof MapSchema) { } else if (schema instanceof MapSchema) {
datatype = "map"; datatype = "map";
} else if ( schema instanceof UUIDSchema) { } else if (schema instanceof UUIDSchema) {
datatype = "UUID"; datatype = "UUID";
} else if (schema instanceof StringSchema) { } else if (schema instanceof StringSchema) {
datatype = "string"; datatype = "string";
@ -1216,6 +1217,7 @@ public class DefaultCodegen implements CodegenConfig {
* Determine the type alias for the given type if it exists. This feature * Determine the type alias for the given type if it exists. This feature
* is only used for Java, because the language does not have a aliasing * is only used for Java, because the language does not have a aliasing
* mechanism of its own. * mechanism of its own.
*
* @param name The type name. * @param name The type name.
* @return The alias of the given type, if it exists. If there is no alias * @return The alias of the given type, if it exists. If there is no alias
* for this type, then returns the input type name. * for this type, then returns the input type name.
@ -1347,7 +1349,7 @@ public class DefaultCodegen implements CodegenConfig {
allRequired = new ArrayList<String>(); allRequired = new ArrayList<String>();
m.allVars = new ArrayList<CodegenProperty>(); m.allVars = new ArrayList<CodegenProperty>();
int modelImplCnt = 0; // only one inline object allowed in a ComposedModel int modelImplCnt = 0; // only one inline object allowed in a ComposedModel
for (Schema innerModel: composed.getAllOf()) { for (Schema innerModel : composed.getAllOf()) {
if (m.discriminator == null) { if (m.discriminator == null) {
m.discriminator = schema.getDiscriminator(); m.discriminator = schema.getDiscriminator();
} }
@ -1444,7 +1446,7 @@ public class DefaultCodegen implements CodegenConfig {
} }
if (m.vars != null) { if (m.vars != null) {
for(CodegenProperty prop : m.vars) { for (CodegenProperty prop : m.vars) {
postProcessModelProperty(m, prop); postProcessModelProperty(m, prop);
} }
} }
@ -1610,7 +1612,7 @@ public class DefaultCodegen implements CodegenConfig {
if (p.getEnum() != null) { if (p.getEnum() != null) {
List<Integer> _enum = p.getEnum(); List<Integer> _enum = p.getEnum();
property._enum = new ArrayList<String>(); property._enum = new ArrayList<String>();
for(Integer i : _enum) { for (Integer i : _enum) {
property._enum.add(i.toString()); property._enum.add(i.toString());
} }
property.isEnum = true; property.isEnum = true;
@ -1658,7 +1660,7 @@ public class DefaultCodegen implements CodegenConfig {
if (p instanceof UUIDSchema || SchemaTypeUtil.UUID_FORMAT.equals(p.getFormat())) { if (p instanceof UUIDSchema || SchemaTypeUtil.UUID_FORMAT.equals(p.getFormat())) {
// keep isString to true to make it backward compatible // keep isString to true to make it backward compatible
property.isString =true; property.isString = true;
property.isUuid = true; property.isUuid = true;
} }
if (p instanceof ByteArraySchema || SchemaTypeUtil.BYTE_FORMAT.equals(p.getFormat())) { if (p instanceof ByteArraySchema || SchemaTypeUtil.BYTE_FORMAT.equals(p.getFormat())) {
@ -1669,7 +1671,7 @@ public class DefaultCodegen implements CodegenConfig {
property.isNumeric = Boolean.TRUE; property.isNumeric = Boolean.TRUE;
if (SchemaTypeUtil.FLOAT_FORMAT.equals(p.getFormat())) { // float if (SchemaTypeUtil.FLOAT_FORMAT.equals(p.getFormat())) { // float
property.isFloat = Boolean.TRUE; property.isFloat = Boolean.TRUE;
} else if (SchemaTypeUtil.DOUBLE_FORMAT.equals(p.getFormat())){ // double } else if (SchemaTypeUtil.DOUBLE_FORMAT.equals(p.getFormat())) { // double
property.isDouble = Boolean.TRUE; property.isDouble = Boolean.TRUE;
} else { // type is number and without format } else { // type is number and without format
property.isNumber = Boolean.TRUE; property.isNumber = Boolean.TRUE;
@ -1695,7 +1697,7 @@ public class DefaultCodegen implements CodegenConfig {
if (p.getEnum() != null) { if (p.getEnum() != null) {
List<String> _enum = p.getEnum(); List<String> _enum = p.getEnum();
property._enum = new ArrayList<String>(); property._enum = new ArrayList<String>();
for(String i : _enum) { for (String i : _enum) {
property._enum.add(i); property._enum.add(i);
} }
property.isEnum = true; property.isEnum = true;
@ -1712,7 +1714,7 @@ public class DefaultCodegen implements CodegenConfig {
if (p.getEnum() != null) { if (p.getEnum() != null) {
List<String> _enum = p.getEnum(); List<String> _enum = p.getEnum();
property._enum = new ArrayList<String>(); property._enum = new ArrayList<String>();
for(String i : _enum) { for (String i : _enum) {
property._enum.add(i); property._enum.add(i);
} }
property.isEnum = true; property.isEnum = true;
@ -1744,7 +1746,7 @@ public class DefaultCodegen implements CodegenConfig {
property.baseType = getSchemaType(p); property.baseType = getSchemaType(p);
if (p.getXml() != null) { if (p.getXml() != null) {
property.isXmlWrapped = p.getXml().getWrapped() == null ? false : p.getXml().getWrapped(); property.isXmlWrapped = p.getXml().getWrapped() == null ? false : p.getXml().getWrapped();
property.xmlPrefix= p.getXml().getPrefix(); property.xmlPrefix = p.getXml().getPrefix();
property.xmlNamespace = p.getXml().getNamespace(); property.xmlNamespace = p.getXml().getNamespace();
property.xmlName = p.getXml().getName(); property.xmlName = p.getXml().getName();
} }
@ -1788,6 +1790,7 @@ public class DefaultCodegen implements CodegenConfig {
/** /**
* Update property for array(list) container * Update property for array(list) container
*
* @param property Codegen property * @param property Codegen property
* @param innerProperty Codegen inner property of map or list * @param innerProperty Codegen inner property of map or list
*/ */
@ -1819,6 +1822,7 @@ public class DefaultCodegen implements CodegenConfig {
/** /**
* Update property for map container * Update property for map container
*
* @param property Codegen property * @param property Codegen property
* @param innerProperty Codegen inner property of map or list * @param innerProperty Codegen inner property of map or list
*/ */
@ -1850,6 +1854,7 @@ public class DefaultCodegen implements CodegenConfig {
/** /**
* Update property for map container * Update property for map container
*
* @param property Codegen property * @param property Codegen property
* @return True if the inner most type is enum * @return True if the inner most type is enum
*/ */
@ -1876,6 +1881,7 @@ public class DefaultCodegen implements CodegenConfig {
/** /**
* Update datatypeWithEnum for array container * Update datatypeWithEnum for array container
*
* @param property Codegen property * @param property Codegen property
*/ */
protected void updateDataTypeWithEnumForArray(CodegenProperty property) { protected void updateDataTypeWithEnumForArray(CodegenProperty property) {
@ -1903,6 +1909,7 @@ public class DefaultCodegen implements CodegenConfig {
/** /**
* Update datatypeWithEnum for map container * Update datatypeWithEnum for map container
*
* @param property Codegen property * @param property Codegen property
*/ */
protected void updateDataTypeWithEnumForMap(CodegenProperty property) { protected void updateDataTypeWithEnumForMap(CodegenProperty property) {
@ -1938,6 +1945,7 @@ public class DefaultCodegen implements CodegenConfig {
/** /**
* Override with any special handling of response codes * Override with any special handling of response codes
*
* @param responses OAS Operation's responses * @param responses OAS Operation's responses
* @return default method response or <tt>null</tt> if not found * @return default method response or <tt>null</tt> if not found
*/ */
@ -2002,7 +2010,7 @@ public class DefaultCodegen implements CodegenConfig {
if (removeOperationIdPrefix) { if (removeOperationIdPrefix) {
int offset = operationId.indexOf('_'); int offset = operationId.indexOf('_');
if (offset > -1) { if (offset > -1) {
operationId = operationId.substring(offset+1); operationId = operationId.substring(offset + 1);
} }
} }
operationId = removeNonNameElementToCamelCase(operationId); operationId = removeNonNameElementToCamelCase(operationId);
@ -2033,10 +2041,10 @@ public class DefaultCodegen implements CodegenConfig {
} }
r.isDefault = response == methodResponse; r.isDefault = response == methodResponse;
op.responses.add(r); op.responses.add(r);
if (Boolean.TRUE.equals(r.isBinary) && Boolean.TRUE.equals(r.isDefault)){ if (Boolean.TRUE.equals(r.isBinary) && Boolean.TRUE.equals(r.isDefault)) {
op.isResponseBinary = Boolean.TRUE; op.isResponseBinary = Boolean.TRUE;
} }
if (Boolean.TRUE.equals(r.isFile) && Boolean.TRUE.equals(r.isDefault)){ if (Boolean.TRUE.equals(r.isFile) && Boolean.TRUE.equals(r.isDefault)) {
op.isResponseFile = Boolean.TRUE; op.isResponseFile = Boolean.TRUE;
} }
} }
@ -2242,7 +2250,7 @@ public class DefaultCodegen implements CodegenConfig {
} }
public boolean isParameterNameUnique(CodegenParameter p, List<CodegenParameter> parameters) { public boolean isParameterNameUnique(CodegenParameter p, List<CodegenParameter> parameters) {
for (CodegenParameter parameter: parameters) { for (CodegenParameter parameter : parameters) {
if (System.identityHashCode(p) == System.identityHashCode(parameter)) { if (System.identityHashCode(p) == System.identityHashCode(parameter)) {
continue; // skip itself continue; // skip itself
} }
@ -2683,6 +2691,7 @@ public class DefaultCodegen implements CodegenConfig {
/** /**
* Returns the data type of a parameter. * Returns the data type of a parameter.
* Returns null by default to use the CodegenProperty.datatype value * Returns null by default to use the CodegenProperty.datatype value
*
* @param parameter * @param parameter
* @param property * @param property
* @return * @return
@ -2921,12 +2930,12 @@ public class DefaultCodegen implements CodegenConfig {
String uniqueName = co.operationId; String uniqueName = co.operationId;
int counter = 0; int counter = 0;
for (CodegenOperation op : opList) { for (CodegenOperation op : opList) {
if(uniqueName.equals(op.operationId)) { if (uniqueName.equals(op.operationId)) {
uniqueName = co.operationId + "_" + counter; uniqueName = co.operationId + "_" + counter;
counter ++; counter++;
} }
} }
if(!co.operationId.equals(uniqueName)) { if (!co.operationId.equals(uniqueName)) {
LOGGER.warn("generated unique operationId `" + uniqueName + "`"); LOGGER.warn("generated unique operationId `" + uniqueName + "`");
} }
co.operationId = uniqueName; co.operationId = uniqueName;
@ -3031,7 +3040,7 @@ public class DefaultCodegen implements CodegenConfig {
m.hasVars = true; m.hasVars = true;
m.hasEnums = false; m.hasEnums = false;
Set<String> mandatory = required == null ? Collections.<String> emptySet() Set<String> mandatory = required == null ? Collections.<String>emptySet()
: new TreeSet<String>(required); : new TreeSet<String>(required);
addVars(m, m.vars, properties, mandatory); addVars(m, m.vars, properties, mandatory);
m.allMandatory = m.mandatory = mandatory; m.allMandatory = m.mandatory = mandatory;
@ -3042,7 +3051,7 @@ public class DefaultCodegen implements CodegenConfig {
} }
if (allProperties != null) { if (allProperties != null) {
Set<String> allMandatory = allRequired == null ? Collections.<String> emptySet() Set<String> allMandatory = allRequired == null ? Collections.<String>emptySet()
: new TreeSet<String>(allRequired); : new TreeSet<String>(allRequired);
addVars(m, m.allVars, allProperties, allMandatory); addVars(m, m.allVars, allProperties, allMandatory);
m.allMandatory = allMandatory; m.allMandatory = allMandatory;
@ -3077,10 +3086,10 @@ public class DefaultCodegen implements CodegenConfig {
m.hasOnlyReadOnly = false; m.hasOnlyReadOnly = false;
} }
if (i+1 != totalCount) { if (i + 1 != totalCount) {
cp.hasMore = true; cp.hasMore = true;
// check the next entry to see if it's read only // 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 cp.hasMoreNonReadOnly = true; // next entry is not ready only
} }
} }
@ -3091,7 +3100,7 @@ public class DefaultCodegen implements CodegenConfig {
addImport(m, cp.baseType); addImport(m, cp.baseType);
CodegenProperty innerCp = cp; CodegenProperty innerCp = cp;
while(innerCp != null) { while (innerCp != null) {
addImport(m, innerCp.complexType); addImport(m, innerCp.complexType);
innerCp = innerCp.items; innerCp = innerCp.items;
} }
@ -3118,6 +3127,7 @@ public class DefaultCodegen implements CodegenConfig {
/** /**
* Determine all of the types in the model definitions (schemas) that are aliases of * Determine all of the types in the model definitions (schemas) that are aliases of
* simple types. * simple types.
*
* @param schemas The complete set of model definitions (schemas). * @param schemas The complete set of model definitions (schemas).
* @return A mapping from model name to type alias * @return A mapping from model name to type alias
*/ */
@ -3262,7 +3272,6 @@ public class DefaultCodegen implements CodegenConfig {
* *
* @param templateName template name * @param templateName template name
* @param tag tag * @param tag tag
*
* @return the API documentation file name with full path * @return the API documentation file name with full path
*/ */
public String apiDocFilename(String templateName, String tag) { public String apiDocFilename(String templateName, String tag) {
@ -3275,7 +3284,6 @@ public class DefaultCodegen implements CodegenConfig {
* *
* @param templateName template name * @param templateName template name
* @param tag tag * @param tag tag
*
* @return the API test file name with full path * @return the API test file name with full path
*/ */
public String apiTestFilename(String templateName, String tag) { public String apiTestFilename(String templateName, String tag) {
@ -3306,6 +3314,7 @@ public class DefaultCodegen implements CodegenConfig {
/** /**
* All library templates supported. * All library templates supported.
* (key: library name, value: library description) * (key: library name, value: library description)
*
* @return the supported libraries * @return the supported libraries
*/ */
public Map<String, String> supportedLibraries() { public Map<String, String> supportedLibraries() {
@ -3320,7 +3329,7 @@ public class DefaultCodegen implements CodegenConfig {
public void setLibrary(String library) { public void setLibrary(String library) {
if (library != null && !supportedLibraries.containsKey(library)) { if (library != null && !supportedLibraries.containsKey(library)) {
StringBuilder sb = new StringBuilder("Unknown library: " + library + "\nAvailable libraries:"); StringBuilder sb = new StringBuilder("Unknown library: " + library + "\nAvailable libraries:");
if(supportedLibraries.size() == 0) { if (supportedLibraries.size() == 0) {
sb.append("\n ").append("NONE"); sb.append("\n ").append("NONE");
} else { } else {
for (String lib : supportedLibraries.keySet()) { for (String lib : supportedLibraries.keySet()) {
@ -3470,8 +3479,7 @@ public class DefaultCodegen implements CodegenConfig {
// $php_variable => php_variable // $php_variable => php_variable
if (allowUnicodeIdentifiers) { //could be converted to a single line with ?: operator if (allowUnicodeIdentifiers) { //could be converted to a single line with ?: operator
name = Pattern.compile("\\W", Pattern.UNICODE_CHARACTER_CLASS).matcher(name).replaceAll(""); name = Pattern.compile("\\W", Pattern.UNICODE_CHARACTER_CLASS).matcher(name).replaceAll("");
} } else {
else {
name = name.replaceAll("\\W", ""); name = name.replaceAll("\\W", "");
} }
@ -3504,17 +3512,16 @@ public class DefaultCodegen implements CodegenConfig {
public void writeOptional(String outputFolder, SupportingFile supportingFile) { public void writeOptional(String outputFolder, SupportingFile supportingFile) {
String folder = ""; String folder = "";
if(outputFolder != null && !"".equals(outputFolder)) { if (outputFolder != null && !"".equals(outputFolder)) {
folder += outputFolder + File.separator; folder += outputFolder + File.separator;
} }
folder += supportingFile.folder; folder += supportingFile.folder;
if(!"".equals(folder)) { if (!"".equals(folder)) {
folder += File.separator + supportingFile.destinationFilename; folder += File.separator + supportingFile.destinationFilename;
} } else {
else {
folder = supportingFile.destinationFilename; folder = supportingFile.destinationFilename;
} }
if(!new File(folder).exists()) { if (!new File(folder).exists()) {
supportingFiles.add(supportingFile); supportingFiles.add(supportingFile);
} else { } else {
LOGGER.info("Skipped overwriting " + supportingFile.destinationFilename + " as the file already exists in " + folder); LOGGER.info("Skipped overwriting " + supportingFile.destinationFilename + " as the file already exists in " + folder);
@ -3679,7 +3686,7 @@ public class DefaultCodegen implements CodegenConfig {
/** /**
* Provides an override location, if any is specified, for the .swagger-codegen-ignore. * Provides an override location, if any is specified, for the .swagger-codegen-ignore.
* * <p>
* This is originally intended for the first generation only. * This is originally intended for the first generation only.
* *
* @return a string of the full path to an override ignore file. * @return a string of the full path to an override ignore file.
@ -3748,7 +3755,7 @@ public class DefaultCodegen implements CodegenConfig {
if (flow.getScopes() != null && !flow.getScopes().isEmpty()) { if (flow.getScopes() != null && !flow.getScopes().isEmpty()) {
List<Map<String, Object>> scopes = new ArrayList<Map<String, Object>>(); List<Map<String, Object>> scopes = new ArrayList<Map<String, Object>>();
int count = 0, numScopes = flow.getScopes().size(); int count = 0, numScopes = flow.getScopes().size();
for(Map.Entry<String, String> scopeEntry : flow.getScopes().entrySet()) { for (Map.Entry<String, String> scopeEntry : flow.getScopes().entrySet()) {
Map<String, Object> scope = new HashMap<String, Object>(); Map<String, Object> scope = new HashMap<String, Object>();
scope.put("scope", scopeEntry.getKey()); scope.put("scope", scopeEntry.getKey());
scope.put("description", escapeText(scopeEntry.getValue())); scope.put("description", escapeText(scopeEntry.getValue()));
@ -3770,9 +3777,9 @@ public class DefaultCodegen implements CodegenConfig {
List<Schema> interfaces; List<Schema> interfaces;
if (composed.getAllOf() != null && !composed.getAllOf().isEmpty()) { if (composed.getAllOf() != null && !composed.getAllOf().isEmpty()) {
return composed.getAllOf(); return composed.getAllOf();
} else if(composed.getAnyOf() != null && !composed.getAnyOf().isEmpty()) { } else if (composed.getAnyOf() != null && !composed.getAnyOf().isEmpty()) {
return composed.getAnyOf(); return composed.getAnyOf();
} else if(composed.getOneOf() != null && !composed.getOneOf().isEmpty()) { } else if (composed.getOneOf() != null && !composed.getOneOf().isEmpty()) {
return composed.getOneOf(); return composed.getOneOf();
} else { } else {
return null; return null;
@ -3809,12 +3816,50 @@ public class DefaultCodegen implements CodegenConfig {
} }
public static Set<String> getConsumesInfo(Operation operation) { public static Set<String> getConsumesInfo(Operation operation) {
if(operation.getRequestBody() == null || operation.getRequestBody().getContent() == null || operation.getRequestBody().getContent().isEmpty()) { if (operation.getRequestBody() == null || operation.getRequestBody().getContent() == null || operation.getRequestBody().getContent().isEmpty()) {
return null; return null;
} }
return operation.getRequestBody().getContent().keySet(); return operation.getRequestBody().getContent().keySet();
} }
public Boolean hasFormParameter(Operation operation) {
if (getConsumesInfo(operation) == null) {
return Boolean.FALSE;
}
List<String> consumes = new ArrayList<String>(getConsumesInfo(operation));
if (consumes == null) {
return Boolean.FALSE;
}
for (String consume : consumes) {
if ("application/x-www-form-urlencoded".equalsIgnoreCase(consume) || "multipart/form-data".equalsIgnoreCase(consume)) {
return Boolean.TRUE;
}
}
return Boolean.FALSE;
}
public Boolean hasBodyParameter(Operation operation) {
RequestBody requestBody = operation.getRequestBody();
if (requestBody == null) {
return Boolean.FALSE;
}
Schema schema = getSchemaFromBody(requestBody);
if (schema == null) {
return Boolean.FALSE;
}
if (!StringUtils.isEmpty(schema.get$ref())) {
return Boolean.TRUE;
} else {
return Boolean.FALSE;
}
}
private void addProducesInfo(ApiResponse response, CodegenOperation codegenOperation) { private void addProducesInfo(ApiResponse response, CodegenOperation codegenOperation) {
if (response == null || response.getContent() == null || response.getContent().isEmpty()) { if (response == null || response.getContent() == null || response.getContent().isEmpty()) {
return; return;
@ -3848,7 +3893,7 @@ public class DefaultCodegen implements CodegenConfig {
} }
public static Set<String> getProducesInfo(Operation operation) { public static Set<String> getProducesInfo(Operation operation) {
if(operation.getResponses() == null || operation.getResponses().isEmpty()) { if (operation.getResponses() == null || operation.getResponses().isEmpty()) {
return null; return null;
} }
return operation.getResponses().keySet(); return operation.getResponses().keySet();
@ -3896,14 +3941,11 @@ public class DefaultCodegen implements CodegenConfig {
} else { } else {
return "multi"; return "multi";
} }
} } else if (Parameter.StyleEnum.PIPEDELIMITED.equals(parameter.getStyle())) {
else if (Parameter.StyleEnum.PIPEDELIMITED.equals(parameter.getStyle())) {
return "pipe"; return "pipe";
} } else if (Parameter.StyleEnum.SPACEDELIMITED.equals(parameter.getStyle())) {
else if (Parameter.StyleEnum.SPACEDELIMITED.equals(parameter.getStyle())) {
return "space"; return "space";
} } else {
else {
return null; return null;
} }
} }
@ -4087,8 +4129,8 @@ public class DefaultCodegen implements CodegenConfig {
} }
imports.add(codegenProperty.baseType); imports.add(codegenProperty.baseType);
CodegenProperty innerCp = codegenProperty; CodegenProperty innerCp = codegenProperty;
while(innerCp != null) { while (innerCp != null) {
if(innerCp.complexType != null) { if (innerCp.complexType != null) {
imports.add(innerCp.complexType); imports.add(innerCp.complexType);
} }
innerCp = innerCp.items; innerCp = innerCp.items;
@ -4119,7 +4161,7 @@ public class DefaultCodegen implements CodegenConfig {
return codegenParameter; return codegenParameter;
} }
private boolean isObjectSchema (Schema schema) { private boolean isObjectSchema(Schema schema) {
if (schema instanceof ObjectSchema) { if (schema instanceof ObjectSchema) {
return true; return true;
} }

View File

@ -2,12 +2,14 @@ package org.openapitools.codegen.languages;
import java.io.File; import java.io.File;
import java.util.Arrays; import java.util.Arrays;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.ListIterator; import java.util.ListIterator;
import java.util.Map; import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import io.swagger.v3.oas.models.PathItem; import io.swagger.v3.oas.models.PathItem;
@ -599,18 +601,16 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
ArraySchema ap = (ArraySchema) p; ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems(); Schema inner = ap.getItems();
if (inner == null) { if (inner == null) {
LOGGER.warn(ap.getName() + "(array property) does not have a proper inner type defined"); LOGGER.warn(ap.getName() + "(array property) does not have a proper inner type defined.Default to string");
// TODO maybe better defaulting to StringSchema than returning null inner = new StringSchema().description("TODO default missing array inner type to string");
return null;
} }
return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">"; return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (isMapSchema(p)) { } else if (isMapSchema(p)) {
MapSchema mp = (MapSchema) p; MapSchema mp = (MapSchema) p;
Schema inner = (Schema) mp.getAdditionalProperties(); Schema inner = (Schema) mp.getAdditionalProperties();
if (inner == null) { if (inner == null) {
LOGGER.warn(mp.getName() + "(map property) does not have a proper inner type defined"); LOGGER.warn(mp.getName() + "(map property) does not have a proper inner type defined. Default to string");
// TODO maybe better defaulting to StringSchema than returning null inner = new StringSchema().description("TODO default missing array inner type to string");
return null;
} }
return getSchemaType(p) + "<String, " + getTypeDeclaration(inner) + ">"; return getSchemaType(p) + "<String, " + getTypeDeclaration(inner) + ">";
} }
@ -917,26 +917,15 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
continue; continue;
} }
for (Operation operation : path.readOperations()) { for (Operation operation : path.readOperations()) {
// TODO revise the logic below if (hasBodyParameter(operation) || hasFormParameter(operation)){
/* String defaultContentType = hasFormParameter(operation) ? "application/x-www-form-urlencoded" : "application/json";
boolean hasFormParameters = false; List<String> consumes = new ArrayList<String>(getConsumesInfo(operation));
boolean hasBodyParameters = false; String contentType = consumes == null || consumes.isEmpty() ? defaultContentType : consumes.get(0);
for (Parameter parameter : operation.getParameters()) { operation.getExtensions().put("x-contentType", contentType);
if (parameter instanceof FormParameter) {
hasFormParameters = true;
}
if (parameter instanceof BodyParameter) {
hasBodyParameters = true;
}
}
if (hasBodyParameters || hasFormParameters){
String defaultContentType = hasFormParameters ? "application/x-www-form-urlencoded" : "application/json";
String contentType = operation.getConsumes() == null || operation.getConsumes().isEmpty() ? defaultContentType : operation.getConsumes().get(0);
operation.setExtensions("x-contentType", contentType);
} }
String accepts = getAccept(operation); String accepts = getAccept(operation);
operation.setExtension("x-accepts", accepts); operation.getExtensions().put("x-accepts", accepts);
*/
} }
} }
} }
@ -944,18 +933,18 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
private static String getAccept(Operation operation) { private static String getAccept(Operation operation) {
String accepts = null; String accepts = null;
String defaultContentType = "application/json"; String defaultContentType = "application/json";
/* TODO need to revise the logic below ArrayList<String> produces = new ArrayList<String>(getProducesInfo(operation));
if (operation.getProduces() != null && !operation.getProduces().isEmpty()) { if (produces != null && !produces.isEmpty()) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (String produces : operation.getProduces()) { for (String produce : produces) {
if (defaultContentType.equalsIgnoreCase(produces)) { if (defaultContentType.equalsIgnoreCase(produce)) {
accepts = defaultContentType; accepts = defaultContentType;
break; break;
} else { } else {
if (sb.length() > 0) { if (sb.length() > 0) {
sb.append(","); sb.append(",");
} }
sb.append(produces); sb.append(produce);
} }
} }
if (accepts == null) { if (accepts == null) {
@ -964,7 +953,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
} else { } else {
accepts = defaultContentType; accepts = defaultContentType;
} }
*/
return accepts; return accepts;
} }

View File

@ -277,18 +277,12 @@ public class ApexClientCodegen extends AbstractJavaCodegen {
Map<String, Schema> definitions, Map<String, Schema> definitions,
OpenAPI openAPI) { OpenAPI openAPI) {
Boolean hasFormParams = false; Boolean hasFormParams = false;
// need to revise the logic below as there's no form parameters // comment out the following as there's no consume/produce in OAS3.0
// we can move the logic below to postProcessOperations if needed
/* /*
for (Parameter p : operation.getParameters()) {
if ("formData".equals(p.getIn())) {
hasFormParams = true;
break;
}
}
// only support serialization into JSON and urlencoded forms for now // only support serialization into JSON and urlencoded forms for now
operation.setConsumes( operation.setConsumes(
Collections.singletonList(hasFormParams Collections.singletonList(hasFormParameter(operation)
? "application/x-www-form-urlencoded" ? "application/x-www-form-urlencoded"
: "application/json")); : "application/json"));