Skip to content

Commit

Permalink
Merge branch 'OpenAPITools:master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
azdolinski authored Mar 15, 2024
2 parents 045bc2e + 3bd8974 commit 14c5972
Show file tree
Hide file tree
Showing 502 changed files with 2,000 additions and 1,605 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1036,6 +1036,7 @@ private Schema processNormalize31Spec(Schema schema, Set<Schema> visitedSchemas)
as.setMaxItems(schema.getMaxItems());
as.setExtensions(schema.getExtensions());
as.setXml(schema.getXml());
as.setUniqueItems(schema.getUniqueItems());
if (schema.getItems() != null) {
// `items` is also a json schema
if (StringUtils.isNotEmpty(schema.getItems().get$ref())) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1103,13 +1103,13 @@ public String getAlias(String name) {
*/
public String toArrayDefaultValue(CodegenProperty cp, Schema schema) {
if (schema.getDefault() != null) { // has default value
if (cp.isArray && !cp.getUniqueItems()) { // array
if (cp.isArray) {
List<String> _values = new ArrayList<>();

if (schema.getDefault() instanceof ArrayNode) { // array of default values
ArrayNode _default = (ArrayNode) schema.getDefault();
if (_default.isEmpty()) { // e.g. default: []
return "new ArrayList<>()";
return getDefaultCollectionType(schema);
}

List<String> final_values = _values;
Expand Down Expand Up @@ -1155,14 +1155,12 @@ public String toArrayDefaultValue(CodegenProperty cp, Schema schema) {
defaultValue = StringUtils.join(_values, ", ");
}
} else {
return "new ArrayList<>()";
return getDefaultCollectionType(schema);
}

return String.format(Locale.ROOT, "new ArrayList<>(Arrays.asList(%s))", defaultValue);
} else if (cp.isArray && cp.getUniqueItems()) { // set
// TODO
return null;
} else if (cp.isMap) { // map
return getDefaultCollectionType(schema, defaultValue);
}
if (cp.isMap) { // map
// TODO
return null;
} else {
Expand All @@ -1178,21 +1176,13 @@ public String toDefaultValue(CodegenProperty cp, Schema schema) {
schema = ModelUtils.getReferencedSchema(this.openAPI, schema);
if (ModelUtils.isArraySchema(schema)) {
if (schema.getDefault() == null) {
// nullable, optional or containerDefaultToNull set to true
if (cp.isNullable || !cp.required || containerDefaultToNull) {
// nullable or containerDefaultToNull set to true
if (cp.isNullable || containerDefaultToNull) {
return null;
} else {
if (ModelUtils.isSet(schema)) {
return String.format(Locale.ROOT, "new %s<>()",
instantiationTypes().getOrDefault("set", "LinkedHashSet"));
} else {
return String.format(Locale.ROOT, "new %s<>()",
instantiationTypes().getOrDefault("array", "ArrayList"));
}
}
} else { // has default value
return toArrayDefaultValue(cp, schema);
return getDefaultCollectionType(schema);
}
return toArrayDefaultValue(cp, schema);
} else if (ModelUtils.isMapSchema(schema) && !(ModelUtils.isComposedSchema(schema))) {
if (schema.getProperties() != null && schema.getProperties().size() > 0) {
// object is complex object with free-form additional properties
Expand All @@ -1202,7 +1192,8 @@ public String toDefaultValue(CodegenProperty cp, Schema schema) {
return null;
}

if (cp.isNullable || containerDefaultToNull) { // nullable or containerDefaultToNull set to true
// nullable or containerDefaultToNull set to true
if (cp.isNullable || containerDefaultToNull) {
return null;
}

Expand Down Expand Up @@ -1290,6 +1281,24 @@ public String toDefaultValue(CodegenProperty cp, Schema schema) {
return super.toDefaultValue(schema);
}

private String getDefaultCollectionType(Schema schema) {
return getDefaultCollectionType(schema, null);
}

private String getDefaultCollectionType(Schema schema, String defaultValues) {
String arrayFormat = "new %s<>(Arrays.asList(%s))";
if(defaultValues == null || defaultValues.isEmpty()){
defaultValues = "";
arrayFormat = "new %s<>()";
}

if (ModelUtils.isSet(schema)) {
return String.format(Locale.ROOT, arrayFormat,
instantiationTypes().getOrDefault("set", "LinkedHashSet"),defaultValues);
}
return String.format(Locale.ROOT, arrayFormat, instantiationTypes().getOrDefault("array", "ArrayList"),defaultValues);
}

@Override
public String toDefaultParameterValue(final Schema<?> schema) {
Object defaultValue = schema.get$ref() != null ? ModelUtils.getReferencedSchema(openAPI, schema).getDefault() : schema.getDefault();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -374,19 +374,25 @@ List<PostmanRequestItem> getPostmanRequests(CodegenOperation codegenOperation) {
items.add(new PostmanRequestItem(codegenOperation.summary, getJsonFromSchema(codegenOperation.bodyParam)));
} else {
// get from examples
if (codegenOperation.bodyParam.example != null) {
// find in bodyParam example
items.add(new PostmanRequestItem(codegenOperation.summary, formatJson(codegenOperation.bodyParam.example)));
} else if (codegenOperation.bodyParam.getContent().get("application/json") != null &&
if (codegenOperation.bodyParam.getContent().get("application/json") != null &&
codegenOperation.bodyParam.getContent().get("application/json").getExamples() != null) {
// find in components/examples
for (Map.Entry<String, Example> entry : codegenOperation.bodyParam.getContent().get("application/json").getExamples().entrySet()) {
String exampleRef = entry.getValue().get$ref();
Example example = this.openAPI.getComponents().getExamples().get(extractExampleByName(exampleRef));
String exampleAsString = getJsonFromExample(example);

items.add(new PostmanRequestItem(example.getSummary(), exampleAsString));
if(entry.getValue().get$ref() != null) {
// find in components/examples
String exampleRef = entry.getValue().get$ref();
Example example = this.openAPI.getComponents().getExamples().get(extractExampleByName(exampleRef));
String exampleAsString = getJsonFromExample(example);

items.add(new PostmanRequestItem(example.getSummary(), exampleAsString));
} else if (entry.getValue().getValue() != null && entry.getValue().getValue() instanceof ObjectNode) {
// find inline
String exampleAsString = convertToJson((ObjectNode) entry.getValue().getValue());
items.add(new PostmanRequestItem(entry.getKey(), exampleAsString));
}
}
} else if (codegenOperation.bodyParam.example != null) {
// find in bodyParam example
items.add(new PostmanRequestItem(codegenOperation.summary, formatJson(codegenOperation.bodyParam.example)));
} else if (codegenOperation.bodyParam.getSchema() != null) {
// find in schema example
String exampleAsString = formatJson(codegenOperation.bodyParam.getSchema().getExample());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -605,11 +605,11 @@ public void toDefaultValueTest() {

ModelUtils.setGenerateAliasAsModel(false);
defaultValue = codegen.toDefaultValue(codegen.fromProperty("", schema), schema);
Assert.assertEquals(defaultValue, null);
Assert.assertEquals(defaultValue, "new ArrayList<>()");

ModelUtils.setGenerateAliasAsModel(true);
defaultValue = codegen.toDefaultValue(codegen.fromProperty("", schema), schema);
Assert.assertEquals(defaultValue, null);
Assert.assertEquals(defaultValue, "new ArrayList<>()");

// Create a map schema with additionalProperties type set to array alias
schema = new MapSchema().additionalProperties(new Schema().$ref("#/components/schemas/NestedArray"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public void converterInArrayTest() {
Assert.assertEquals(enumVar.dataType, "List<String>");
Assert.assertEquals(enumVar.datatypeWithEnum, "List<NameEnum>");
Assert.assertEquals(enumVar.name, "name");
Assert.assertEquals(enumVar.defaultValue, null);
Assert.assertEquals(enumVar.defaultValue, "new ArrayList<>()");
Assert.assertEquals(enumVar.baseType, "List");
Assert.assertTrue(enumVar.isEnum);

Expand Down Expand Up @@ -108,7 +108,7 @@ public void converterInArrayInArrayTest() {
Assert.assertEquals(enumVar.dataType, "List<List<String>>");
Assert.assertEquals(enumVar.datatypeWithEnum, "List<List<NameEnum>>");
Assert.assertEquals(enumVar.name, "name");
Assert.assertEquals(enumVar.defaultValue, null);
Assert.assertEquals(enumVar.defaultValue, "new ArrayList<>()");
Assert.assertEquals(enumVar.baseType, "List");
Assert.assertTrue(enumVar.isEnum);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ public void listPropertyTest() {
Assert.assertEquals(property.setter, "setUrls");
Assert.assertEquals(property.dataType, "List<String>");
Assert.assertEquals(property.name, "urls");
Assert.assertEquals(property.defaultValue, null);
Assert.assertEquals(property.defaultValue, "new ArrayList<>()");
Assert.assertEquals(property.baseType, "List");
Assert.assertEquals(property.containerType, "array");
Assert.assertFalse(property.required);
Expand Down Expand Up @@ -162,7 +162,7 @@ public void setPropertyTest() {
Assert.assertEquals(property.setter, "setUrls");
Assert.assertEquals(property.dataType, "Set<String>");
Assert.assertEquals(property.name, "urls");
Assert.assertEquals(property.defaultValue, null);
Assert.assertEquals(property.defaultValue, "new LinkedHashSet<>()");
Assert.assertEquals(property.baseType, "Set");
Assert.assertEquals(property.containerType, "set");
Assert.assertFalse(property.required);
Expand Down Expand Up @@ -248,7 +248,7 @@ public void list2DPropertyTest() {
Assert.assertEquals(property.setter, "setList2D");
Assert.assertEquals(property.dataType, "List<List<Pet>>");
Assert.assertEquals(property.name, "list2D");
Assert.assertEquals(property.defaultValue, null);
Assert.assertEquals(property.defaultValue, "new ArrayList<>()");
Assert.assertEquals(property.baseType, "List");
Assert.assertEquals(property.containerType, "array");
Assert.assertFalse(property.required);
Expand Down Expand Up @@ -333,7 +333,7 @@ public void complexListPropertyTest() {
Assert.assertEquals(property.setter, "setChildren");
Assert.assertEquals(property.dataType, "List<Children>");
Assert.assertEquals(property.name, "children");
Assert.assertEquals(property.defaultValue, null);
Assert.assertEquals(property.defaultValue, "new ArrayList<>()");
Assert.assertEquals(property.baseType, "List");
Assert.assertEquals(property.containerType, "array");
Assert.assertFalse(property.required);
Expand Down Expand Up @@ -396,7 +396,7 @@ public void complexArrayPropertyTest() {
Assert.assertEquals(property.setter, "setChildren");
Assert.assertEquals(property.dataType, "List<Children>");
Assert.assertEquals(property.name, "children");
Assert.assertEquals(property.defaultValue, null);
Assert.assertEquals(property.defaultValue, "new ArrayList<>()");
Assert.assertEquals(property.baseType, "List");
Assert.assertEquals(property.containerType, "array");
Assert.assertFalse(property.required);
Expand Down Expand Up @@ -429,7 +429,7 @@ public void complexSetPropertyTest() {
Assert.assertEquals(property.setter, "setChildren");
Assert.assertEquals(property.dataType, "Set<Children>");
Assert.assertEquals(property.name, "children");
Assert.assertEquals(property.defaultValue, null);
Assert.assertEquals(property.defaultValue, "new LinkedHashSet<>()");
Assert.assertEquals(property.baseType, "Set");
Assert.assertEquals(property.containerType, "set");
Assert.assertFalse(property.required);
Expand Down Expand Up @@ -466,7 +466,7 @@ public void arrayModelWithItemNameTest() {
Assert.assertEquals(property.setter, "setChildren");
Assert.assertEquals(property.dataType, "List<Child>");
Assert.assertEquals(property.name, "children");
Assert.assertEquals(property.defaultValue, null);
Assert.assertEquals(property.defaultValue, "new ArrayList<>()");
Assert.assertEquals(property.baseType, "List");
Assert.assertEquals(property.containerType, "array");
Assert.assertFalse(property.required);
Expand Down Expand Up @@ -974,7 +974,7 @@ public void modelWithWrappedXmlTest() {
Assert.assertEquals(property2.setter, "setArray");
Assert.assertEquals(property2.dataType, "List<String>");
Assert.assertEquals(property2.name, "array");
Assert.assertEquals(property2.defaultValue, null);
Assert.assertEquals(property2.defaultValue, "new ArrayList<>()");
Assert.assertEquals(property2.baseType, "List");
Assert.assertTrue(property2.isContainer);
Assert.assertTrue(property2.isXmlWrapped);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,20 @@ public JavaFileAssert fileContains(final String... lines) {
return this;
}

public JavaFileAssert fileDoesNotContains(final String... lines) {
final String actualBody = actual.getTokenRange()
.orElseThrow(() -> new IllegalStateException("Empty file"))
.toString();
Assertions.assertThat(actualBody)
.withFailMessage(
"File should not contains lines\n====\n%s\n====\nbut actually was\n====\n%s\n====",
Arrays.stream(lines).collect(Collectors.joining(System.lineSeparator())), actualBody
)
.doesNotContain(lines);

return this;
}

public TypeAnnotationAssert assertTypeAnnotations() {
return new TypeAnnotationAssert(this, actual.getType(0).getAnnotations());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4518,4 +4518,76 @@ public void testLombokAnnotations() throws IOException {
.assertMethod("equals")
;
}

@Test
public void optionalListShouldBeEmpty() throws IOException {
File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
output.deleteOnExit();

OpenAPI openAPI = new OpenAPIParser()
.readLocation("src/test/resources/3_1/petstore.yaml", null, new ParseOptions()).getOpenAPI();
SpringCodegen codegen = new SpringCodegen();
codegen.setLibrary(SPRING_CLOUD_LIBRARY);
codegen.setOutputDir(output.getAbsolutePath());
codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "xyz.model");
codegen.additionalProperties().put(CodegenConstants.API_NAME_SUFFIX, "Controller");
codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "xyz.controller");
codegen.additionalProperties().put(CodegenConstants.MODEL_NAME_SUFFIX, "Dto");


ClientOptInput input = new ClientOptInput()
.openAPI(openAPI)
.config(codegen);

DefaultGenerator generator = new DefaultGenerator();
Map<String, File> files = generator.opts(input).generate().stream()
.collect(Collectors.toMap(File::getName, Function.identity()));

JavaFileAssert.assertThat(files.get("PetDto.java"))
.fileContains("private List<@Valid TagDto> tags = new ArrayList<>();")
.fileContains("private List<String> photoUrls = new ArrayList<>();");

}

@Test
public void testCollectionTypesWithDefaults_issue_18102() throws IOException {
File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
output.deleteOnExit();

OpenAPI openAPI = new OpenAPIParser()
.readLocation("src/test/resources/3_1/java/issue_18102.yaml", null, new ParseOptions()).getOpenAPI();
SpringCodegen codegen = new SpringCodegen();
codegen.setLibrary(SPRING_CLOUD_LIBRARY);
codegen.setOutputDir(output.getAbsolutePath());
codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "xyz.model");
codegen.additionalProperties().put(CodegenConstants.API_NAME_SUFFIX, "Controller");
codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "xyz.controller");
codegen.additionalProperties().put(CodegenConstants.MODEL_NAME_SUFFIX, "Dto");
codegen.setContainerDefaultToNull(true);


ClientOptInput input = new ClientOptInput()
.openAPI(openAPI)
.config(codegen);

DefaultGenerator generator = new DefaultGenerator();
Map<String, File> files = generator.opts(input).generate().stream()
.collect(Collectors.toMap(File::getName, Function.identity()));

JavaFileAssert.assertThat(files.get("PetDto.java"))
.fileContains("private List<@Valid TagDto> tags")
.fileContains("private List<@Valid TagDto> tagsDefaultList = new ArrayList<>()")
.fileContains("private Set<@Valid TagDto> tagsUnique")
.fileContains("private Set<@Valid TagDto> tagsDefaultSet = new LinkedHashSet<>();")
.fileContains("private List<String> stringList")
.fileContains("private List<String> stringDefaultList = new ArrayList<>(Arrays.asList(\"A\", \"B\"));")
.fileContains("private List<String> stringEmptyDefaultList = new ArrayList<>();")
.fileContains("Set<String> stringSet")
.fileContains("private Set<String> stringDefaultSet = new LinkedHashSet<>(Arrays.asList(\"A\", \"B\"));")
.fileContains("private Set<String> stringEmptyDefaultSet = new LinkedHashSet<>();")
.fileDoesNotContains("private List<@Valid TagDto> tags = new ArrayList<>()")
.fileDoesNotContains("private Set<@Valid TagDto> tagsUnique = new LinkedHashSet<>()")
.fileDoesNotContains("private List<String> stringList = new ArrayList<>()")
.fileDoesNotContains("private Set<String> stringSet = new LinkedHashSet<>()");
}
}
Loading

0 comments on commit 14c5972

Please sign in to comment.