Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[JAVA][GO] Fix inheritance issues #18784

Draft
wants to merge 13 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4746,9 +4746,7 @@ public CodegenOperation fromOperation(String path,
if (contentType != null) {
contentType = contentType.toLowerCase(Locale.ROOT);
}
if (contentType != null &&
((!(this instanceof RustAxumServerCodegen) && contentType.startsWith("application/x-www-form-urlencoded")) ||
contentType.startsWith("multipart"))) {
if (isFormMimeType(contentType)) {
// process form parameters
formParams = fromRequestBodyToFormParameters(requestBody, imports);
op.isMultipart = contentType.startsWith("multipart");
Expand Down Expand Up @@ -5276,11 +5274,7 @@ public CodegenParameter fromParameter(Parameter parameter, Set<String> imports)
parameterSchema = unaliasSchema(parameter.getSchema());
parameterModelName = getParameterDataType(parameter, parameterSchema);
CodegenProperty prop;
if (this instanceof RustServerCodegen) {
// for rust server, we need to do somethings special as it uses
// $ref (e.g. #components/schemas/Pet) to determine whether it's a model
prop = fromProperty(parameter.getName(), parameterSchema, false);
} else if (getUseInlineModelResolver()) {
if (getUseInlineModelResolver()) {
prop = fromProperty(parameter.getName(), getReferencedSchemaWhenNotEnum(parameterSchema), false);
} else {
prop = fromProperty(parameter.getName(), parameterSchema, false);
Expand Down Expand Up @@ -5327,7 +5321,7 @@ public CodegenParameter fromParameter(Parameter parameter, Set<String> imports)
return codegenParameter;
}

if (getUseInlineModelResolver() && !(this instanceof RustServerCodegen)) {
if (getUseInlineModelResolver()) {
// for rust server, we cannot run the following as it uses
// $ref (e.g. #components/schemas/Pet) to determine whether it's a model
parameterSchema = getReferencedSchemaWhenNotEnum(parameterSchema);
Expand Down Expand Up @@ -7011,9 +7005,7 @@ public boolean hasFormParameter(Operation operation) {
}

for (String consume : consumesInfo) {
if (consume != null &&
(consume.toLowerCase(Locale.ROOT).startsWith("application/x-www-form-urlencoded") ||
consume.toLowerCase(Locale.ROOT).startsWith("multipart"))) {
if (isFormMimeType(consume)) {
return true;
}
}
Expand Down Expand Up @@ -7156,8 +7148,6 @@ public List<CodegenParameter> fromRequestBodyToFormParameters(RequestBody body,
// https://github.com/OpenAPITools/openapi-generator/issues/10415
addProperties(properties, allRequired, schema, new HashSet<>());

boolean isOneOfOrAnyOf = ModelUtils.isOneOf(schema) || ModelUtils.isAnyOf(schema);

if (!properties.isEmpty()) {
for (Map.Entry<String, Schema> entry : properties.entrySet()) {
CodegenParameter codegenParameter;
Expand All @@ -7167,7 +7157,7 @@ public List<CodegenParameter> fromRequestBodyToFormParameters(RequestBody body,
Schema propertySchema = entry.getValue();
codegenParameter = fromFormProperty(propertyName, propertySchema, imports);

if (isOneOfOrAnyOf) {
if (ModelUtils.isOneOf(schema) || ModelUtils.isAnyOf(schema)) {
// for oneOf/anyOf, mark all the properties collected from the sub-schemas as optional
// so that users can choose which property to include in the form parameters
codegenParameter.required = false;
Expand Down Expand Up @@ -8345,6 +8335,16 @@ public int hashCode() {
}
}

protected boolean isFormMimeType(String mime) {
if (mime == null) {
return false;
}

mime = mime.toLowerCase(Locale.ROOT);
return mime.startsWith("application/x-www-form-urlencoded")
|| mime.startsWith("multipart"); // ← maybe multipart/form-data would be more accurate?
}

/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -760,9 +760,6 @@ public ModelsMap postProcessModels(ModelsMap objs) {
addedOSImport = true;
}
}
if (this instanceof GoClientCodegen && model.isEnum) {
imports.add(createMapping("import", "fmt"));
}

// if oneOf contains "null" type
if (model.oneOf != null && !model.oneOf.isEmpty() && model.oneOf.contains("nil")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1790,15 +1790,6 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert
}
}

// hard-coded Arrays import in Java client as it has been removed from the templates
if (this instanceof JavaClientCodegen &&
("jersey2".equals(library) ||
"jersey3".equals(library) ||
"native".equals(library) ||
"okhttp-gson".equals(library))) {
model.imports.add("Arrays");
}

if ("array".equals(property.containerType)) {
model.imports.add("ArrayList");
model.imports.add("Arrays");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -477,6 +477,14 @@ public ModelsMap postProcessModels(ModelsMap objs) {

for (ModelMap m : objs.getModels()) {
CodegenModel model = m.getModel();

if (model.isEnum
|| model.hasRequired
|| (model.oneOf != null && !model.oneOf.isEmpty())
|| (model.anyOf != null && !model.anyOf.isEmpty())) {
imports.add(createMapping("import", "fmt"));
}

if (model.isEnum) {
continue;
}
Expand All @@ -499,31 +507,11 @@ public ModelsMap postProcessModels(ModelsMap objs) {
}
}

// additional import for different cases
boolean addedFmtImport = false;

// oneOf
if (model.oneOf != null && !model.oneOf.isEmpty()) {
imports.add(createMapping("import", "fmt"));
addedFmtImport = true;
}

// anyOf
if (model.anyOf != null && !model.anyOf.isEmpty()) {
imports.add(createMapping("import", "fmt"));
addedFmtImport = true;
}

if (model.hasRequired) {
if (!model.isAdditionalPropertiesTrue &&
(model.oneOf == null || model.oneOf.isEmpty()) &&
(model.anyOf == null || model.anyOf.isEmpty())) {
imports.add(createMapping("import", "bytes"));
}

if (!addedFmtImport) {
imports.add(createMapping("import", "fmt"));
}
if (model.hasRequired
&& !model.isAdditionalPropertiesTrue
&& (model.oneOf == null || model.oneOf.isEmpty())
&& (model.anyOf == null || model.anyOf.isEmpty())) {
imports.add(createMapping("import", "bytes"));
}

// additionalProperties: true and parent
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -996,6 +996,13 @@ private static boolean isMultipartType(List<Map<String, String>> consumes) {
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);

// hard-coded Arrays import in Java client as it has been removed from the templates
final List<String> libsRequiringArrayImport = List.of("jersey2", "jersey3", "native", "okhttp-gson");
if (libsRequiringArrayImport.contains(library)) {
model.imports.add("Arrays");
}

if (!BooleanUtils.toBoolean(model.isEnum)) {
//final String lib = getLibrary();
//Needed imports for Jackson based libraries
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,13 +89,9 @@ public JavaMicronautAbstractCodegen() {
visitable = false;
buildTool = OPT_BUILD_ALL;
testTool = OPT_TEST_JUNIT;
outputFolder = this instanceof JavaMicronautClientCodegen ?
"generated-code/java-micronaut-client" : "generated-code/java-micronaut";
apiPackage = "org.openapitools.api";
modelPackage = "org.openapitools.model";
invokerPackage = "org.openapitools";
artifactId = this instanceof JavaMicronautClientCodegen ?
"openapi-micronaut-client" : "openapi-micronaut";
embeddedTemplateDir = templateDir = "java-micronaut";
apiDocPath = "docs/apis";
modelDocPath = "docs/models";
Expand All @@ -104,9 +100,6 @@ public JavaMicronautAbstractCodegen() {
reactive = true;
wrapInHttpResponse = false;
appName = artifactId;
generateSwaggerAnnotations = this instanceof JavaMicronautClientCodegen ?
OPT_GENERATE_SWAGGER_ANNOTATIONS_FALSE : OPT_GENERATE_SWAGGER_ANNOTATIONS_SWAGGER_2;
generateOperationOnlyForFirstTag = this instanceof JavaMicronautServerCodegen;

// Set implemented features for user information
modifyFeatureSet(features -> features
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,11 @@ public JavaMicronautClientCodegen() {
super();

title = "OpenAPI Micronaut Client";
artifactId = "openapi-micronaut-client";
configureAuthorization = false;
generateOperationOnlyForFirstTag = false;
generateSwaggerAnnotations = OPT_GENERATE_SWAGGER_ANNOTATIONS_FALSE;
outputFolder = "generated-code/java-micronaut-client";

generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata)
.stability(Stability.BETA)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ public JavaMicronautServerCodegen() {
title = "OpenAPI Micronaut Server";
apiPackage = "org.openapitools.api";
apiDocPath = "docs/controllers";
artifactId = "openapi-micronaut";
generateOperationOnlyForFirstTag = true;
generateSwaggerAnnotations = OPT_GENERATE_SWAGGER_ANNOTATIONS_SWAGGER_2;
outputFolder = "generated-code/java-micronaut";

generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata)
.stability(Stability.BETA)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,11 @@ boolean isMimetypePlain(String mimetype) {
isMimetypeMultipartRelated(mimetype));
}

@Override protected boolean isFormMimeType(String mime) {
return mime != null
&& mime.toLowerCase(Locale.ROOT).startsWith("multipart"); // ← maybe multipart/form-data would be more accurate?
}

@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, List<Server> servers) {
CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1480,4 +1480,11 @@ protected String getParameterDataType(Parameter parameter, Schema schema) {
}
return null;
}

@Override
public boolean getUseInlineModelResolver() {
// for rust server, we need to do something special as it uses
// $ref (e.g. #components/schemas/Pet) to determine whether it's a model
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

package org.openapitools.codegen;


import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
Expand All @@ -31,6 +30,7 @@
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.headers.Header;
import io.swagger.v3.oas.models.media.*;
import io.swagger.v3.oas.models.parameters.PathParameter;
import io.swagger.v3.oas.models.parameters.QueryParameter;
import io.swagger.v3.oas.models.parameters.RequestBody;
import io.swagger.v3.oas.models.responses.ApiResponse;
Expand All @@ -47,6 +47,7 @@
import org.openapitools.codegen.utils.SemVer;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Ignore;
import org.testng.annotations.Test;

Expand All @@ -57,6 +58,7 @@
import java.util.stream.Collectors;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.InstanceOfAssertFactories.type;
import static org.testng.Assert.*;

public class DefaultCodegenTest {
Expand Down Expand Up @@ -4933,4 +4935,86 @@ public void testAllVars_issue_18340() {
CodegenModel springCat2 = springCodegen.fromModel("Cat2", cat2Model);
assertThat(getNames(springCat2.allVars)).isEqualTo(List.of("petType", "name"));
}

@SuppressWarnings("NewClassNamingConvention")
public static class fromParameter {

DefaultCodegen codegen = new DefaultCodegen();

@BeforeTest void setOpenAPI() {
codegen.setOpenAPI(new OpenAPI().components(new Components().addSchemas(
"SampleRequestInput",
new ObjectSchema().addProperty(
"FormProp1",
new StringSchema()
)
)));
}

@Test public void resolvesReferencedSchema() {
var parameter = new PathParameter()
.name("input")
.schema(new Schema<>().$ref("SampleRequestInput"));

CodegenParameter result = codegen.fromParameter(parameter, new HashSet<>());

assertThat(result.getSchema())
.returns("object", CodegenProperty::getBaseType)
.returns("Object", CodegenProperty::getDataType)
.returns(null, CodegenProperty::getRef)
.returns(true, CodegenProperty::getHasVars)

.extracting(CodegenProperty::getVars).asList().hasSize(1)
.first(type(CodegenProperty.class))
.returns("FormProp1", CodegenProperty::getName)
.returns("String", CodegenProperty::getDataType);
}
}

@SuppressWarnings("NewClassNamingConvention")
public static class fromOperation {

DefaultCodegen codegen = new DefaultCodegen();

@BeforeTest void setOpenAPI() {
codegen.setOpenAPI(new OpenAPI().components(new Components().addSchemas("SampleRequestInput", new ObjectSchema().addProperty("FormProp1", new StringSchema()))));
}


@Test public void addsFormParametersFromRequestProperties_forFormContentType() {
var operation = new Operation()
.parameters(List.of())
.operationId("foobar")
.requestBody(new RequestBody().content(new Content().addMediaType(
"application/x-www-form-urlencoded",
new MediaType().schema(new Schema<>().$ref("SampleRequestInput"))
)));

CodegenOperation result = codegen.fromOperation("/", "GET", operation, List.of());

assertThat(result.bodyParams).isEmpty();
assertThat(result.formParams).hasSize(1).first()
.hasFieldOrPropertyWithValue("baseName", "FormProp1")
.hasFieldOrPropertyWithValue("dataType", "String")
.hasFieldOrPropertyWithValue("paramName", "formProp1");
}

@Test public void doesNotAddFormParametersFromRequestProperties_forJsonContentType() {
var operation = new Operation()
.parameters(List.of())
.operationId("foobar")
.requestBody(new RequestBody().content(new Content().addMediaType(
"application/json",
new MediaType().schema(new Schema<>().$ref("SampleRequestInput"))
)));

CodegenOperation result = codegen.fromOperation("", "GET", operation, List.of());

assertThat(result.formParams).isEmpty();
assertThat(result.bodyParams).hasSize(1).first()
.hasFieldOrPropertyWithValue("baseName", "SampleRequestInput")
.hasFieldOrPropertyWithValue("dataType", "SampleRequestInput")
.hasFieldOrPropertyWithValue("paramName", "sampleRequestInput");
}
}
}
Loading
Loading