Используйте Enunciate для документирования конечной точки, возвращающей двоичный файл (image / png) - PullRequest
0 голосов
/ 06 июня 2018

Я использую Enunciate для документирования службы REST, написанной с использованием spring-webmvc.Некоторые из конечных точек возвращают изображения.(Пожалуйста, игнорируйте тот факт, что эти изображения будут лучше обслуживаться другим процессом, таким как nginx или веб-сервер apache.)

Я пытаюсь настроить Enunciate для документирования следующей функции, но я не знаю, как это сделать:

  • аннотируйте этот метод, чтобы документально подтвердить, что он возвращает двоичный файл (обычно png, но в будущем запрашивающая сторона сможет запросить jpg или png)
  • приведите примерпоказывая "/ hcm? empl_id = 12345".И @DocumentationExample в методе, и @DocumentationExample в emplId игнорируются.

Возможно ли документировать это с помощью Enunciate?Нужно ли что-то включать?Я начинаю думать, что Enunciate просто не будет делать то, что мне поручено.

/**
 * Returns the HCM photo (image/png) for the staff member with the specified empl_id. If no such
 * image exists, return a 404.
 *
 * @pathExample /hcm?id=12345
 * 
 * @param idType currently only supports "hcm".
 *
 * @param emplId is the HCM EMPLID or the Active Directory EmployeeNumber for a given staff
 *        member
 *
 * @throws IOException when there is a problem accessing the image.
 */

@Override
@GetMapping(value = "/hcm", produces = {MediaType.IMAGE_PNG_VALUE})
@DocumentationExample(value = "/hcm?empl_id=12345")
public void getHcmPhoto(
        @RequestParam(value = "id_type", required = false, defaultValue = "hcm") String idType,
        @DocumentationExample(value = "12345")
        @RequestParam("empl_id") String emplId,
        HttpServletResponse response) throws IOException {
    logger.trace("/hcm call made for emplHcmId: {} {}", idType, emplId);
    final String emplHcmId = getHcmId(idType, emplId);

    if (emplHcmId == null) {
        response.setStatus(HttpStatus.NOT_FOUND.value());
        return;
    }

    File fileToSent = new File(pathToImages, emplHcmId + ".png");
    if (!fileToSend.exists()) {
        logger.debug("Photo {} does not exist", fileToSend.getAbsolutePath());
        response.setStatus(HttpStatus.NOT_FOUND.value());
        return;
    }

    try (InputStream in = new FileInputStream(fileToSend)) {
        logger.trace("Photo {} found", fileToSend.getAbsolutePath());
        response.setContentType(MediaType.IMAGE_PNG_VALUE);
        IOUtils.copy(in, response.getOutputStream());
    }
    catch (IOException ioe) {
        logger.error("Could not send {}: {}", fileToSend.getName(), ioe.getMessage(), ioe);
        throw ioe;
    }
}

Я строю с Maven.Я создаю исходные файлы jar и ссылаюсь на них в файле .war

<plugin>
    <groupId>com.webcohesion.enunciate</groupId>
    <artifactId>enunciate-maven-plugin</artifactId>
    <version>${enunciate.version}</version>
    <executions>
        <execution>
            <id>assemble</id>
            <goals>
                <goal>assemble</goal>
            </goals>
            <configuration>
                <sourcepath-includes>
                    <include pattern="com.foo.**">
                        <!-- configure Enunciate to look for the source jars for all dependencies 
                            in the "com.foo.domain" groupId. -->
                        <groupId>com.foo.staff</groupId>
                        <artifactId>com.foo.staff.photo.controller</artifactId>
                    </include>
                </sourcepath-includes>
                <!-- but exclude com.foo.domain:domain-utils <sourcepath-excludes> <exclude>
                        <groupId>com.foo.domain</groupId> <artifactId>domain-utils</artifactId>
                    </exclude> </sourcepath-excludes> -->
                <docsDir>${project.build.directory}/docs</docsDir>
            </configuration>
        </execution>
    </executions>
</plugin>

Мой файл enunciate.xml содержит

<?xml version="1.0" encoding="UTF-8"?>
<enunciate xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="http://enunciate.webcohesion.com/schemas/enunciate-1.27.xsd">

<!-- 
    <facets>
        <exclude name="internal_api" />
    </facets>
 -->

    <api-classes>
        <include pattern="com.foo.**" />
        <exclude pattern="org.springframework.**" />
    </api-classes>


    <modules>
        <docs docsDir="target/docs" title="Staff Photo REST API"/>
        <spring-web />
    </modules>

</enunciate>

1 Ответ

0 голосов
/ 09 июня 2018

Я решил эту проблему, возвращая ResponseEntity вместо возврата void и манипулируя HttpServletResponse.Т.е.

@Override
@GetMapping(value = "/hcm", produces = {MediaType.IMAGE_PNG_VALUE})
public ResponseEntity<Resource> getHcmPhoto(
        @RequestParam(value = "id_type", required = false, defaultValue = "hcm") String idType,
        @RequestParam("empl_id") String emplId) throws IOException {
    logger.trace("/hcm call made for emplHcmId: {} {}", idType, emplId);
    final String emplHcmId = getHcmId(idType, emplId);

    HttpHeaders headers = new HttpHeaders();

    if (emplHcmId == null) {
        return new ResponseEntity<>(null, headers, HttpStatus.NOT_FOUND);
    }

    File hcmPhoto = getHcmPhotoFile(emplHcmId);
    if (hcmPhoto == null) {
        return new ResponseEntity<>(null, headers, HttpStatus.NOT_FOUND);
    }

    return new ResponseEntity<>(new org.springframework.core.io.FileUrlResource(hcmPhoto.toURI().toURL()),
            headers, HttpStatus.OK);
}

В целом, это кажется лучше как с точки зрения того, как Enunciate документирует это, так и с точки зрения чтения кода.Win-Win!

...