Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

openapi-generator-maven-plugin generates invalid Java code when using "oneOf:" property #12556

Closed
R4NN-BAE opened this issue Jun 8, 2022 · 16 comments

Comments

@R4NN-BAE
Copy link

R4NN-BAE commented Jun 8, 2022

Description

Maven test target in openapi-generator-maven-plugin will run successfully,
but the generated Java models are not valid Java code and cannot be compiled by Java compiler
and therefore cannot be used as a JavaClient.
Because of the following issues in the generated Java model Value.java:

Array.validateJsonObject(jsonObject); // The method validateJsonObject(JsonObject) is undefined for the type Array

Is the generated Java code in the maven test target not validate by a Java compiler?
Note, the same error can be reproduced with the Java Types, String, Boolean, BigDecimal

Steps to reproduce

When using following modified schema in openapi\modules\openapi-generator-maven-plugin\src\test\resources\petstore-on-classpath.yaml

openapi: 3.0.0
servers:
  - url: 'http://petstore.swagger.io/v2'
info:
  description: >-
    This is a sample server Petstore server. For this sample, you can use the api key
    `special-key` to test the authorization
  version: 1.0.0
  title: OpenAPI Petstore
  license:
    name: Apache-2.0
    url: 'https://www.apache.org/licenses/LICENSE-2.0.html'
...
paths: 
  /values:  
    get:  
      tags:  
        - values  
      summary: Get some primitive values  
      description: ''  
      operationId: getSomeValues  
      responses:  
        '200':  
          description: successful operation  
          content:  
            application/json:  
              schema:  
                $ref: '#/components/schemas/Value'  
        '400':  
          description: Invalid Value  
...

schemas:  
    Value:  
      description: Value datatype  
      oneOf:  
        - $ref: "#/components/schemas/Scalar"  
        - $ref: "#/components/schemas/Array"  
    Scalar:  
      description: Scalar datatype  
      oneOf:  
        - type: string  
          maxLength: 1089  
        - type: number  
        - type: boolean  
    Array:  
      type: array  
      minItems: 1  
      items:  
        $ref: "#/components/schemas/Scalar"

And the following modified openapi\modules\openapi-generator-maven-plugin\pom.xml,
the <library>jersey2</library> was removed.

 <configuration>
                    <inputSpec>petstore-on-classpath.yaml</inputSpec>
                    <generatorName>java</generatorName>

                    <skipIfSpecIsUnchanged>true</skipIfSpecIsUnchanged>

                    <configOptions>
                        <dateLibrary>joda</dateLibrary>
                    </configOptions>
                    <output>${basedir}/target/generated-sources/common-maven/remote-openapi</output>
                    <apiPackage>remote.org.openapitools.client.api</apiPackage>
                    <modelPackage>remote.org.openapitools.client.model</modelPackage>
                    <invokerPackage>remote.org.openapitools.client</invokerPackage>
</configuration>
openapi-generator version

Can be reproduced with the current "Master" version of this repository.
But also the compile error was reproduced on a build server with the openapi-generator-maven-plugin:

<!-- RELEASE_VERSION -->
<version>6.0.0</version>
<!-- /RELEASE_VERSION -->
Suggest a fix

Maybe there should be a more strict check in this code section,

{{#oneOf}}
// deserialize {{{.}}}
try {
// validate the JSON object to see if any exception is thrown
{{.}}.validateJsonObject(jsonObject);
actualAdapter = adapter{{.}};
match++;
log.log(Level.FINER, "Input data matches schema '{{{.}}}'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for {{{.}}} failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema '{{{.}}}'", e);
}
{{/oneOf}}
if (match == 1) {
{{classname}} ret = new {{classname}}();
ret.setActualInstance(actualAdapter.fromJsonTree(jsonObject));
return ret;
}
throw new IOException(String.format("Failed deserialization for {{classname}}: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonObject.toString()));
}

It looks like this would generate .validateJsonObject(jsonObject) on every type which is not valid
for type Array, String, Boolean, BigDecimal in Java.

@premnalla
Copy link

premnalla commented Jun 8, 2022

I'm having the same issue with DigitalOceans's API - https://github.com/digitalocean/openapi

$openapi-generator --version
openapi-generator-cli 6.0.0
commit : 69f79fb
built : 2022-05-26T02:54:15Z
source : https://github.com/openapitools/openapi-generator
docs : https://openapi-generator.tech/

@lalitmathwani
Copy link

+1 seeing this issue with 6.0.0 as well on one of our internal apis @ adobe.

@autumoswitzerland
Copy link

The same here with:

Command: openapi-generator-cli generate -i SWIFT-API-swift-banking-premium-1.1.2-swagger.yaml -g java -o out

YAML:

https://developer.swift.com/sites/default/files/specs/SWIFT-API-swift-banking-premium-1.1.2-swagger.yaml

I didn't specify any specific property and I got the code:

...
// deserialize Object
try {
// validate the JSON object to see if any exception is thrown
Object.validateJsonObject(jsonObject);
actualAdapter = adapterObject;
match++;
log.log(Level.FINER, "Input data matches schema 'Object'");
...

@aruvic
Copy link

aruvic commented Oct 11, 2022

+1 seeing this issue with 6.1.0 as well on one of our internal apis

@aruvic
Copy link

aruvic commented Oct 19, 2022

@wing328 Hi William, please can you prioritize this bug for 6.2.1. I'm trying to read the code and fix it myself but the code base is huge and I still don't get how things work :-)

@Santobert
Copy link

It is not only oneOf that is affected. I have the same problem with anyOf. I assume this will gain relevance since swagger-api/swagger-core#4291 was merged.

@StevenArzt
Copy link

StevenArzt commented Nov 4, 2022

We also have this issue with one of our builds running openapi-generator-maven-plugin in version 6.2.1, which is the most recent one. The issue affects Boolean, Double, Float, Integer, Long, String. It would be great if this bug could be fixed very soon.

@karzang
Copy link
Contributor

karzang commented Nov 7, 2022

In #13897 I provided a potential fix for this problem regarding oneOf. I think this PR would also be a good baseline for fixing the same problem concerning anyOf.

@felicamargo
Copy link

I am experiencing the same problem with Fireblocks API, @StevenArzt it also affects BigDecimal, on top of the other classes you listed.
error: cannot find symbol
[ERROR] symbol: method validateJsonObject(JsonObject)
[ERROR] location: class BigDecimal

@lostiniceland
Copy link
Contributor

lostiniceland commented Nov 17, 2022

Same here with 6.2.1
We are seing an LocalDate.validateJsonObject(... which is completely bogus. It seems to be cause by an allOf in this case

@tstuber
Copy link

tstuber commented Nov 18, 2022

Is there a known workaround for this issue?

@karzang
Copy link
Contributor

karzang commented Nov 18, 2022

I think a workaround would be to wrap your Boolean, Double, Float, Integer, Long, String or LocalDate Schema into an Object and then reference the object in your allOf/anyOf/oneOf

karzang pushed a commit to karzang/openapi-generator that referenced this issue Jun 27, 2023
@anshuman8800
Copy link

Still facing the same issues, it's latest versions (6., 7.) generating the invalid code like validateJsonObject and java compiler failed to compile it.

Solution : I found 5.1.0 is the stable one and it is working for me in my case and doesn't generated any such invalid codes.

@jagpreetsinghsasan
Copy link

Still facing the same issues, it's latest versions (6., 7.) generating the invalid code like validateJsonObject and java compiler failed to compile it.

Solution : I found 5.1.0 is the stable one and it is working for me in my case and doesn't generated any such invalid codes.

Facing the same issue with openapi 6.6.0

@misakamumu
Copy link

misakamumu commented Jan 5, 2024

Facing the same issue with openapi 6.6.0 , and is there any workaround here, wrap as a object may not have the
same behavior
our request body must be "name": "123" or
"name":{
"operation": true
}
name:
oneOf:
- type: string
- $ref: "#/components/schemas/operation"

@wing328
Copy link
Member

wing328 commented Jan 5, 2024

It (test spec provided in the issue description) works with okhttp-gson but not jersey2/3.

If anyone would like to contribute a PR to sponsor the fix, please reply to let us know. Thank you.

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

No branches or pull requests