OpenAPITools / openapi-generator

OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)
https://openapi-generator.tech
Apache License 2.0
21.15k stars 6.41k forks source link

[BUG][Java] Schema name collision with template imports #19170

Open gtsystem opened 1 month ago

gtsystem commented 1 month ago

Bug Report Checklist

Description

If a schema is named "Schema", the import of such class will be import io.swagger.v3.oas.annotations.media.Schema;. This will also trigger an error because this module is not defined in the pom file by default.

openapi-generator version

7.7.0 and latest (7.8.0-SNAPSHOT)

OpenAPI declaration file content or url
openapi: 3.0.3
info:
  title: Example API
  description: Example API
  contact: {}
  version: 2.0.0

paths: {}

components:
  schemas:
    Response:
      properties:
        schema:
          $ref: '#/components/schemas/Schema'

    Schema:
      properties:
        test:
          type: string
Generation Details
Steps to reproduce
  1. Create the file openapi-example-schema.yml with the content above in the current directory
  2. run docker run -vpwd:/temp -it openapitools/openapi-generator-cli:latest generate -g java -i /temp/openapi-example-schema.yml -o /temp/build/
  3. check the content of the file build/src/main/java/org/openapitools/client/model/Response.java

Current behavior:

Expected behavior:

Tested the same behavior with other imported classes like HashMap

Related issues/PRs

The error I get, is the same reported in #16932, but root cause could be different

Suggest a fix

Schema is one of the optional imports of the Java code generator: AbstractJavaCodegen.java#L578 and I believe the system automatically use the existing import for it.

In theory this could be solved by adding Schema in the list of reserved words. Doing so will result in a class named SchemaModel. However this will also change the property name called schema to _schema which in reality is not necessary. I'm not sure why all reserved words are compared in a case insensitive way..

I also tried to use reservedWordsMappings, but it seems it's only considered for pre-existing reserved words

gtsystem commented 1 month ago

Fix in #19178 works for the case annotationLibrary is not set to swagger2