Skip to content

[BUG] [Java] Java generator initialize non-required collections with empty collection  #14875

Closed

Description

@Giletka

Bug Report Checklist

  • Have you provided a full/minimal spec to reproduce the issue?
  • Have you validated the input using an OpenAPI validator (example)?
  • Have you tested with the latest master to confirm the issue still exists?
  • Have you searched for related issues/PRs?
  • What's the actual output vs expected output?
  • [Optional] Sponsorship to speed up the bug fix or feature request (example)
Description

After upgrading openapi generator 5.1.1 -> 6.3.0 our integration tests was broken. Reason that API expected null as a init value of the non-required collection property in the pojo classes, but new version initialize it with empty collection (like required ones).

Expected:

  public static final String JSON_PROPERTY_EMAILS = "emails";
  private List<ScimUserEmails> emails = new ArrayList<>();

  public static final String JSON_PROPERTY_ADDRESSES = "addresses";
  private List<ScimUserAddresses> addresses = null;

Actual:

  public static final String JSON_PROPERTY_EMAILS = "emails";
  private List<ScimUserEmailsInner> emails = new ArrayList<>();

  public static final String JSON_PROPERTY_ADDRESSES = "addresses";
  private List<ScimUserAddressesInner> addresses = new ArrayList<>();

Also, generator don't respect @Nullable annotation, but works as expected if you add nullable: true in spec to the property

openapi-generator version

6.2.1, 6.3.0, 6.4.0

OpenAPI declaration file content or url
openapi: 3.0.2
info:
  title: 'Shared SCIM object definitions'
  description: 'SCIM object definitions'
  version: 1.0.1
externalDocs:
  description: Find out more about CIS
  url: https://where.am.i
servers:
  - url: https://where.am.i
paths:
  /test:
    post:
      summary: Test a user with email and address
      operationId: test
      responses:
        '200':
          description: 'Some description'
          content:
            application/scim+json:
              schema:
                $ref: '#/components/schemas/ScimUser'
components:
  schemas:
    ScimUser:
      type: object
      description: 'Here is some description'
      required:
        - userName
        - emails
      properties:
        userName:
          type: string
        emails:
          type: array
          items:
            type: object
            properties:
              key:
                type: string
              type:
                type: string
              value:
                type: string
              display:
                type: string
              primary:
                type: boolean
        addresses:
          type: array
          items:
            type: object
            properties:
              key:
                type: string
              type:
                type: string
              display:
                type: string
              primary:
                type: boolean
              country:
                type: string
              formatted:
                type: string
              locality:
                type: string
              postalCode:
                type: string
              region:
                type: string
              streetAddress:
                type: string
Generation Details

Used Java 11 with gradle

task generateScimModels(type: GenerateTask) {
  generatorName = "java"
  inputSpec = "${inputSpecBasePath}/spec-scim.yaml"
  outputDir = "${buildDir}/generated/sources/scim"
  generateModelTests = false
  generateModelDocumentation = false
  generateApiTests = false
  generateApiDocumentation = false
  validateSpec = false
  apiFilesConstrainedTo = []
  supportingFilesConstrainedTo = []
  modelFilesConstrainedTo = [
      "ScimUser"
  ]
  configOptions = [
      dateLibrary                    : "java8",
      library                             : "resttemplate",
      modelPackage               : "ecg.identity.scim.model",
      useBeanValidation        : "false",
      performBeanValidation: "false",
      supportingFiles             : "false",
      serializableModel          : "true"
  ]
}
Steps to reproduce
  1. Create pojo in spec with required and non-required collections as properties
  2. Generate with "java" generator
Related issues/PRs

This one provides toggle to set null as default for all collections (required and non-required). But no solution to keep null only for non-required as in previous versions.
#1861

Suggest a fix

For me I just made this workaround in openapi/Java/pojo.mustache.
Changed this

  {{^vendorExtensions.x-is-jackson-optional-nullable}}
  {{#isContainer}}
  private {{{datatypeWithEnum}}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}};
  {{/isContainer}}

To this

  {{^vendorExtensions.x-is-jackson-optional-nullable}}
  {{#isContainer}}
  private {{{datatypeWithEnum}}} {{name}} = {{#required}}{{{defaultValue}}}{{/required}}{{^required}}null{{/required}};
  {{/isContainer}}

Activity

  1. wing328 commented on Mar 4, 2023

    @wing328
    Member

    have you tried setting the java generator option containerDefaultToNull to true to see if that meets your requirement?

  2. Giletka commented on Mar 4, 2023

    @Giletka
    Author

    have you tried setting the java generator option containerDefaultToNull to true to see if that meets your requirement?

    Yes, this option makes all collections initialize as null, but default behavior expected empty collection in requred ones.
    I wrote about it here (sorry if it wasn't clear):

    This one provides toggle to set null as default for all collections (required and non-required). But no solution to keep null only for non-required as in previous versions.
    #1861

  3. Giletka commented on Mar 4, 2023

    @Giletka
    Author

    Also, I want to add that "spring" generator, for example, works as expected: required ones generated with empty collection, non-required with null.

  4. eivbjorkelund commented on Mar 8, 2023

    @eivbjorkelund

    Having the same issues when we upgrade to 6.3.0 and 6.4.0. It works fine in 6.2.1 and below.

  5. wing328 commented on Mar 15, 2023

    @wing328
    Member

    Hi all, can you please test #14961 when you've time?

    I did a test with the spec provided in this issue and the result looks good:

    /**
     * Here is some description
     */
    @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2023-03-15T15:56:12.256532+08:00[Asia/Hong_Kong]")
    public class ScimUser {
      public static final String SERIALIZED_NAME_USER_NAME = "userName";
      @SerializedName(SERIALIZED_NAME_USER_NAME)
      private String userName;
    
      public static final String SERIALIZED_NAME_EMAILS = "emails";
      @SerializedName(SERIALIZED_NAME_EMAILS)
      private List<ScimUserEmailsInner> emails = new ArrayList<>();
    
      public static final String SERIALIZED_NAME_ADDRESSES = "addresses";
      @SerializedName(SERIALIZED_NAME_ADDRESSES)
      private List<ScimUserAddressesInner> addresses;
    
  6. eivbjorkelund commented on Mar 16, 2023

    @eivbjorkelund

    Hi. Thanks! #14961 works perfectly in my case.

  7. wing328 commented on Mar 16, 2023

    @wing328
    Member

    @eivbjorkelund thanks for confirming the fix 🙏

  8. wing328 commented on Mar 17, 2023

    @wing328
    Member

    the fix has been merged and will be included in the upcoming 6.5.0 release

  9. fastluca commented on May 23, 2023

    @fastluca

    I have this exactly same issue in the version 6.6.0. A collection field marked as 'required' in the Open API definition is initialized as null. I can confirm that until version 6.2.1 it is working as expected.

  10. wing328 commented on May 24, 2023

    @wing328
    Member

    @fastluca please open a new issue with a spec to reproduce the issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions