-1

I use Java 8, Spring Boot 2.0, JUnit4. I try to make a proper documentation with Spring Auto REST Docs. Here is my dto:

@Data
@NoArgsConstructor
public class ESLogRequestDTO {

    /**
     * Дата начала поиска
     */
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSX")
    private Date rangeFrom;

    /**
     * Дата конца поиска
     */
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSX")
    private Date rangeTo;

    /**
     * Название сообщения(для отображения в таблице логов)
     */
    private String header;

    /**
     * Тип записи (техническое или бизнес-сообщение)
     */
    private String type;

    /**
     * Текст сообщения (отображается в детальной информации)
     */
    private String message;

    /**
     * Уровни логирования (TRACE, DEBUG, INFO, WARN, ERROR, FATAL)
     */
    private Set<String> levels;

    /**
     * Имя ноды, из которой добавлена запись
     */
    private String node;

    /**
     * Система, из которой получена запись
     */
    private String system;

    /**
     * Система, из которой получена запись
     */
    private String version;

    /**
     * Сервис системы, из которой получена запись
     */
    private String service;

    /**
     * Модуль системы, из которой получена запись
     */
    private String module;

    /**
     * Подмодуль системы, из которой получена запись
     */
    private String submodule;

    /**
     * Нить системы, из которой получена запись
     */
    private String thread;

    /**
     * Операция, которая выполнялась в системе, из которой получена запись
     */
    private String operation;

    /**
     * ID сессии, в рамках которой была сделана запись
     */
    private String requestId;

    /**Тип метрики (duration, quantity, quality)*/
    private String metricType;

    /** Значение метрики начала поиска*/
    private Long valueFrom;

    /** Значение метрики конца поиска*/
    private Long valueTo;

}

Here is my controller method:

 /**
     * Download logs to .xls file. Request parameters are included in ESLogRequestDTO
     * @param esLogRequest request params
     * @param response
     * @throws NoConnectionException
     * @throws IOException
     */
    @PostMapping("/download")
    public void exportLogs(@Valid @RequestBody ESLogRequestDTO esLogRequest,
                           HttpServletResponse response) throws NoConnectionException, IOException {
        Set<ESLogDTO> allLogsByParameters = elasticUIService.
                findAllLogsByParameters(esLogRequest);

        ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
        Workbook workbook = excelWriter.createXlsx(allLogsByParameters);
        workbook.write(outByteStream);
        byte[] outArray = outByteStream.toByteArray();

        response.setContentType("application/ms-excel");
        response.setContentLength(outArray.length);
        response.setHeader("Expires:", "0"); // eliminates browser caching
        response.setHeader("Content-Disposition", "attachment; filename=testxls.xlsx");

        OutputStream outStream = response.getOutputStream();
        outStream.write(outArray);
        outStream.flush();
        workbook.close();
        return;
    }

I finally here is my test:

@Test
    public void downloadLogs() throws Exception {

        when(elasticUIService.findAllLogsByParameters(any()))
                .thenReturn(getLogs());
        when(excelWriter.createXlsx(any()))
                .thenReturn(getWorkbook());

        when(esRequestDTOValidator.supports(any()))
                .thenReturn(true);

        mockMvc.perform(post("/api/logs/download")
                .contentType(CONTENT_TYPE)
                .content(searchRequest)
                .accept(CONTENT_TYPE)
                .header("Authorization", "Bearer {access-token}")
        )

                .andExpect(status().isOk())
                .andDo(MockMvcRestDocumentation.document(CLASS_NAME_METHOD_NAME))
                .andExpect(content().contentType("application/ms-excel"));
    }

    private Workbook getWorkbook() {
        return new XSSFWorkbook();
    }


    private Set<ESLogDTO> getLogs() {
        return new LinkedHashSet<ESLogDTO>() {
            {
                add(new ESLogDTO());
            }
        };
    }

@Rule
    public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation();

    @Before
    public void setUp() throws Exception {
        this.mockMvc = MockMvcBuilders
                .webAppContextSetup(context)
                .alwaysDo(JacksonResultHandlers.prepareJackson(objectMapper))
                .alwaysDo(MockMvcRestDocumentation.document("{class-name}/{method-name}",
                        Preprocessors.preprocessRequest(),
                        Preprocessors.preprocessResponse(
                                ResponseModifyingPreprocessors.replaceBinaryContent(),
                                ResponseModifyingPreprocessors.limitJsonArrayLength(objectMapper),
                                Preprocessors.prettyPrint())))
                .apply(MockMvcRestDocumentation.documentationConfiguration(restDocumentation)
                        .uris()
                        .withScheme("http")
                        .withHost("localhost")
                        .withPort(8081)
                        .and().snippets()
                        .withDefaults(CliDocumentation.curlRequest(),
                                HttpDocumentation.httpRequest(),
                                HttpDocumentation.httpResponse(),
                                AutoDocumentation.requestFields(),
                                AutoDocumentation.responseFields(),
                                AutoDocumentation.pathParameters(),
                                AutoDocumentation.requestParameters(),
                                AutoDocumentation.description(),
                                AutoDocumentation.methodAndPath(),
                                AutoDocumentation.section()))
                .build();
    }

    String searchRequest = "{\n" +
            "\t            \"levels\": [\"INFO\"],\n" +
            "                    \"module\": \"test module\",\n" +
            "                    \"version\": \"version 1\",\n" +
            "                    \"thread\": \"test thread\",\n" +
            "                    \"requestId\": \"1\",\n" +
            "                    \"message\": \"test message 3\",\n" +
            "                    \"rangeFrom\": \"2018-02-26T07:02:50.000Z\",\n" +
            "                    \"rangeTo\": \"2018-03-05T07:02:50.000Z\",\n" +
            "                    \"node\": \"first node\",\n" +
            "                    \"system\": \"super system 1\",\n" +
            "                    \"header\": \"test\",\n" +
            "                    \"submodule\": \"test submodule\",\n" +
            "                    \"operation\": \"some operation\",\n" +
            "                    \"service\": \"some service\",\n" +
            "                    \"type\": \"some type\",\n" +
            "                    \"metricType\": \"duration\",\n" +
            "                    \"valueFrom\":400,\n" +
            "                    \"valueTo\":600\n" +
            "}";

So, the problem is that in my documentation fields Date rangeFrom and Date rangeTo in Request fields have String type but not Date. Also, in Request fields I don't have any description of my dto fields. Here my rest docs plugins in maven:

<!-- RestDocs -->
            <plugin>
                <groupId>org.asciidoctor</groupId>
                <artifactId>asciidoctor-maven-plugin</artifactId>
                <version>1.5.3</version>
                <executions>
                    <execution>
                        <id>generate-docs</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>process-asciidoc</goal>
                        </goals>
                        <configuration>
                            <backend>html</backend>
                            <doctype>book</doctype>
                        </configuration>
                    </execution>
                </executions>
                <dependencies>
                    <dependency>
                        <groupId>org.springframework.restdocs</groupId>
                        <artifactId>spring-restdocs-asciidoctor</artifactId>
                        <version>2.0.1.RELEASE</version>
                    </dependency>
                </dependencies>
            </plugin>

            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.7</version>
                <executions>
                    <execution>
                        <id>copy-resources</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>
                                src/main/docs/asciidoc
                            </outputDirectory>
                            <resources>
                                <resource>
                                    <directory>
                                        target/generated-docs
                                    </directory>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <!-- RestDocs -->
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <includes>
                        <include>**/*Test.java</include>
                    </includes>
                    <systemPropertyVariables>
                        <org.springframework.restdocs.outputDir>
                            ${project.build.directory}/generated-snippets
                        </org.springframework.restdocs.outputDir>
                        <org.springframework.restdocs.javadocJsonDir>
                            ${project.build.directory}/generated-javadoc-json
                        </org.springframework.restdocs.javadocJsonDir>
                    </systemPropertyVariables>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-javadoc-plugin</artifactId>
                <extensions>true</extensions>
                <executions>
                    <execution>
                        <id>generate-javadoc-json</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>javadoc-no-fork</goal>
                        </goals>
                        <configuration>
                            <doclet>capital.scalable.restdocs.jsondoclet.ExtractDocumentationAsJsonDoclet</doclet>
                            <docletArtifact>
                                <groupId>capital.scalable</groupId>
                                <artifactId>spring-auto-restdocs-json-doclet</artifactId>
                                <version>2.0.1</version>
                            </docletArtifact>
                            <destDir>generated-javadoc-json</destDir>
                            <reportOutputDirectory>${project.build.directory}</reportOutputDirectory>
                            <useStandardDocletOptions>false</useStandardDocletOptions>
                            <show>package</show>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

        </plugins>
4

1 回答 1

0

这是因为日期对象被序列化为字符串。文档中根本没有日期类型。看枚举 JsonFieldType

于 2018-07-11T13:29:27.810 回答