openapi-generator icon indicating copy to clipboard operation
openapi-generator copied to clipboard

[BUG] Java enum values are messed up

Open mortenegelund opened this issue 1 year ago • 2 comments

Description

When enum values are parsed with the Java parser, they get messed up in the generated code.

For example:

  • "R2D2" becomes "R2_D2" in Java code
  • "U2F" becomes "U2_F" in Java code
openapi-generator version

Version 7.8.0

Suggested fix

This bug has been introduced with https://github.com/OpenAPITools/openapi-generator/pull/18338

AbstractJavaCodeGen.java, line 1913:

    @Override
    public String toEnumVarName(String value, String datatype) {
        if (enumNameMapping.containsKey(value)) {
            return enumNameMapping.get(value);
        }

        if (value.length() == 0) {
            return "EMPTY";
        }

        // for symbol, e.g. $, #
        if (getSymbolName(value) != null) {
            return getSymbolName(value).toUpperCase(Locale.ROOT);
        }

        if (" ".equals(value)) {
            return "SPACE";
        }

        // number
        if ("Integer".equals(datatype) || "Long".equals(datatype) ||
                "Float".equals(datatype) || "Double".equals(datatype) || "BigDecimal".equals(datatype)) {
            String varName = "NUMBER_" + value;
            varName = varName.replaceAll("-", "MINUS_");
            varName = varName.replaceAll("\\+", "PLUS_");
            varName = varName.replaceAll("\\.", "_DOT_");
            return varName;
        }

        // string
        String var = value.replaceAll("\\W+", "_").toUpperCase(Locale.ROOT);
        if (var.matches("\\d.*")) {
            var = "_" + var;
        }
        return this.toVarName(var); <----------------Should be changed to "return var;"
    }

Related issues/PRs

https://github.com/OpenAPITools/openapi-generator/pull/18338

mortenegelund avatar Aug 23 '24 17:08 mortenegelund

Same issue as #19204

There 2 workarounds: x-enum-varnames in the contract or enumNameMappings option

Some generators have the enumPropertyNaming option. original could solve your specific issue but you would loose the conversion to uppercase. Unfortunately no java implementation yet. There is #19277

jpfinne avatar Aug 24 '24 08:08 jpfinne

There are no hard enum naming conventions in Java. I suggest enum parsing should be done at an absolute minimum level just to avoid syntax errors.

mortenegelund avatar Aug 26 '24 07:08 mortenegelund