Repository navigation
[java][native] support useOneOfInterfaces and useDeductionForOneOfInterfaces - #25813
thorstenhirsch wants to merge 1 commit into
Conversation
…erfaces
The native library ignored useOneOfInterfaces in model.mustache and always
rendered the oneOf wrapper class, while DefaultCodegen still made the member
models implement the oneOf type. The generated code therefore failed to
compile ("interface expected here"), which also made
useDeductionForOneOfInterfaces unusable for oneOf schemas without a
discriminator.
- native/model.mustache and model_doc.mustache dispatch to the shared
oneof_interface / pojo_doc templates for x-is-one-of-interface models, like
the okhttp library does.
- The generated api classes call toUrlQueryString on deepObject and exploded
query parameters, so the interface declares it (guarded by supportUrlQuery)
through a new oneof_interface_members hook partial that is empty for all
other libraries.
- Add unit tests, a native-oneof-interface sample with deserialization tests
and wire it into the JDK11 sample workflow.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
8 issues found across 52 files
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="samples/client/others/java/native-oneof-interface/src/test/java/org/openapitools/client/model/AuthorTest.java">
<violation number="1" location="samples/client/others/java/native-oneof-interface/src/test/java/org/openapitools/client/model/AuthorTest.java:42">
P2: These regression tests never execute in the Maven sample: `pom.xml` declares `junit-jupiter-api` but no `junit-jupiter-engine`, while CI runs `mvn clean package`. Add the Jupiter engine to the Maven test dependencies so this test can fail the build when deserialization breaks.</violation>
</file>
<file name="modules/openapi-generator/src/main/resources/Java/libraries/native/model.mustache">
<violation number="1" location="modules/openapi-generator/src/main/resources/Java/libraries/native/model.mustache:67">
P2: With `useSealedOneOfInterfaces=true`, native now emits `sealed interface ... permits ...` through the new `oneof_interface` branch. The PR says sealed is unsupported for native, and the code has no guard for it. Add a native guard that rejects or ignores the option, or confirm the generated Java 11 build compiles.</violation>
</file>
<file name="samples/client/others/java/native-oneof-interface/docs/DefaultApi.md">
<violation number="1" location="samples/client/others/java/native-oneof-interface/docs/DefaultApi.md:27">
P2: The API documentation examples import a nonexistent plural `models` package. Change each example to `org.openapitools.client.model.*` so the snippets compile against this client.</violation>
<violation number="2" location="samples/client/others/java/native-oneof-interface/docs/DefaultApi.md:69">
P3: The POST endpoint documentation says no `Accept` header exists, but the generated request sends `Accept: application/json`. List `application/json` for both create operations to keep the documentation consistent with the client and specification.</violation>
</file>
<file name=".github/workflows/samples-java-client-jdk11.yaml">
<violation number="1" location=".github/workflows/samples-java-client-jdk11.yaml:115">
P2: This matrix entry never exercises the sample's Gradle build because the workflow checks for `./gradlew` at repository root. Gate the step with `hashFiles(format('{0}/gradlew', matrix.sample))` instead.</violation>
</file>
<file name="samples/client/others/java/native-oneof-interface/README.md">
<violation number="1" location="samples/client/others/java/native-oneof-interface/README.md:89">
P2: The Getting Started example cannot compile because `Author` is generated as an interface. Instantiate a concrete variant such as `new ServiceAuthor().subject("Jane")`, and update the repeated API examples as well.</violation>
</file>
<file name="samples/client/others/java/native-oneof-interface/src/main/java/org/openapitools/client/ServerConfiguration.java">
<violation number="1" location="samples/client/others/java/native-oneof-interface/src/main/java/org/openapitools/client/ServerConfiguration.java:55">
P2: `ServerConfiguration.URL` dereferences `enumValues` even though `ServerVariable` permits it to be null. Guard the collection before checking its size so variables without enum constraints can be overridden.</violation>
</file>
<file name="samples/client/others/java/native-oneof-interface/src/main/java/org/openapitools/client/api/DefaultApi.java">
<violation number="1" location="samples/client/others/java/native-oneof-interface/src/main/java/org/openapitools/client/api/DefaultApi.java:338">
P2: `getAuthor` decodes JSON with the platform default charset, corrupting non-ASCII responses on non-UTF-8 JVMs. Decode the bytes as UTF-8 before deserialization.</violation>
</file>
Tip: Get a Slack DM when cubic finishes reviewing your PRs. Connect Slack
View guided diff | Re-trigger cubic
| private final com.fasterxml.jackson.databind.ObjectMapper mapper = new org.openapitools.client.JSON().getMapper(); | ||
|
|
||
| @Test | ||
| void deducesServiceAuthorFromSubject() throws Exception { |
There was a problem hiding this comment.
P2: These regression tests never execute in the Maven sample: pom.xml declares junit-jupiter-api but no junit-jupiter-engine, while CI runs mvn clean package. Add the Jupiter engine to the Maven test dependencies so this test can fail the build when deserialization breaks.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At samples/client/others/java/native-oneof-interface/src/test/java/org/openapitools/client/model/AuthorTest.java, line 42:
<comment>These regression tests never execute in the Maven sample: `pom.xml` declares `junit-jupiter-api` but no `junit-jupiter-engine`, while CI runs `mvn clean package`. Add the Jupiter engine to the Maven test dependencies so this test can fail the build when deserialization breaks.</comment>
<file context>
@@ -0,0 +1,70 @@
+ private final com.fasterxml.jackson.databind.ObjectMapper mapper = new org.openapitools.client.JSON().getMapper();
+
+ @Test
+ void deducesServiceAuthorFromSubject() throws Exception {
+ Author author = mapper.readValue("{\"subject\":\"Jane\"}", Author.class);
+
</file context>
| {{/vendorExtensions.x-is-one-of-interface}} | ||
|
|
||
| {{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#oneOf}}{{#-first}}{{>oneof_model}}{{/-first}}{{/oneOf}}{{^oneOf}}{{#anyOf}}{{#-first}}{{>anyof_model}}{{/-first}}{{/anyOf}}{{^anyOf}}{{>pojo}}{{/anyOf}}{{/oneOf}}{{/isEnum}} | ||
| {{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#vendorExtensions.x-is-one-of-interface}}{{>oneof_interface}}{{/vendorExtensions.x-is-one-of-interface}}{{^vendorExtensions.x-is-one-of-interface}}{{#oneOf}}{{#-first}}{{>oneof_model}}{{/-first}}{{/oneOf}}{{^oneOf}}{{#anyOf}}{{#-first}}{{>anyof_model}}{{/-first}}{{/anyOf}}{{^anyOf}}{{>pojo}}{{/anyOf}}{{/oneOf}}{{/vendorExtensions.x-is-one-of-interface}}{{/isEnum}} |
There was a problem hiding this comment.
P2: With useSealedOneOfInterfaces=true, native now emits sealed interface ... permits ... through the new oneof_interface branch. The PR says sealed is unsupported for native, and the code has no guard for it. Add a native guard that rejects or ignores the option, or confirm the generated Java 11 build compiles.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At modules/openapi-generator/src/main/resources/Java/libraries/native/model.mustache, line 67:
<comment>With `useSealedOneOfInterfaces=true`, native now emits `sealed interface ... permits ...` through the new `oneof_interface` branch. The PR says sealed is unsupported for native, and the code has no guard for it. Add a native guard that rejects or ignores the option, or confirm the generated Java 11 build compiles.</comment>
<file context>
@@ -56,12 +56,14 @@ import org.hibernate.validator.constraints.*;
+{{/vendorExtensions.x-is-one-of-interface}}
-{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#oneOf}}{{#-first}}{{>oneof_model}}{{/-first}}{{/oneOf}}{{^oneOf}}{{#anyOf}}{{#-first}}{{>anyof_model}}{{/-first}}{{/anyOf}}{{^anyOf}}{{>pojo}}{{/anyOf}}{{/oneOf}}{{/isEnum}}
+{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#vendorExtensions.x-is-one-of-interface}}{{>oneof_interface}}{{/vendorExtensions.x-is-one-of-interface}}{{^vendorExtensions.x-is-one-of-interface}}{{#oneOf}}{{#-first}}{{>oneof_model}}{{/-first}}{{/oneOf}}{{^oneOf}}{{#anyOf}}{{#-first}}{{>anyof_model}}{{/-first}}{{/anyOf}}{{^anyOf}}{{>pojo}}{{/anyOf}}{{/oneOf}}{{/vendorExtensions.x-is-one-of-interface}}{{/isEnum}}
{{/model}}
{{/models}}
</file context>
| import org.openapitools.client.ApiClient; | ||
| import org.openapitools.client.ApiException; | ||
| import org.openapitools.client.Configuration; | ||
| import org.openapitools.client.models.*; |
There was a problem hiding this comment.
P2: The API documentation examples import a nonexistent plural models package. Change each example to org.openapitools.client.model.* so the snippets compile against this client.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At samples/client/others/java/native-oneof-interface/docs/DefaultApi.md, line 27:
<comment>The API documentation examples import a nonexistent plural `models` package. Change each example to `org.openapitools.client.model.*` so the snippets compile against this client.</comment>
<file context>
@@ -0,0 +1,262 @@
+import org.openapitools.client.ApiClient;
+import org.openapitools.client.ApiException;
+import org.openapitools.client.Configuration;
+import org.openapitools.client.models.*;
+import org.openapitools.client.api.DefaultApi;
+
</file context>
| - samples/client/others/java/jersey2-oneOf-duplicates/ | ||
| - samples/client/others/java/jersey2-oneOf-Mixed/ | ||
| - samples/client/others/java/native-oneOf-array/ | ||
| - samples/client/others/java/native-oneof-interface/ |
There was a problem hiding this comment.
P2: This matrix entry never exercises the sample's Gradle build because the workflow checks for ./gradlew at repository root. Gate the step with hashFiles(format('{0}/gradlew', matrix.sample)) instead.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At .github/workflows/samples-java-client-jdk11.yaml, line 115:
<comment>This matrix entry never exercises the sample's Gradle build because the workflow checks for `./gradlew` at repository root. Gate the step with `hashFiles(format('{0}/gradlew', matrix.sample))` instead.</comment>
<file context>
@@ -110,6 +112,7 @@ jobs:
- samples/client/others/java/jersey2-oneOf-duplicates/
- samples/client/others/java/jersey2-oneOf-Mixed/
- samples/client/others/java/native-oneOf-array/
+ - samples/client/others/java/native-oneof-interface/
- samples/client/others/java/resttemplate-list-schema-validation/
- samples/client/petstore/java/okhttp-gson-3.1-duplicated-operationid/
</file context>
| // Configure clients using the `defaultClient` object, such as | ||
| // overriding the host and port, timeout, etc. | ||
| DefaultApi apiInstance = new DefaultApi(defaultClient); | ||
| Author author = new Author(); // Author | |
There was a problem hiding this comment.
P2: The Getting Started example cannot compile because Author is generated as an interface. Instantiate a concrete variant such as new ServiceAuthor().subject("Jane"), and update the repeated API examples as well.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At samples/client/others/java/native-oneof-interface/README.md, line 89:
<comment>The Getting Started example cannot compile because `Author` is generated as an interface. Instantiate a concrete variant such as `new ServiceAuthor().subject("Jane")`, and update the repeated API examples as well.</comment>
<file context>
@@ -0,0 +1,137 @@
+ // Configure clients using the `defaultClient` object, such as
+ // overriding the host and port, timeout, etc.
+ DefaultApi apiInstance = new DefaultApi(defaultClient);
+ Author author = new Author(); // Author |
+ try {
+ apiInstance.createAuthor(author);
</file context>
|
|
||
| if (variables != null && variables.containsKey(name)) { | ||
| value = variables.get(name); | ||
| if (serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value)) { |
There was a problem hiding this comment.
P2: ServerConfiguration.URL dereferences enumValues even though ServerVariable permits it to be null. Guard the collection before checking its size so variables without enum constraints can be overridden.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At samples/client/others/java/native-oneof-interface/src/main/java/org/openapitools/client/ServerConfiguration.java, line 55:
<comment>`ServerConfiguration.URL` dereferences `enumValues` even though `ServerVariable` permits it to be null. Guard the collection before checking its size so variables without enum constraints can be overridden.</comment>
<file context>
@@ -0,0 +1,72 @@
+
+ if (variables != null && variables.containsKey(name)) {
+ value = variables.get(name);
+ if (serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value)) {
+ throw new IllegalArgumentException("The variable " + name + " in the server URL has invalid value " + value + ".");
+ }
</file context>
| if (serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value)) { | |
| if (serverVariable.enumValues != null && serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value)) { |
|
|
||
|
|
||
|
|
||
| String responseBody = new String(localVarResponseBody.readAllBytes()); |
There was a problem hiding this comment.
P2: getAuthor decodes JSON with the platform default charset, corrupting non-ASCII responses on non-UTF-8 JVMs. Decode the bytes as UTF-8 before deserialization.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At samples/client/others/java/native-oneof-interface/src/main/java/org/openapitools/client/api/DefaultApi.java, line 338:
<comment>`getAuthor` decodes JSON with the platform default charset, corrupting non-ASCII responses on non-UTF-8 JVMs. Decode the bytes as UTF-8 before deserialization.</comment>
<file context>
@@ -0,0 +1,383 @@
+
+
+
+ String responseBody = new String(localVarResponseBody.readAllBytes());
+ Author responseValue = responseBody.isBlank()? null: memberVarObjectMapper.readValue(responseBody, new TypeReference<Author>() {});
+
</file context>
| ### HTTP request headers | ||
|
|
||
| - **Content-Type**: application/json | ||
| - **Accept**: Not defined |
There was a problem hiding this comment.
P3: The POST endpoint documentation says no Accept header exists, but the generated request sends Accept: application/json. List application/json for both create operations to keep the documentation consistent with the client and specification.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At samples/client/others/java/native-oneof-interface/docs/DefaultApi.md, line 69:
<comment>The POST endpoint documentation says no `Accept` header exists, but the generated request sends `Accept: application/json`. List `application/json` for both create operations to keep the documentation consistent with the client and specification.</comment>
<file context>
@@ -0,0 +1,262 @@
+### HTTP request headers
+
+- **Content-Type**: application/json
+- **Accept**: Not defined
+
+### HTTP response details
</file context>
Title
[java][native] support useOneOfInterfaces / useDeductionForOneOfInterfaces
Description
Related to #25727 and #25728.
With
library=native,useOneOfInterfaces=truecurrently produces code that does not compile.native/model.mustacheignoresx-is-one-of-interfaceand always renders theoneof_modelwrapper class (extends AbstractOpenApiSchema), butDefaultCodegenstill makes the members implement the oneOf type:As a consequence
useDeductionForOneOfInterfacescannot be used withnativeeither, although it is the way to resolve aoneOfwithout discriminator by the set of properties (as pointed out by @jpfinne in #25727).This PR makes
nativehonour the option, the same wayokhttpalready does:libraries/native/model.mustacheandmodel_doc.mustachedispatch to the sharedoneof_interface/pojo_doctemplates forx-is-one-of-interfacemodels. WithoutuseOneOfInterfacesnothing changes (wrapper class withgetActualInstance()).toUrlQueryString(...)on deepObject / exploded query parameters. To keep that compiling for a oneOf type, the interface declarestoUrlQueryString(String prefix)(plus adefaultno-arg variant, because enums only implement the prefix variant). This is guarded bysupportUrlQuery, like in the pojo. To avoid copying the whole template, the sharedoneof_interface.mustachegot a hook partialoneof_interface_members, which is empty for every library exceptnative.com.fasterxml.jackson.annotation).Example (spec from #25727,
useOneOfInterfaces=true,useDeductionForOneOfInterfaces=true):{"subject":"Jane"}→ServiceAuthor,{"id":"u-1","domainId":"acme"}→UserAuthor,{"unknown":1}is rejected.Please note: Jackson's deduction only looks at which properties are present, not at
required.{"id":"u-1"}is therefore resolved toUserAuthor(it is the only variant that has anid), it is not rejected. Combine it withgenerateJsonCreatorfrom #25728 if missing required properties must be rejected, too.useSealedOneOfInterfacesis still not supported fornative(the native pojos are notfinal); this PR does not change that.Tests
JavaClientCodegenTest: discriminator interface, deduction interface (Jackson 2 and 3),supportUrlQuery=false, and a regression test thatnativewithoutuseOneOfInterfacesstill generates the wrapper class. All generated sources are compiled byvalidateJavaSourceFiles.samples/client/others/java/native-oneof-interface(added to the JDK11 sample workflow) with deserialization tests inAuthorTest.PR checklist
Commit all changed files.
This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master.
These must match the expectations made by your contribution.
You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example
./bin/generate-samples.sh bin/configs/java*.IMPORTANT: Do NOT purge/delete any folders/files (e.g. tests) when regenerating the samples as manually written tests may be removed.
@bbdouglas (2017/07) @sreeshas (2017/08) @jfiala (2017/08) @lukoyanov (2017/09) @cbornet (2017/09) @jeff9finger (2018/01) @karismann (2019/03) @Zomzog (2019/04) @lwlee2608 (2019/10) @martin-mfg (2023/08) @KannaKim (2026/07) @AndreyVMarkelov (2026/11)
🤖 Generated with Claude Code
Summary by cubic
Makes the
nativeJava library honoruseOneOfInterfaces=true, fixing generated code that previously failed to compile, and enablesuseDeductionForOneOfInterfacesfor oneOf schemas without a discriminator.Previously the native templates always rendered the oneOf wrapper class while members still implemented the oneOf interface type, producing
interface expected hereerrors. The templates now dispatch to the shared oneof_interface template like theokhttplibrary does.Details
toUrlQueryString()(prefix and default no-arg variants) via a newoneof_interface_membershook, empty for all other libraries and guarded bysupportUrlQuery.native-oneof-interfacesample with deserialization tests, registered in the JDK11 sample workflow.useSealedOneOfInterfacesremains unsupported fornative.required; combine withgenerateJsonCreator([java][native] add generateJsonCreator to distinguish between oneOf types w/o discriminator #25728) to reject payloads with missing required properties.Written for commit 3458e02. Summary will update on new commits.