OpenAPITools / OpenAPITools/openapi-generator

[BUG] Can NOT work with generic parameter using spring boot ResponseBodyAdvice

Open
#19,403 0 comments 0 reactions 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

@RestController
public class ProductController {

    @Autowired
    private ProductService productService;

    @Operation(
            operationId = "viewProduct",
            summary = "View a product's details",
            tags = { "Products" },
            responses = {
                    @ApiResponse(responseCode = "200", description = "OK", content = {
                            @Content(mediaType = "application/json", schema = @Schema(implementation = ResultVO.class))
                    }),
                    @ApiResponse(responseCode = "400", description = "Bad Request", content = {
                            @Content(mediaType = "application/json", schema = @Schema(implementation = ResultVO.class))
                    }),
                    @ApiResponse(responseCode = "401", description = "Not authorized", content = {
                            @Content(mediaType = "application/json", schema = @Schema(implementation = ResultVO.class))
                    }),
                    @ApiResponse(responseCode = "403", description = "Forbidden", content = {
                            @Content(mediaType = "application/json", schema = @Schema(implementation = ResultVO.class))
                    }),
                    @ApiResponse(responseCode = "404", description = "Not Found", content = {
                            @Content(mediaType = "application/json", schema = @Schema(implementation = ResultVO.class))
                    }),
                    @ApiResponse(responseCode = "429", description = "429 Too Many Requests", content = {
                            @Content(mediaType = "application/json", schema = @Schema(implementation = ResultVO.class))
                    }),
                    @ApiResponse(responseCode = "500", description = "500 Internal Server Error", content = {
                            @Content(mediaType = "application/json", schema = @Schema(implementation = ResultVO.class))
                    })
            },
            security = {
                    @SecurityRequirement(name = "ApiKeyAuth")
            }
    )
    @RequestMapping(
            method = RequestMethod.GET,
            value = "/v1/catalog/products/{id}",
            produces = { "application/json" }
    )
    public Product viewProduct(
            @Parameter(name = "id", description = "Product identifier", required = true) @PathVariable("id") UUID id) {
        Product product = productService.viewProduct(id);
        return product;
    }
}


@RestControllerAdvice(basePackages = {"com.acmepetsupplies.controller"})
public class RestAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(
            MethodParameter returnType,
            Class<? extends HttpMessageConverter<?>> aClass) {

        return !returnType.getGenericParameterType().equals(ResultVO.class);
    }

    @Override
    public Object beforeBodyWrite(
            Object data,
            MethodParameter returnType,
            MediaType mediaType,
            Class<? extends HttpMessageConverter<?>> aClass,
            ServerHttpRequest request,
            ServerHttpResponse response) {
        if (returnType.getGenericParameterType().equals(String.class)) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                return objectMapper.writeValueAsString(new ResultVO(data));
            } catch (JsonProcessingException e) {
                throw new RuntimeException("返回String类型错误");
            }
        }

        return new ResultVO(data);
    }
}
"responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ResultVO<Product>"
                }
              }
            }
          },
...
"ResultVO<Product>": {
        "type": "object",
        "properties": {
          "status": {
            "type": "integer",
            "description": "200: ok; others: failed",
            "format": "int32"
          },
          "errorMessage": {
            "type": "string",
            "description": "error message"
          },
          "data": {
            "$ref": "#/components/schemas/Product"
          }
        }
      }

org.openapitools.codegen.SpecValidationException: There were issues with the specification. The option can be disabled via validateSpec (Maven/Gradle) or --skip-validate-spec (CLI).
| Error count: 1, Warning count: 0
Errors:
-components.schemas.Schema name ResultVO doesn't adhere to regular expression ^[a-zA-Z0-9.-_]+$

at org.openapitools.codegen.config.CodegenConfigurator.toContext (CodegenConfigurator.java:604)

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 generated OpenAPI schema name ResultVO and the validation failure reported from CodegenConfigurator.toContext. Reproduce the controller and ResponseBodyAdvice example, then trace how generic response types become component names. Done means the generated specification passes validation without a schema name that violates the stated regular expression.

Written by the indexing model from the issue text.

Assessment

Tech stack
java, openapi, spring-boot
Domain
api, tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.