fix issues with body parameters

This commit is contained in:
wing328
2018-03-19 16:46:45 +08:00
parent 6b65b02c56
commit f2489b256a
3 changed files with 148 additions and 51 deletions
@@ -810,6 +810,7 @@ public class DefaultCodegen {
typeMapping.put("binary", "byte[]");
typeMapping.put("file", "File");
typeMapping.put("UUID", "UUID");
typeMapping.put("BigDecimal", "BigDecimal"); //TODO need the mapping?
instantiationTypes = new HashMap<String, String>();
@@ -2072,6 +2073,12 @@ public class DefaultCodegen {
List<CodegenParameter> formParams = new ArrayList<CodegenParameter>();
List<CodegenParameter> requiredParams = new ArrayList<CodegenParameter>();
if (operation.getRequestBody() != null) {
bodyParam = fromRequestBody(operation.getRequestBody(), schemas, imports);
bodyParams.add(bodyParam);
allParams.add(bodyParam);
}
if (parameters != null) {
for (Parameter param : parameters) {
CodegenParameter p = fromParameter(param, imports);
@@ -2356,8 +2363,6 @@ public class DefaultCodegen {
codegenProperty = codegenProperty.items;
}
} else {
LOGGER.warn("Unknown case for parameter \"" + parameter.getName() + "\"");
}
if (parameterSchema == null) {
@@ -2374,7 +2379,7 @@ public class DefaultCodegen {
codegenParameter.dataType = codegenProperty.datatype;
codegenParameter.dataFormat = codegenProperty.dataFormat;
if(codegenProperty.isEnum) {
if (codegenProperty.isEnum) {
codegenParameter.datatypeWithEnum = codegenProperty.datatypeWithEnum;
codegenParameter.enumName = codegenProperty.enumName;
}
@@ -3611,6 +3616,19 @@ public class DefaultCodegen {
additionalProperties.put(propertyKey, value);
}
protected String getContentType(RequestBody requestBody) {
if (requestBody == null || requestBody.getContent() == null || requestBody.getContent().isEmpty()) {
return null;
}
return new ArrayList<>(requestBody.getContent().keySet()).get(0);
}
protected Schema getSchemaFromBody(RequestBody requestBody) {
String contentType = new ArrayList<>(requestBody.getContent().keySet()).get(0);
MediaType mediaType = requestBody.getContent().get(contentType);
return mediaType.getSchema();
}
private Schema getSchemaFromResponse(ApiResponse response) {
if (response.getContent() == null || response.getContent().isEmpty()) {
return null;
@@ -3623,6 +3641,12 @@ public class DefaultCodegen {
return schema;
}
protected Parameter getParameterFromRef(String ref, OpenAPI openAPI) {
String parameterName = ref.substring(ref.lastIndexOf('/') + 1);
Map<String, Parameter> parameterMap = openAPI.getComponents().getParameters();
return parameterMap.get(parameterName);
}
private void setOauth2Info(CodegenSecurity codegenSecurity, OAuthFlow flow) {
codegenSecurity.authorizationUrl = flow.getAuthorizationUrl();
codegenSecurity.tokenUrl = flow.getTokenUrl();
@@ -3778,4 +3802,81 @@ public class DefaultCodegen {
return null;
}
public CodegenParameter fromRequestBody(RequestBody body, Map<String, Schema> schemas, Set<String> imports) {
CodegenParameter codegenParameter = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER);
codegenParameter.baseName = "UNKNOWN_BASE_NAME";
codegenParameter.paramName = "UNKNOWN_PARAM_NAME";
codegenParameter.required = body.getRequired() != null ? body.getRequired() : Boolean.FALSE;
codegenParameter.isBodyParam = Boolean.TRUE;
String name = null;
Schema schema = getSchemaFromBody(body);
if (StringUtils.isNotBlank(schema.get$ref())) {
name = getSimpleRef(schema.get$ref());
schema = schemas.get(name);
}
if ((SchemaTypeUtil.OBJECT_TYPE.equals(schema.getType())
|| (schema.getType() == null && schema.getProperties() != null && !schema.getProperties().isEmpty()))
&& !(schema instanceof MapSchema)) {
CodegenModel codegenModel = null;
if (StringUtils.isNotBlank(name)) {
schema.setName(name);
codegenModel = fromModel(name, schema, schemas);
}
if (codegenModel != null && !codegenModel.emptyVars) {
codegenParameter.paramName = codegenModel.classname.toLowerCase();
codegenParameter.dataType = getTypeDeclaration(codegenModel.classname);
imports.add(codegenParameter.dataType);
} else {
CodegenProperty codegenProperty = fromProperty("property", schema);
if (codegenProperty != null) {
codegenParameter.baseType = codegenProperty.baseType;
codegenParameter.dataType = codegenProperty.datatype;
codegenParameter.isPrimitiveType = codegenProperty.isPrimitiveType;
codegenParameter.isBinary = codegenProperty.isBinary;
codegenParameter.isFile = codegenProperty.isFile;
if (codegenProperty.complexType != null) {
imports.add(codegenProperty.complexType);
}
}
setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty);
}
}
else if (schema instanceof ArraySchema) {
final ArraySchema arraySchema = (ArraySchema) schema;
Schema inner = arraySchema.getItems();
if (inner == null) {
inner = new StringSchema().description("//TODO automatically added by swagger-codegen");
arraySchema.setItems(inner);
}
CodegenProperty codegenProperty = fromProperty("inner", inner);
if (codegenProperty.complexType != null) {
imports.add(codegenProperty.complexType);
}
imports.add(codegenProperty.baseType);
CodegenProperty innerCp = codegenProperty;
while(innerCp != null) {
if(innerCp.complexType != null) {
imports.add(innerCp.complexType);
}
innerCp = innerCp.items;
}
codegenParameter.items = codegenProperty;
codegenParameter.dataType = codegenProperty.datatype;
codegenParameter.baseType = codegenProperty.complexType;
codegenParameter.isPrimitiveType = codegenProperty.isPrimitiveType;
codegenParameter.isContainer = codegenProperty.isContainer;
codegenParameter.isListContainer = codegenProperty.isListContainer;
setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty);
while (codegenProperty != null) {
imports.add(codegenProperty.baseType);
codegenProperty = codegenProperty.items;
}
}
return codegenParameter;
}
}
@@ -13,6 +13,8 @@ import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.security.OAuthFlow;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.servers.Server;
import io.swagger.v3.oas.models.tags.Tag;
@@ -164,10 +166,6 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
config.vendorExtensions().putAll(openAPI.getExtensions());
}
if (openAPI.getExtensions() != null) {
config.vendorExtensions().putAll(openAPI.getExtensions());
}
URL url = URLPathUtil.getServerURL(openAPI);
contextPath = config.escapeText(url == null ? "" : url.getPath());
basePath = config.escapeText(URLPathUtil.getHost(openAPI));
@@ -707,7 +705,9 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
bundle.put("models", allModels);
bundle.put("apiFolder", config.apiPackage().replace('.', File.separatorChar));
bundle.put("modelPackage", config.modelPackage());
List<CodegenSecurity> authMethods = config.fromSecurity(openAPI.getComponents().getSecuritySchemes());
Map<String, SecurityScheme> securitySchemeMap = openAPI.getComponents() != null ? openAPI.getComponents().getSecuritySchemes() : null;
List<CodegenSecurity> authMethods = config.fromSecurity(securitySchemeMap);
if (authMethods != null && !authMethods.isEmpty()) {
bundle.put("authMethods", authMethods);
bundle.put("hasAuthMethods", true);
@@ -749,7 +749,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
/* TODO revise inline model logic
// resolve inline models
InlineModelResolver inlineModelResolver = new InlineModelResolver();
inlineModelResolver.flatten(swagger);
inlineModelResolver.flatten(openAPI);
*/
List<File> files = new ArrayList<File>();
@@ -869,60 +869,36 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
}
}
final Map<String, Schema> schemas = openAPI.getComponents() != null ? openAPI.getComponents().getSchemas() : null;
final Map<String, SecurityScheme> securitySchemes = openAPI.getComponents() != null ? openAPI.getComponents().getSecuritySchemes() : null;
final List<SecurityRequirement> globalSecurities = openAPI.getSecurity();
for (Tag tag : tags) {
try {
CodegenOperation codegenOperation = config.fromOperation(resourcePath, httpMethod, operation, openAPI.getComponents().getSchemas(), openAPI);
codegenOperation.tags = new ArrayList<Tag>(tags);
CodegenOperation codegenOperation = config.fromOperation(resourcePath, httpMethod, operation, schemas, openAPI);
codegenOperation.tags = new ArrayList<>(tags);
config.addOperationToGroup(config.sanitizeTag(tag.getName()), resourcePath, operation, codegenOperation, operations);
/* TODO revise security setting
List<Map<String, List<String>>> securities = operation.getSecurity();
if (securities == null && swagger.getSecurity() != null) {
securities = new ArrayList<Map<String, List<String>>>();
for (SecurityRequirement sr : swagger.getSecurity()) {
securities.add(sr.getRequirements());
}
}
if (securities == null || swagger.getSecurityDefinitions() == null) {
List<SecurityRequirement> securities = operation.getSecurity();
if (securities != null && securities.isEmpty()) {
continue;
}
Map<String, SecuritySchemeDefinition> authMethods = new HashMap<String, SecuritySchemeDefinition>();
for (Map<String, List<String>> security : securities) {
for (String securityName : security.keySet()) {
SecuritySchemeDefinition securityDefinition = swagger.getSecurityDefinitions().get(securityName);
if (securityDefinition == null) {
continue;
}
if (securityDefinition instanceof OAuth2Definition) {
OAuth2Definition oauth2Definition = (OAuth2Definition) securityDefinition;
OAuth2Definition oauth2Operation = new OAuth2Definition();
oauth2Operation.setType(oauth2Definition.getType());
oauth2Operation.setAuthorizationUrl(oauth2Definition.getAuthorizationUrl());
oauth2Operation.setFlow(oauth2Definition.getFlow());
oauth2Operation.setTokenUrl(oauth2Definition.getTokenUrl());
oauth2Operation.setScopes(new HashMap<String, String>());
for (String scope : security.get(securityName)) {
if (oauth2Definition.getScopes().containsKey(scope)) {
oauth2Operation.addScope(scope, oauth2Definition.getScopes().get(scope));
}
}
authMethods.put(securityName, oauth2Operation);
} else {
authMethods.put(securityName, securityDefinition);
}
}
Map<String, SecurityScheme> authMethods = getAuthMethods(securities, securitySchemes);
if (authMethods == null || authMethods.isEmpty()) {
authMethods = getAuthMethods(globalSecurities, securitySchemes);
}
if (!authMethods.isEmpty()) {
if (authMethods != null && !authMethods.isEmpty()) {
codegenOperation.authMethods = config.fromSecurity(authMethods);
codegenOperation.hasAuthMethods = true;
}*/
}
/* TODO need to revise the logic below
Map<String, SecurityScheme> securitySchemeMap = openAPI.getComponents().getSecuritySchemes();
if (securitySchemeMap != null && !securitySchemeMap.isEmpty()) {
codegenOperation.authMethods = config.fromSecurity(securitySchemeMap);
codegenOperation.hasAuthMethods = true;
}
*/
} catch (Exception ex) {
String msg = "Could not process operation:\n" //
+ " Tag: " + tag + "\n"//
@@ -963,7 +939,6 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
operations.put("operations", objs);
operations.put("package", config.apiPackage());
Set<String> allImports = new TreeSet<String>();
for (CodegenOperation op : ops) {
allImports.addAll(op.imports);
@@ -1047,4 +1022,20 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
config.postProcessModels(objs);
return objs;
}
private Map<String, SecurityScheme> getAuthMethods(List<SecurityRequirement> securities, Map<String, SecurityScheme> securitySchemes) {
if (securities == null || (securitySchemes == null || securitySchemes.isEmpty())) {
return null;
}
final Map<String, SecurityScheme> authMethods = new HashMap<>();
for (SecurityRequirement requirement : securities) {
for (String key : requirement.keySet()) {
SecurityScheme securityScheme = securitySchemes.get(key);
if (securityScheme != null) {
authMethods.put(key, securityScheme);
}
}
}
return authMethods;
}
}
@@ -13,7 +13,7 @@ import java.util.List;
public class URLPathUtil {
protected static final Logger LOGGER = LoggerFactory.getLogger(URLPathUtil.class);
public static String DEFAULT_PATH = "/";
public static final String LOCAL_HOST = "http://localhost";
public static URL getServerURL(OpenAPI openAPI) {
@@ -21,7 +21,12 @@ public class URLPathUtil {
if (servers == null || servers.isEmpty()) {
return null;
}
// TOOD need a way to obtain all server URLs
final Server server = servers.get(0);
String url = server.getUrl();
if (url.equals(DEFAULT_PATH)) {
url = LOCAL_HOST;
}
try {
return new URL(server.getUrl());
} catch (MalformedURLException e) {