Skip to content
Open
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
1 change: 1 addition & 0 deletions bin/configs/java-native-jackson3.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ additionalProperties:
useReflectionEqualsHashCode: "true"
useJackson3: "true"
openApiNullable: "false"
generateJsonCreator: "true"
1 change: 1 addition & 0 deletions docs/generators/java-microprofile.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|generateClientAsBean|For resttemplate, restclient and webclient, configure whether to create `ApiClient.java` and Apis clients as bean (with `@Component` annotation).| |false|
|generateConstructorWithAllArgs|whether to generate a constructor for all arguments| |false|
|generateInsecureTlsHook|Generate the hook that disables TLS certificate validation and trusts all certificates (default to true): ApiClient.disableCertificateValidation on jersey2/jersey3, ApiClient.setVerifyingSsl(false) on okhttp. Set to false to omit it, e.g. when static analysis flags the trust-all TrustManager it contains. Available on `jersey2`, `jersey3`, `okhttp` libraries.| |true|
|generateJsonCreator|Whether to generate a `@JsonCreator` constructor for required properties, so that deserialization fails when a required property is missing (native library only).| |false|
|gradleProperties|Append additional Gradle properties to the gradle.properties file| |null|
|groupId|groupId in generated pom.xml| |org.openapitools|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
Expand Down
1 change: 1 addition & 0 deletions docs/generators/java.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|generateClientAsBean|For resttemplate, restclient and webclient, configure whether to create `ApiClient.java` and Apis clients as bean (with `@Component` annotation).| |false|
|generateConstructorWithAllArgs|whether to generate a constructor for all arguments| |false|
|generateInsecureTlsHook|Generate the hook that disables TLS certificate validation and trusts all certificates (default to true): ApiClient.disableCertificateValidation on jersey2/jersey3, ApiClient.setVerifyingSsl(false) on okhttp. Set to false to omit it, e.g. when static analysis flags the trust-all TrustManager it contains. Available on `jersey2`, `jersey3`, `okhttp` libraries.| |true|
|generateJsonCreator|Whether to generate a `@JsonCreator` constructor for required properties, so that deserialization fails when a required property is missing (native library only).| |false|
|gradleProperties|Append additional Gradle properties to the gradle.properties file| |null|
|groupId|groupId in generated pom.xml| |org.openapitools|
|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false|
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
public static final String USE_SEALED_ONE_OF_INTERFACES = "useSealedOneOfInterfaces";
public static final String USE_UNARY_INTERCEPTOR = "useUnaryInterceptor";
public static final String USE_JACKSON_3 = "useJackson3";
public static final String GENERATE_JSON_CREATOR = "generateJsonCreator";

// Internal configurations
public static final String SINGLE_REQUEST_PARAMETER = "singleRequestParameter";
Expand All @@ -139,6 +140,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
private static final String JACKSON2_PACKAGE = "com.fasterxml.jackson";
private static final String JACKSON3_PACKAGE = "tools.jackson";
private static final String JACKSON_PACKAGE = "jacksonPackage";
private static final String JSON_CREATOR_VARS = "x-java-json-creator-vars";

public static final String GENERATE_CLIENT_AS_BEAN = "generateClientAsBean";

Expand Down Expand Up @@ -176,6 +178,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
@Setter protected boolean useSealedOneOfInterfaces = false;
@Setter protected boolean useUnaryInterceptor = false;
@Getter @Setter protected boolean useJackson3 = false;
@Getter @Setter protected boolean generateJsonCreator = false;

protected String authFolder;
/**
Expand Down Expand Up @@ -299,6 +302,7 @@ public JavaClientCodegen() {
cliOptions.add(CliOption.newBoolean(USE_ENUM_CASE_INSENSITIVE, "Use `equalsIgnoreCase` when String for enum comparison", useEnumCaseInsensitive));
cliOptions.add(CliOption.newBoolean(FAIL_ON_UNKNOWN_PROPERTIES, "Fail Jackson de-serialization on unknown properties", this.failOnUnknownProperties));
cliOptions.add(CliOption.newBoolean(USE_JACKSON_3, "Use Jackson 3 instead of Jackson 2. Supported for 'native', 'apache-httpclient', 'jersey3', 'okhttp', and 'rest-assured' libraries (requires Java 17+) and for Spring 'resttemplate', 'webclient', and 'restclient' libraries (require useSpringBoot4=true).", this.useJackson3));
cliOptions.add(CliOption.newBoolean(GENERATE_JSON_CREATOR, "Whether to generate a `@JsonCreator` constructor for required properties, so that deserialization fails when a required property is missing (native library only).", this.generateJsonCreator));
cliOptions.add(CliOption.newBoolean(SUPPORT_VERTX_FUTURE, "Also generate api methods that return a vertx Future instead of taking a callback. Only `vertx` supports this option. Requires vertx 4 or greater.", this.supportVertxFuture));
cliOptions.add(CliOption.newBoolean(USE_SEALED_ONE_OF_INTERFACES, "Generate the oneOf interfaces as sealed interfaces. Only supported for WebClient, RestClient and Microprofile (with Jackson).", this.useSealedOneOfInterfaces));
cliOptions.add(CliOption.newBoolean(USE_UNARY_INTERCEPTOR, "If true it will generate ResponseInterceptors using a UnaryOperator. This can be usefull for manipulating the request before it gets passed, for example doing your own decryption", this.useUnaryInterceptor));
Expand Down Expand Up @@ -424,6 +428,7 @@ public void processOpts() {
SERIALIZATION_LIBRARY_JACKSON.equals(additionalProperties.get(CodegenConstants.SERIALIZATION_LIBRARY));
convertPropertyToBooleanAndWriteBack(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, this::setUseOneOfDiscriminatorLookup);
convertPropertyToBooleanAndWriteBack(USE_JACKSON_3, this::setUseJackson3);
convertPropertyToBooleanAndWriteBack(GENERATE_JSON_CREATOR, this::setGenerateJsonCreator);
convertPropertyToBooleanAndWriteBack(USE_SPRING_BOOT4, this::setUseSpringBoot4);
if (useJackson3 && (libRestClient || libRestTemplate || libWebClient) && !useSpringBoot4) {
throw new IllegalArgumentException("useJackson3 for the restclient, resttemplate, and webclient libraries requires useSpringBoot4=true");
Expand Down Expand Up @@ -1411,6 +1416,18 @@ public Map<String, ModelsMap> postProcessAllModels(Map<String, ModelsMap> objs)
if (isLibrary(OKHTTP)) {
pruneUnusedOkHttpModelImports(objs);
}
if (isLibrary(NATIVE) && this.jackson) {
// The native library deserializes models through their no-arg constructor, so required
// properties are not enforced by Jackson. A @JsonCreator constructor is needed to make
// deserialization fail when a required property is missing, which is what allows oneOf
// variants with different required properties to be told apart.
for (CodegenModel cm : getAllModels(objs).values()) {
if (cm.isEnum) {
continue;
}
addJsonCreatorVendorExtensions(cm);
}
}
return objs;
}

Expand Down Expand Up @@ -1497,6 +1514,137 @@ private static boolean declaresPropertyOfType(CodegenModel cm, String simpleName
|| (v.datatypeWithEnum != null && type.matcher(v.datatypeWithEnum).find()));
}

private void addJsonCreatorVendorExtensions(CodegenModel cm) {
if (generateJsonCreator && !canGenerateJsonCreator(cm)) {
if (hasIncompatibleOverride(cm)) {
LOGGER.warn("Skipping the @JsonCreator constructor for model '{}' because it overrides an inherited property with a different type", cm.name);
} else {
LOGGER.debug("Skipping the @JsonCreator constructor for model '{}' because an ancestor cannot generate one", cm.name);
}
return;
}
List<CodegenProperty> creatorVars = getJsonCreatorVars(cm);
if (creatorVars.isEmpty()) {
return;
}

Set<String> ownNames = new HashSet<>();
for (CodegenProperty property : cm.vars) {
ownNames.add(property.name);
}
List<CodegenProperty> assignVars = new ArrayList<>();
for (CodegenProperty property : creatorVars) {
if (ownNames.contains(property.name)) {
assignVars.add(property);
}
}

String superCall;
if (generateJsonCreator && cm.getParentModel() != null) {
StringBuilder sb = new StringBuilder("super(");
boolean first = true;
for (CodegenProperty property : getJsonCreatorVars(cm.getParentModel())) {
if (!first) {
sb.append(", ");
}
sb.append(property.name);
first = false;
}
superCall = sb.append(")").toString();
} else {
superCall = "this()";
}

cm.vendorExtensions.put("x-java-json-creator", true);
cm.vendorExtensions.put(JSON_CREATOR_VARS, creatorVars);
cm.vendorExtensions.put("x-java-json-creator-assign-vars", assignVars);
cm.vendorExtensions.put("x-java-json-creator-super-call", superCall);
}

/**
* Returns true when a property defined by this model reuses the name of an inherited
* property with a different Java type. Such a model cannot have a constructor that both
* assigns the child field and calls the parent constructor, so no creator is generated and
* the model keeps its historical no-arg deserialization.
*/
private boolean hasIncompatibleOverride(CodegenModel cm) {
CodegenModel parent = cm.getParentModel();
if (parent == null) {
return false;
}
Map<String, String> inheritedTypes = new HashMap<>();
for (CodegenProperty property : getJsonCreatorVars(parent)) {
inheritedTypes.put(property.name, property.datatypeWithEnum);
}
for (CodegenProperty property : cm.vars) {
String inheritedType = inheritedTypes.get(property.name);
if (inheritedType != null && !inheritedType.equals(property.datatypeWithEnum)) {
return true;
}
}
return false;
}

/**
* Returns true when this model and all its ancestors can have a {@code @JsonCreator}
* constructor. If an ancestor cannot (because of an incompatible property override), its
* descendants must not call a non-existent parent constructor.
*/
private boolean canGenerateJsonCreator(CodegenModel cm) {
if (hasIncompatibleOverride(cm)) {
return false;
}
CodegenModel parent = cm.getParentModel();
return parent == null || canGenerateJsonCreator(parent);
}

/**
* Returns the constructor parameters for the {@code @JsonCreator} constructor of the given
* model, in the order they must be passed to the parent constructor.
*/
@SuppressWarnings("unchecked")
private List<CodegenProperty> getJsonCreatorVars(CodegenModel cm) {
Object cached = cm.vendorExtensions.get(JSON_CREATOR_VARS);
if (cached instanceof List) {
return (List<CodegenProperty>) cached;
}

List<CodegenProperty> vars = new ArrayList<>();
Set<String> names = new HashSet<>();

if (!generateJsonCreator) {
// Preserve the historical behaviour: a constructor holding the read-only properties only.
for (CodegenProperty property : cm.readOnlyVars) {
if (names.add(property.name)) {
vars.add(property);
}
}
return vars;
}

CodegenModel parent = cm.getParentModel();
if (parent != null) {
vars.addAll(getJsonCreatorVars(parent));
}
for (CodegenProperty property : cm.vars) {
int index = -1;
for (int i = 0; i < vars.size(); i++) {
if (vars.get(i).name.equals(property.name)) {
index = i;
break;
}
}
if (index >= 0) {
// an overridden property keeps the slot of the inherited one, but uses the type of
// the child so the generated field assignment compiles
vars.set(index, property);
} else if (property.required || property.isReadOnly) {
vars.add(property);
}
}
return vars;
}

@Override
public ModelsMap postProcessModelsEnum(ModelsMap objs) {
objs = super.postProcessModelsEnum(objs);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,20 @@ dependencies {
implementation "org.openapitools:jackson-databind-nullable:0.2.13"
{{/openApiNullable}}
{{/useJackson3}}
{{#withXml}}
{{#useJackson3}}
implementation "tools.jackson.dataformat:jackson-dataformat-xml:$jackson3_version"
{{/useJackson3}}
{{^useJackson3}}
implementation "com.fasterxml.jackson.dataformat:jackson-dataformat-xml:$jackson_version"
{{/useJackson3}}
{{#useJakartaEe}}
implementation "jakarta.xml.bind:jakarta.xml.bind-api:4.0.0"
{{/useJakartaEe}}
{{^useJakartaEe}}
implementation "javax.xml.bind:jaxb-api:2.3.1"
{{/useJakartaEe}}
{{/withXml}}
{{#useJspecify}}
implementation "org.jspecify:jspecify:1.0.0"
{{/useJspecify}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,11 @@ import java.io.Serializable;
{{#jackson}}
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
{{#withXml}}
import com.fasterxml.jackson.dataformat.xml.annotation.*;
import {{jacksonPackage}}.dataformat.xml.annotation.*;
{{/withXml}}
{{#vendorExtensions.x-has-readonly-properties}}
{{#vendorExtensions.x-java-json-creator}}
import com.fasterxml.jackson.annotation.JsonCreator;
{{/vendorExtensions.x-has-readonly-properties}}
{{/vendorExtensions.x-java-json-creator}}
{{/jackson}}
{{#withXml}}
import {{javaxPackage}}.xml.bind.annotation.*;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,19 +85,30 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens
public {{classname}}() { {{#parent}}{{#parcelableModel}}
super();{{/parcelableModel}}{{/parent}}{{#gson}}{{#discriminator}}
this.{{{discriminatorName}}} = this.getClass().getSimpleName();{{/discriminator}}{{/gson}}
}{{#vendorExtensions.x-has-readonly-properties}}{{^withXml}}
}{{#vendorExtensions.x-java-json-creator}}

{{#jackson}}@JsonCreator{{/jackson}}
/**
* Constructor with required and read-only properties
*/
@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
public {{classname}}(
{{#readOnlyVars}}
@JsonProperty(JSON_PROPERTY_{{nameInSnakeCase}}) {{{datatypeWithEnum}}} {{name}}{{^-last}}, {{/-last}}
{{/readOnlyVars}}
{{#vendorExtensions.x-java-json-creator-vars}}
@JsonProperty(value = JSON_PROPERTY_{{nameInSnakeCase}}, required = {{required}})
@JsonInclude({{#isMap}}{{#items.isNullable}}content = JsonInclude.Include.ALWAYS, {{/items.isNullable}}{{/isMap}}value = JsonInclude.Include.{{#required}}ALWAYS{{/required}}{{^required}}USE_DEFAULTS{{/required}})
{{#withXml}}
@JacksonXmlProperty(localName = "{{items.xmlName}}{{^items.xmlName}}{{xmlName}}{{^xmlName}}{{baseName}}{{/xmlName}}{{/items.xmlName}}"{{#isXmlAttribute}}, isAttribute = true{{/isXmlAttribute}}{{#xmlNamespace}}, namespace = "{{.}}"{{/xmlNamespace}})
{{#isContainer}}
@JacksonXmlElementWrapper({{#isXmlWrapped}}localName = "{{xmlName}}{{^xmlName}}{{baseName}}{{/xmlName}}", {{#xmlNamespace}}namespace = "{{.}}", {{/xmlNamespace}}{{/isXmlWrapped}}useWrapping = {{isXmlWrapped}})
{{/isContainer}}
{{/withXml}}
{{>nullableArgumentWithEnum}} {{name}}{{^-last}},{{/-last}}
{{/vendorExtensions.x-java-json-creator-vars}}
) {
this();
{{#readOnlyVars}}
{{{vendorExtensions.x-java-json-creator-super-call}}};
{{#vendorExtensions.x-java-json-creator-assign-vars}}
this.{{name}} = {{#vendorExtensions.x-is-jackson-optional-nullable}}{{name}} == null ? JsonNullable.<{{{datatypeWithEnum}}}>undefined() : JsonNullable.of({{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{name}}{{/vendorExtensions.x-is-jackson-optional-nullable}};
{{/readOnlyVars}}
}{{/withXml}}{{/vendorExtensions.x-has-readonly-properties}}
{{/vendorExtensions.x-java-json-creator-assign-vars}}
}{{/vendorExtensions.x-java-json-creator}}
{{#vars}}

{{^isReadOnly}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,37 @@
<version>${jackson-databind-nullable-version}</version>
</dependency>
{{/useJackson3}}
{{#withXml}}
<!-- XML processing: Jackson -->
{{#useJackson3}}
<dependency>
<groupId>tools.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>${jackson3-version}</version>
</dependency>
{{/useJackson3}}
{{^useJackson3}}
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>${jackson-version}</version>
</dependency>
{{/useJackson3}}
{{#useJakartaEe}}
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>4.0.0</version>
</dependency>
{{/useJakartaEe}}
{{^useJakartaEe}}
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
{{/useJakartaEe}}
{{/withXml}}
{{^useJspecify}}

<!-- @Nullable annotation -->
Expand Down
Loading
Loading