OpenAPITools / OpenAPITools/openapi-generator

[BUG] [Java] [OkHttp] [Client] Discriminator implementation has many issues

Open
#19,514 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Issue: Bug
Dominant language
Java
Stars
26.8k
Forks
7.7k
PR merge metrics
PR metrics pending

Description

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

I had a few issues with discriminators in the okhttp and there are several flaws or problems that I have found. I was able to solve all of them using custom templates, but I think they should be solved.

  1. I think in a typed language like Java, the discriminator should not even be a property, because you could have potential mismatches between the actual type and the discriminator property.
  2. The discriminator property is set to the class name, which causes serialization issues: https://github.com/OpenAPITools/openapi-generator/blob/master/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache#L84
  3. A type selector is registered for every class, which is not really needed, because I think it is only needed for the base class. This means that each class with a discriminator needs the discriminator property, which is definitely not the case, e.g. when I want to deserialize Animal I need the discriminator, but not for Dog or Cat
openapi-generator version

7.8.0

OpenAPI declaration file content or url

Sorry, it is not a small reproducible, but it shows the issue
https://cloud.squidex.io/api/swagger/v1/swagger.json

Generation Details

I use the CLI with docker:

docker run --rm -v ${PWD}:/local openapitools/openapi-generator-cli generate -i /local/openapi.json -g java -o /local -c /local/openapi-config.yml
Steps to reproduce
  1. Download the openapi.json
  2. Run the command above.
Related issues/PRs
Suggest a fix

Everything can be solved with changes to the template. I am not sure if my changes catch all problems, though or only my problems.

In the JSON.mustache I changed the type selector registration to the following template:

{{#models}}
        {{#model}}
        {{#discriminator}}
                {{#mappedModels}}
                .registerPostProcessor({{modelPackage}}.{{modelName}}.class, new PostProcessor<{{modelPackage}}.{{modelName}}>() {
                    @Override
                    public void postDeserialize({{modelPackage}}.{{modelName}} result, JsonElement src, Gson gson) {
                    }

                    @Override
                    public void postSerialize(JsonElement result, {{modelPackage}}.{{modelName}} src, Gson gson) {
                        if (result instanceof JsonObject) {
                            ((JsonObject)result).add("{{{propertyBaseName}}}", new JsonPrimitive("{{mappingName}}"));
                        }
                    }
                })
                {{/mappedModels}}
                {{#mappedModels.size}}
                .registerTypeSelector({{modelPackage}}.{{classname}}.class, new TypeSelector<{{modelPackage}}.{{classname}}>() {
                    @Override
                    public Class<? extends {{modelPackage}}.{{classname}}> getClassForElement(JsonElement readElement) {
                        Map<String, Class> classByDiscriminatorValue = new HashMap<String, Class>();
                        {{#mappedModels}}
                        classByDiscriminatorValue.put("{{mappingName}}"{{^discriminatorCaseSensitive}}.toUpperCase(Locale.ROOT){{/discriminatorCaseSensitive}}, {{modelPackage}}.{{modelName}}.class);
                        {{/mappedModels}}
                        return getClassByDiscriminator(classByDiscriminatorValue,
                                getDiscriminatorValue(readElement, "{{{propertyBaseName}}}"));
                    }
                })
                {{/mappedModels.size}}
        {{/discriminator}}
        {{/model}}
        {{/models}}

In the pojo.mustache I filtered out all vars with {{^isDiscriminator}} but this is a very tedious task. Would be easier to introduce a new "filter" to CodeGenModel to get these vars with something like {{#nonDiscriminatorVars}} or something like that.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the Java okhttp-gson templates, especially JSON.mustache and pojo.mustache, and compare their discriminator handling with the reported generated output from the linked OpenAPI document. Review the related CodeGenModel variables and reproduce generation with the provided Docker CLI command; done means discriminator serialization, property generation, and type-selector registration behave correctly for base and mapped classes.

Written by the indexing model from the issue text.

Assessment

Tech stack
docker, java
Domain
api, tooling
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.