ByteArrayInputStream с Resttemplate - PullRequest
1 голос
/ 20 июня 2020

Мне нужно передать ByteArrayInputStream на веб-уровень. После формирования ByteArrayInputStream я прохожу через RestController в serviceRest, а затем на веб-уровень.

Я экспортирую объекты в .xlsx и возвращаю ByteArrayInputStream

@Override
    public  ByteArrayInputStream exportProjectsToExcel(List<Projects> projectsList) {


        try {
            Workbook workbook = new XSSFWorkbook();

            Sheet sheet = workbook.createSheet("projects");

            Row row = sheet.createRow(0);

            CellStyle headerSellStyle = cellStyle(workbook, IndexedColors.SKY_BLUE);

            Cell cell = row.createCell(0);
            cell.setCellValue("projectId");
            cell.setCellStyle(headerSellStyle);

            cell = row.createCell(1);
            cell.setCellValue("description");
            cell.setCellStyle(headerSellStyle);

            cell = row.createCell(2);
            cell.setCellValue("dateAdded");
            cell.setCellStyle(headerSellStyle);

            for (int i = 0; i < projectsList.size(); i++) {

                Row dataRow = sheet.createRow(i + 1);
                CellStyle bodySellStyle = cellStyle(workbook, IndexedColors.WHITE);

                Cell bodyCell = dataRow.createCell(0);
                bodyCell.setCellValue(projectsList.get(i).getProjectId());
                bodyCell.setCellStyle(bodySellStyle);

                bodyCell = dataRow.createCell(1);
                bodyCell.setCellValue(projectsList.get(i).getDescription());
                bodyCell.setCellStyle(bodySellStyle);

                bodyCell = dataRow.createCell(2);
                bodyCell.setCellValue(projectsList.get(i).getDateAdded().toString());
                bodyCell.setCellStyle(bodySellStyle);
            }
            sheet.autoSizeColumn(0);
            sheet.autoSizeColumn(1);
            sheet.autoSizeColumn(2);

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);

            return new ByteArrayInputStream(outputStream.toByteArray());

        } catch (IOException e) {
            e.printStackTrace();

            return null;
        }
    }

Затем мне нужно передать ByteArrayInputStream через RestController

 @PostMapping(value = "/projectsDownload")
    public ByteArrayInputStream downloadExcelProjects( @RequestBody (required = false) List<Projects> projectsList) throws IOException {

        LOGGER.debug("**************************************************{}", projectsList);

        ByteArrayInputStream stream = excelFileExportService.exportProjectsToExcel(projectsList);

        return stream;
    }


в serviceRest с использованием resttemplate

 @Override
    public ByteArrayInputStream exportProjectsToExcel(List<Projects> projectsList) {

        LOGGER.debug("////////////////////////////////////////////////exportProjectsToExcel({})", projectsList);

        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Collections.singletonList(MediaType.ALL));
        HttpEntity<List> entity = new HttpEntity<>(projectsList, headers);
        ResponseEntity<ByteArrayInputStream> result = restTemplate.postForEntity(url + "/projectsDownload", entity, ByteArrayInputStream.class);
        return result.getBody();
    }

, но у меня есть следующее исключение

19:52:15 [http-nio-8088-exec-9] DEBUG c.e.b.c.r.c.DownloadExcelProjectsController - **************************************************[Projects(projectId=1, description=Create a web application based on SpringJDBC, dateAdded=2019-07-15, fileType=null, multipartFile=null, developers=null), Projects(projectId=2, description=Create a web application based on SpringBoot, dateAdded=2019-08-13, fileType=null, multipartFile=null, developers=null), Projects(projectId=3, description=Create a web application based on Hibernate, dateAdded=2020-01-17, fileType=null, multipartFile=null, developers=null)]
19:52:16 [http-nio-8088-exec-9] DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Using @ExceptionHandler com.epam.brest.courses.rest_app.exception.CustomExceptionHandler#handleException(Exception, WebRequest)
19:52:16 [http-nio-8088-exec-9] DEBUG o.s.w.s.m.m.a.HttpEntityMethodProcessor - No match for [*/*], supported: []
19:52:16 [http-nio-8088-exec-9] DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Resolved [org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class java.io.ByteArrayInputStream]
19:52:16 [http-nio-8088-exec-9] DEBUG o.s.o.j.s.OpenEntityManagerInViewInterceptor - Closing JPA EntityManager in OpenEntityManagerInViewInterceptor
19:52:16 [http-nio-8088-exec-9] DEBUG o.s.w.s.DispatcherServlet - Completed 500 INTERNAL_SERVER_ERROR

Буду признателен за любую помощь. Спасибо.

1 Ответ

1 голос
/ 20 июня 2020

Вы можете преобразовать его в объект ресурса Spring не может преобразовать Bytearrayinputstream при записи объекта, также шаблон rest не может его прочитать, просто передав входной поток.

Попробуйте этот код:

Path path = Paths.get(file.getAbsolutePath());
ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));

    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(resource);




File file = restTemplate.execute(FILE_URL, HttpMethod.GET, null, clientHttpResponse -> {
    File ret = File.createTempFile("download", "tmp");
    StreamUtils.copy(clientHttpResponse.getBody(), new FileOutputStream(ret));
    return ret;
});
 

...