Skip to content

Commit

Permalink
Merge pull request swagger-api#580 from swagger-api/model_named_file
Browse files Browse the repository at this point in the history
allow models named file and other utils default java classes.
  • Loading branch information
HugoMario authored Jan 13, 2020
2 parents 7d94b9b + 0c1fd25 commit 8e0d919
Show file tree
Hide file tree
Showing 10 changed files with 336 additions and 43 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ public abstract class DefaultCodegenConfig implements CodegenConfig {
protected String ignoreFilePathOverride;
protected boolean useOas2 = false;
protected boolean copyFistAllOfProperties = false;
protected boolean ignoreImportMapping;

public List<CliOption> cliOptions() {
return cliOptions;
Expand All @@ -181,6 +182,12 @@ public void processOpts() {
this.setTemplateDir((String) additionalProperties.get(CodegenConstants.TEMPLATE_DIR));
}

if (additionalProperties.get(CodegenConstants.IGNORE_IMPORT_MAPPING_OPTION) != null) {
setIgnoreImportMapping(Boolean.parseBoolean( additionalProperties.get(CodegenConstants.IGNORE_IMPORT_MAPPING_OPTION).toString()));
} else {
setIgnoreImportMapping(defaultIgnoreImportMappingOption());
}

if (additionalProperties.containsKey(CodegenConstants.TEMPLATE_VERSION)) {
this.setTemplateVersion((String) additionalProperties.get(CodegenConstants.TEMPLATE_VERSION));
}
Expand Down Expand Up @@ -1717,6 +1724,9 @@ public CodegenProperty fromProperty(String name, Schema propertySchema) {
CodegenProperty cp = fromProperty("inner", new ObjectSchema());
updatePropertyForMap(codegenProperty, cp);
} else {
if (isObjectSchema(propertySchema)) {
codegenProperty.getVendorExtensions().put("x-is-object", Boolean.TRUE);
}
setNonArrayMapProperty(codegenProperty, type);
}
return codegenProperty;
Expand Down Expand Up @@ -3147,6 +3157,29 @@ private void addVars(CodegenModel codegenModel, List<CodegenProperty> vars, Map<
codegenModel.readWriteVars.add(codegenProperty);
}
}
// check if one of the property is a object and has import mapping.
List<CodegenProperty> modelProperties = vars.stream()
.filter(codegenProperty -> getBooleanValue(codegenProperty, "x-is-object") && importMapping.containsKey(codegenProperty.baseType))
.collect(Collectors.toList());
if (modelProperties == null || modelProperties.isEmpty()) {
return;
}

for (CodegenProperty modelProperty : modelProperties) {
List<CodegenProperty> codegenProperties = vars.stream()
.filter(codegenProperty -> !getBooleanValue(codegenProperty, "x-is-object")
&& importMapping.containsKey(codegenProperty.baseType)
&& codegenProperty.baseType.equals(modelProperty.baseType))
.collect(Collectors.toList());
if (codegenProperties == null || codegenProperties.isEmpty()) {
continue;
}
for (CodegenProperty codegenProperty : codegenProperties) {
codegenModel.imports.remove(codegenProperty.baseType);
codegenProperty.datatype = importMapping.get(codegenProperty.baseType);
codegenProperty.datatypeWithEnum = codegenProperty.datatype;
}
}
}

/**
Expand Down Expand Up @@ -4146,7 +4179,10 @@ else if (Parameter.StyleEnum.SPACEDELIMITED.equals(parameter.getStyle())) {
}

public boolean isObjectSchema (Schema schema) {
if (schema instanceof ObjectSchema ||schema instanceof ComposedSchema) {
if (schema == null) {
return false;
}
if (schema instanceof ObjectSchema || schema instanceof ComposedSchema) {
return true;
}
if (SchemaTypeUtil.OBJECT_TYPE.equalsIgnoreCase(schema.getType()) && !(schema instanceof MapSchema)) {
Expand Down Expand Up @@ -4241,7 +4277,15 @@ public void setUnflattenedOpenAPI(OpenAPI unflattenedOpenAPI) {
this.unflattenedOpenAPI = unflattenedOpenAPI;
}

public boolean ignoreImportMapping() {
public boolean getIgnoreImportMapping() {
return ignoreImportMapping;
}

public void setIgnoreImportMapping(boolean ignoreImportMapping) {
this.ignoreImportMapping = ignoreImportMapping;
}

public boolean defaultIgnoreImportMappingOption() {
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -600,10 +600,10 @@ public String toParamName(String name) {
public String toModelName(final String name) {
// We need to check if import-mapping has a different model for this class, so we use it
// instead of the auto-generated one.
if (importMapping.containsKey(name)) {

if (!getIgnoreImportMapping() && importMapping.containsKey(name)) {
return importMapping.get(name);
}

final String sanitizedName = sanitizeName(name);

String nameWithPrefixSuffix = sanitizedName;
Expand Down Expand Up @@ -1449,4 +1449,9 @@ public void setLanguageArguments(List<CodegenArgument> languageArguments) {

super.setLanguageArguments(languageArguments);
}

@Override
public boolean defaultIgnoreImportMappingOption() {
return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package io.swagger.codegen.v3.generators;

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.parser.OpenAPIV3Parser;
import io.swagger.v3.parser.core.models.ParseOptions;
import io.swagger.v3.parser.core.models.SwaggerParseResult;

public abstract class AbstractCodegenTest {

protected OpenAPI getOpenAPI(String filePath) {
OpenAPIV3Parser openApiParser = new OpenAPIV3Parser();
ParseOptions options = new ParseOptions();
options.setResolve(true);
options.setFlatten(true);
SwaggerParseResult parseResult = openApiParser.readLocation(filePath, null, options);

return parseResult.getOpenAPI();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,38 +2,26 @@

import io.swagger.codegen.v3.CodegenOperation;
import io.swagger.codegen.v3.CodegenResponse;
import io.swagger.codegen.v3.generators.AbstractCodegenTest;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Content;
import io.swagger.v3.oas.models.media.MediaType;
import io.swagger.v3.oas.models.media.ObjectSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.responses.ApiResponse;
import io.swagger.v3.oas.models.responses.ApiResponses;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class JavaCXFClientCodegenTest {
public class JavaCXFClientCodegenTest extends AbstractCodegenTest {

@Test
public void responseWithoutContent() throws Exception {
final Schema listOfPets = new ArraySchema()
.items(new Schema<>().$ref("#/components/schemas/Pet"));
Operation operation = new Operation().responses(new ApiResponses()
.addApiResponse("200", new ApiResponse()
.description("Return a list of pets")
.content(new Content().addMediaType("application/json",
new MediaType().schema(listOfPets))))
.addApiResponse("400", new ApiResponse()
.description("Error")));
final Map<String, Schema> allDefinitions = Collections.singletonMap("Pet", new ObjectSchema());
final OpenAPI openAPI = getOpenAPI("3_0_0/response_without_content.yaml");
final Operation operation = openAPI.getPaths().get("/pets").getGet();

final JavaCXFClientCodegen codegen = new JavaCXFClientCodegen();
final CodegenOperation co = codegen.fromOperation("getAllPets", "GET", operation, allDefinitions);
codegen.preprocessOpenAPI(openAPI);
final CodegenOperation co = codegen.fromOperation("getAllPets", "GET", operation, openAPI.getComponents().getSchemas(), openAPI);

Map<String, Object> objs = new HashMap<>();
objs.put("operations", Collections.singletonMap("operation", Collections.singletonList(co)));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
package io.swagger.codegen.v3.generators.java;

import io.swagger.codegen.v3.CodegenConfig;
import io.swagger.codegen.v3.CodegenConstants;
import io.swagger.codegen.v3.CodegenModel;
import io.swagger.codegen.v3.CodegenModelFactory;
import io.swagger.codegen.v3.CodegenModelType;
import io.swagger.codegen.v3.CodegenParameter;
import io.swagger.codegen.v3.CodegenProperty;
import io.swagger.codegen.v3.generators.DefaultCodegenConfig;
import io.swagger.util.Json;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.ComposedSchema;
import io.swagger.v3.oas.models.media.Content;
Expand All @@ -14,6 +19,9 @@
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.parameters.RequestBody;
import io.swagger.v3.parser.OpenAPIV3Parser;
import io.swagger.v3.parser.core.models.ParseOptions;
import io.swagger.v3.parser.core.models.SwaggerParseResult;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import org.testng.Assert;
import org.testng.annotations.Test;
Expand Down Expand Up @@ -154,7 +162,7 @@ public void arraysInRequestBody() throws Exception {
Assert.assertEquals(codegenParameter2.description, "A list of list of values");
Assert.assertEquals(codegenParameter2.dataType, "List<List<Integer>>");
Assert.assertEquals(codegenParameter2.baseType, "List");

RequestBody body3 = new RequestBody();
body3.setDescription("A list of points");
body3.setContent(new Content().addMediaType("application/json", new MediaType().schema(new ArraySchema().items(new ObjectSchema().$ref("#/components/schemas/Point")))));
Expand Down Expand Up @@ -260,4 +268,100 @@ public void customTemplates() throws Exception {
codegen.processOpts();
Assert.assertEquals(codegen.templateDir(), String.join(File.separator,"user", "custom", "location"));
}

@Test
public void testModelNamedFile() {
final OpenAPI openAPI = getOpenAPI("3_0_0/model_named_file.yaml");
final DefaultCodegenConfig config = new JavaClientCodegen();
config.setIgnoreImportMapping(true);
config.preprocessOpenAPI(openAPI);

final Schema modelFile = openAPI.getComponents().getSchemas().get("File");
final Schema modelSetting = openAPI.getComponents().getSchemas().get("Setting");

final CodegenModel codegenModelFile = config.fromModel("File", modelFile, openAPI.getComponents().getSchemas());
final CodegenModel codegenModelSetting = config.fromModel("Setting", modelSetting, openAPI.getComponents().getSchemas());

Assert.assertEquals(codegenModelFile.name, "File");
Assert.assertEquals(codegenModelSetting.name, "Setting");

final List<CodegenProperty> codegenProperties = codegenModelSetting.getVars();

Assert.assertEquals(codegenProperties.size(), 4);

CodegenProperty fileProperty = codegenProperties.stream().filter(property -> property.name.equals("file")).findAny().get();

Assert.assertEquals(fileProperty.name, "file");
Assert.assertEquals(fileProperty.baseType, "File");
Assert.assertEquals(fileProperty.datatype, "File");

CodegenProperty documentProperty = codegenProperties.stream().filter(property -> property.name.equals("document")).findAny().get();

Assert.assertEquals(documentProperty.name, "document");
Assert.assertEquals(documentProperty.baseType, "File");
Assert.assertEquals(documentProperty.datatype, "java.io.File");

Assert.assertFalse(codegenModelSetting.imports.stream().anyMatch(_import -> _import.equals("java.io.File")));
}

private OpenAPI getOpenAPI(String filePath) {
OpenAPIV3Parser openApiParser = new OpenAPIV3Parser();
ParseOptions options = new ParseOptions();
options.setResolve(true);
options.setFlatten(true);
SwaggerParseResult parseResult = openApiParser.readLocation(filePath, null, options);

return parseResult.getOpenAPI();
}



















































}
Loading

0 comments on commit 8e0d919

Please sign in to comment.