Skip to content

[Java][webclient/restclient/resttemplate] Simplify generated API code - #25138

Merged
wing328 merged 2 commits into
OpenAPITools:masterfrom
ondrej-simon:b/java-spring-clients-redundant-null-checks
Oct 7, 2026
Merged

wing328 merged 2 commits into
OpenAPITools:masterfrom
ondrej-simon:b/java-spring-clients-redundant-null-checks

Conversation

@ondrej-simon

@ondrej-simon ondrej-simon commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Simplifies the API code generated by the Spring-based Java client libraries (webclient, restclient, resttemplate), which share the same template structure. IDEs (e.g. IntelliJ) flag the current output with several warnings.

Example (webclient, before):

    private ResponseSpec deletePetRequestCreation(@jakarta.annotation.Nonnull Long petId, @jakarta.annotation.Nullable String apiKey) throws WebClientResponseException {
        Object postBody = null;
        // verify the required parameter 'petId' is set
        if (petId == null) {
            throw new WebClientResponseException(...);
        }
        final Map<String, Object> pathParams = new HashMap<String, Object>();
        ...
        final MultiValueMap<String, String> localVarQueryParams = new LinkedMultiValueMap<String, String>();
        ...
        if (apiKey != null)
        headerParams.add("api_key", apiClient.parameterToString(apiKey));
        ...
        ParameterizedTypeReference<Void> localVarReturnType = new ParameterizedTypeReference<Void>() {};
        return apiClient.invokeAPI("/pet/{petId}", HttpMethod.DELETE, pathParams, localVarQueryParams, postBody, headerParams, ...);
    }

After:

    private ResponseSpec deletePetRequestCreation(@jakarta.annotation.Nonnull Long petId, @jakarta.annotation.Nullable String apiKey) throws WebClientResponseException {
        // verify the required parameter 'petId' is set
        if (petId == null) {
            throw new WebClientResponseException(...);
        }
        final Map<String, Object> pathParams = new HashMap<>();
        ...
        final MultiValueMap<String, String> localVarQueryParams = new LinkedMultiValueMap<>();
        ...
        if (apiKey != null) {
            headerParams.add("api_key", apiClient.parameterToString(apiKey));
        }
        ...
        ParameterizedTypeReference<Void> localVarReturnType = new ParameterizedTypeReference<>() {};
        return apiClient.invokeAPI("/pet/{petId}", HttpMethod.DELETE, pathParams, localVarQueryParams, null, headerParams, ...);
    }

Changes (in all three libraries unless noted):

  • No redundant null checks for required parameters. Header, cookie and form parameters were wrapped in if (param != null), which is always true for required parameters, as they are already validated to be non-null (an exception is thrown otherwise) at the start of the method. These are now added unconditionally; optional parameters keep the null check, now with braces. This also reduces the cyclomatic complexity of the generated methods.
  • No redundant postBody local variable. It was only ever assigned from the body parameter (or null) and passed to invokeAPI, so the body is now passed directly. Same for localVarPostBody = request in resttemplate's generic invokeAPI helper.
  • Diamond operator for HashMap/LinkedMultiValueMap instantiations. For anonymous ParameterizedTypeReference subclasses the diamond operator requires Java 9+, so it is only used when the generated project targets Java 17 (webclient, resttemplate can still target Java 1.8; restclient already used it).
  • resttemplate: to decide that, JavaClientCodegen now sets the existing java17 flag for resttemplate when useJakartaEe is enabled (same as for webclient), and its pom.xml/build.gradle select the Java version via java17 too, so the generated code and build stay consistent. The effective Java version is unchanged; as a side effect, the duplicated <source>17</source><target>17</target> elements in the pom with useSpringBoot4 are gone.

Verification:

  • Regenerated all 35 webclient/restclient/resttemplate sample configs; a script verified that every changed line falls into one of the categories above.
  • Compiled the webclient and resttemplate (Java 1.8 target), webclient-jakarta, resttemplate-jakarta, resttemplate-springBoot4-jackson3 and restclient (Java 17) samples.
  • New tests in JavaClientCodegenTest (shouldNotNullCheckRequiredParametersTwice, shouldUseDiamondOperatorWhereSupported) for all three libraries; all Java generator tests pass.

The second commit updates the go-oneof-not-enum sample, which is stale on master after #25064 and #25089 were merged concurrently and fails the "Samples up-to-date" check.

PR checklist

  • Read the contribution guidelines.
  • Run the following to build the project and update samples:
    ./mvnw clean package || exit
    ./bin/generate-samples.sh ./bin/configs/*.yaml || exit
    ./bin/utils/export_docs_generators.sh || exit
    
    (For Windows users, please run the script in WSL)
    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.
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

cc Java technical committee: @bbdouglas @sreeshas @jfiala @lukoyanov @cbornet @jeff9finger @karismann @Zomzog @lwlee2608 @martin-mfg @KannaKim


Summary by cubic

Simplifies the API code generated by the Spring-based Java client libraries (webclient, restclient, resttemplate) by removing redundant patterns that IDEs flag as warnings.

Refactors

  • Required header, cookie, and form parameters are added unconditionally; they are already validated to be non-null at the start of the method. Optional parameters keep the null check, now with braces.
  • The request body is passed directly to the API invocation call, removing the redundant postBody and localVarPostBody local variables.
  • HashMap and LinkedMultiValueMap instantiations use the diamond operator; anonymous ParameterizedTypeReference subclasses use it only when the target is Java 17.
  • resttemplate now sets the existing java17 flag when useJakartaEe is enabled and uses it to pick the Java version in pom.xml/build.gradle, with no change to the effective Java version and duplicated <source>/<target> elements removed for useSpringBoot4.
  • Updates the stale go-oneof-not-enum sample that failed the "Samples up-to-date" check after concurrent merges.

Written for commit 6c9bf74. Summary will update on new commits.

Review in cubic

- Only null-check optional header, cookie and form parameters (and use
  braces); required parameters are already validated to be non-null
- Pass the request body to invokeAPI directly instead of through a
  redundant postBody local variable
- Use the diamond operator for generic instantiations; for anonymous
  ParameterizedTypeReference classes only when targeting Java 17
- Set the java17 flag for resttemplate when using Jakarta EE and use it
  to select the Java version in its pom.xml and build.gradle (which also
  removes duplicated source/target elements with Spring Boot 4)
The sample on master is out of date after OpenAPITools#25064 and OpenAPITools#25089 were merged
concurrently, which fails the "Samples up-to-date" check.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 145 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread samples/client/others/go/oneof-not-enum/docs/EnumNullUnion.md
@wing328
wing328 merged commit e97c0db into OpenAPITools:master Oct 7, 2026
154 checks passed
@wing328 wing328 added Client: Java Enhancement: Code Cleanup General refactoring, removal of deprecated things, commenting, etc. labels Oct 7, 2026
@wing328 wing328 added this to the 7.27.0 milestone Oct 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Client: Java Enhancement: Code Cleanup General refactoring, removal of deprecated things, commenting, etc.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants