端点“ / api-docs”不适用于自定义GsonHttpMessageConverter

时间:2019-12-18 13:35:00

标签: spring-boot kotlin gson swagger-ui openapi

我从Springfox Swagger迁移到Springdoc OpenApi。我在配置中添加了关于springdoc的几行内容:

springdoc:
  pathsToMatch: /api/**
  packagesToScan: pl.sims.invipoconnector
  api-docs:
    path: /api-docs
  swagger-ui:
    path: /swagger-ui.html

在配置类MainConfig.kt中,我有以下代码:

val customGson: Gson = GsonBuilder()
        .registerTypeAdapter(LocalDateTime::class.java, DateSerializer())
        .registerTypeAdapter(ZonedDateTime::class.java, ZonedDateSerializer())
        .addSerializationExclusionStrategy(AnnotationExclusionStrategy())
        .enableComplexMapKeySerialization()
        .setPrettyPrinting()
        .create()

    override fun configureMessageConverters(converters: MutableList<HttpMessageConverter<*>>) {
        converters.add(GsonHttpMessageConverter(customGson))
    }

当我转到http://localhost:8013/swagger-ui.html(在配置中,我有server.port: 8013)时,页面未重定向到swagger-ui/index.html?url=/api-docs&validatorUrl=。但这不是我的主要问题:)。当我去swagger-ui/index.html?url=/api-docs&validatorUrl=时,页面上显示以下信息:

Unable to render this definition
The provided definition does not specify a valid version field.

Please indicate a valid Swagger or OpenAPI version field. Supported version fields are swagger: "2.0" and those that match openapi: 3.0.n (for example, openapi: 3.0.0).

但是当我转到http://localhost:8013/api-docs时,会得到以下结果:

"{\"openapi\":\"3.0.1\",\"info\":{(...)}}"

我尝试使用默认配置,并注释了configureMessageConverters()方法和\api-docs的结果,现在看起来像普通的JSON:

// 20191218134933
// http://localhost:8013/api-docs

{
  "openapi": "3.0.1",
  "info": {(...)}
}

我记得当我使用Springfox时,序列化出现了问题,我的customGson还有一行:.registerTypeAdapter(Json::class.java, JsonSerializer<Json> { src, _, _ -> JsonParser.parseString(src.value()) })

我想知道我应该有特殊的JsonSerializer。调试后,我的第一个念头是进入OpenApi包中的io.swagger.v3.oas.models类。我在.registerTypeAdapter(OpenAPI::class.java, JsonSerializer<OpenAPI> { _, _, _ -> JsonParser.parseString("") })上添加了以下代码:customGson并没有任何变化...所以,我正在深入研究...

运行Swagger测试后:

@EnableAutoConfiguration
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@ExtendWith(SpringExtension::class)
@ActiveProfiles("test")
class SwaggerIntegrationTest(@Autowired private val mockMvc: MockMvc) {
    @Test
    fun `should display Swagger UI page`() {
        val result = mockMvc.perform(MockMvcRequestBuilders.get("/swagger-ui/index.html"))
                .andExpect(status().isOk)
                .andReturn()

        assertTrue(result.response.contentAsString.contains("Swagger UI"))
    }

    @Disabled("Redirect doesn't work. Check it later")
    @Test
    fun `should display Swagger UI page with redirect`() {
        mockMvc.perform(MockMvcRequestBuilders.get("/swagger-ui.html"))
                .andExpect(status().isOk)
                .andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaType.TEXT_HTML))
    }

    @Test
    fun `should get api docs`() {
        mockMvc.perform(MockMvcRequestBuilders.get("/api-docs"))
                .andExpect(status().isOk)
                .andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
                .andExpect(MockMvcResultMatchers.jsonPath("\$.openapi").exists())
    }
}

我在控制台中看到以下内容:

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /api-docs
       Parameters = {}
          Headers = []
             Body = null
    Session Attrs = {}

Handler:
             Type = org.springdoc.api.OpenApiResource
           Method = org.springdoc.api.OpenApiResource#openapiJson(HttpServletRequest, String)

接下来,我在openapiJson中检查OpenApiResource,然后...

    @Operation(hidden = true)
    @GetMapping(value = API_DOCS_URL, produces = MediaType.APPLICATION_JSON_VALUE)
    public String openapiJson(HttpServletRequest request, @Value(API_DOCS_URL) String apiDocsUrl)
            throws JsonProcessingException {
        calculateServerUrl(request, apiDocsUrl);
        OpenAPI openAPI = this.getOpenApi();
        return Json.mapper().writeValueAsString(openAPI);
    }

好的,杰克逊...我已经@EnableAutoConfiguration(exclude = [(JacksonAutoConfiguration::class)])禁用了杰克逊,因为我(和我的同事)更喜欢GSON,但这并不能解释为什么添加自定义GsonHttpMessageConverter后序列化会出错。我不知道我做了什么坏事。 openapiJson()是终结点,可能有些混乱……我不知道。我什么都不知道您有类似的问题吗?你能给些建议或提示吗?

PS。对不起,我的英语不好:)。

1 个答案:

答案 0 :(得分:1)

我用Java编写的项目也遇到了同样的问题,我刚刚解决了这个问题,方法是定义一个过滤器,以使用Gson格式化springdoc-openapi json文档。我想您可以轻松地将此解决方法移植到Kotlin。

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    ByteResponseWrapper byteResponseWrapper = new ByteResponseWrapper((HttpServletResponse) response);
    ByteRequestWrapper byteRequestWrapper = new ByteRequestWrapper((HttpServletRequest) request);

    chain.doFilter(byteRequestWrapper, byteResponseWrapper);

    String jsonResponse = new String(byteResponseWrapper.getBytes(), response.getCharacterEncoding());

    response.getOutputStream().write((new com.google.gson.JsonParser().parse(jsonResponse).getAsString())
            .getBytes(response.getCharacterEncoding()));
}

@Override
public void destroy() {

}

static class ByteResponseWrapper extends HttpServletResponseWrapper {

    private PrintWriter writer;
    private ByteOutputStream output;

    public byte[] getBytes() {
        writer.flush();
        return output.getBytes();
    }

    public ByteResponseWrapper(HttpServletResponse response) {
        super(response);
        output = new ByteOutputStream();
        writer = new PrintWriter(output);
    }

    @Override
    public PrintWriter getWriter() {
        return writer;
    }

    @Override
    public ServletOutputStream getOutputStream() {
        return output;
    }
}

static class ByteRequestWrapper extends HttpServletRequestWrapper {

    byte[] requestBytes = null;
    private ByteInputStream byteInputStream;


    public ByteRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        InputStream inputStream = request.getInputStream();

        byte[] buffer = new byte[4096];
        int read = 0;
        while ((read = inputStream.read(buffer)) != -1) {
            baos.write(buffer, 0, read);
        }

        replaceRequestPayload(baos.toByteArray());
    }

    @Override
    public BufferedReader getReader() {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() {
        return byteInputStream;
    }

    public void replaceRequestPayload(byte[] newPayload) {
        requestBytes = newPayload;
        byteInputStream = new ByteInputStream(new ByteArrayInputStream(requestBytes));
    }
}

static class ByteOutputStream extends ServletOutputStream {

    private ByteArrayOutputStream bos = new ByteArrayOutputStream();

    @Override
    public void write(int b) {
        bos.write(b);
    }

    public byte[] getBytes() {
        return bos.toByteArray();
    }

    @Override
    public boolean isReady() {
        return false;
    }

    @Override
    public void setWriteListener(WriteListener writeListener) {

    }
}

static class ByteInputStream extends ServletInputStream {

    private InputStream inputStream;

    public ByteInputStream(final InputStream inputStream) {
        this.inputStream = inputStream;
    }

    @Override
    public int read() throws IOException {
        return inputStream.read();
    }

    @Override
    public boolean isFinished() {
        return false;
    }

    @Override
    public boolean isReady() {
        return false;
    }

    @Override
    public void setReadListener(ReadListener readListener) {

    }
}

您还必须只为文档的网址格式注册过滤器。

@Bean
public FilterRegistrationBean<DocsFormatterFilter> loggingFilter() {
    FilterRegistrationBean<DocsFormatterFilter> registrationBean = new FilterRegistrationBean<>();

    registrationBean.setFilter(new DocsFormatterFilter());
    registrationBean.addUrlPatterns("/v3/api-docs");

    return registrationBean;
}