Skip to content

[BUG] Java Generator for Enum produces invalid fromValue method #12874

@brunoborges

Description

@brunoborges

The abstract Java codegen is generating a fromValue method that does not correctly compute the values of a Java Enum.

See the following spec:

    TodoState:
      type: string
      enum:
        - todo
        - inprogress
        - done

The generator produces the following Enum:

public enum TodoState {
  TODO("todo"), INPROGRESS("inprogress"), DONE("done");

  private String value;
  TodoState(String value) {
    this.value = value;
  }

  @JsonValue
  public String getValue() {
    return value;
  }

  @Override
  public String toString() {
    return String.valueOf(value);
  }

  @JsonCreator
  public static TodoState fromValue(String value) {
    for (TodoState b : TodoState.values()) {
      if (b.value.equals(value)) {
        return b;
      }
    }
    throw new IllegalArgumentException("Unexpected value '" + value + "'");
  }
}

If the URL param {state} contains value done , the code fails to find the appropriate Enum type DONE due to a mismatch in the String case.

The method fromValue should check if there is a custom value associated to the enum, and compare with that instead if to respect the case.

Error log

2022-07-14 21:04:46.657  WARN 10016 --- [nio-8080-exec-9] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'com.example.openapi.model.TodoState'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@io.swagger.v3.oas.annotations.Parameter @org.springframework.web.bind.annotation.PathVariable com.example.openapi.model.TodoState] for value 'done'; nested exception is java.lang.IllegalArgumentException: No enum constant com.example.openapi.model.TodoState.done]

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