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

@ -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
*/ */
@ -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
**/ **/
@ -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.
@ -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
*/ */
@ -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
@ -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() {
@ -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", "");
} }
@ -3510,8 +3518,7 @@ public class DefaultCodegen implements CodegenConfig {
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()) {
@ -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.
@ -3815,6 +3822,44 @@ public class DefaultCodegen implements CodegenConfig {
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;
@ -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;
} }
} }

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"));