From 798767c08283a454ae03543c4f59e8049a25da21 Mon Sep 17 00:00:00 2001 From: Zach Date: Fri, 12 Jun 2026 00:24:51 -0400 Subject: [PATCH] perf(download): stream all book downloads via `StreamingResponseBody` (#1722) --- .../controller/AdditionalFileController.java | 4 +- .../booklore/controller/BookController.java | 11 +- .../booklore/controller/KomgaController.java | 3 +- .../booklore/controller/OpdsController.java | 3 +- .../service/book/BookDownloadService.java | 183 ++++++++---------- .../booklore/service/book/BookService.java | 8 +- .../service/file/AdditionalFileService.java | 38 ++-- .../service/AdditionalFileServiceTest.java | 8 +- .../service/book/BookServiceTest.java | 5 +- 9 files changed, 119 insertions(+), 144 deletions(-) diff --git a/backend/src/main/java/org/booklore/controller/AdditionalFileController.java b/backend/src/main/java/org/booklore/controller/AdditionalFileController.java index de103ee17..d5a8649d2 100644 --- a/backend/src/main/java/org/booklore/controller/AdditionalFileController.java +++ b/backend/src/main/java/org/booklore/controller/AdditionalFileController.java @@ -11,9 +11,9 @@ import org.booklore.service.book.BookFileDetachmentService; import org.booklore.service.file.AdditionalFileService; import org.booklore.service.upload.FileUploadService; import lombok.AllArgsConstructor; -import org.springframework.core.io.Resource; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @@ -81,7 +81,7 @@ public class AdditionalFileController { ) @GetMapping("/{fileId}/download") @CheckBookAccess(bookIdParam = "bookId") - public ResponseEntity downloadAdditionalFile( + public ResponseEntity downloadAdditionalFile( @PathVariable Long bookId, @PathVariable Long fileId) throws IOException { return additionalFileService.downloadAdditionalFile(bookId, fileId); diff --git a/backend/src/main/java/org/booklore/controller/BookController.java b/backend/src/main/java/org/booklore/controller/BookController.java index 173f78853..d007dca33 100644 --- a/backend/src/main/java/org/booklore/controller/BookController.java +++ b/backend/src/main/java/org/booklore/controller/BookController.java @@ -32,7 +32,6 @@ import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; import jakarta.validation.Valid; import jakarta.validation.constraints.Max; import jakarta.validation.constraints.Min; @@ -43,6 +42,7 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; @@ -189,7 +189,7 @@ public class BookController { @GetMapping("/{bookId}/download") @PreAuthorize("@securityUtil.canDownload() or @securityUtil.isAdmin()") @CheckBookAccess(bookIdParam = "bookId") - public ResponseEntity downloadBook(@Parameter(description = "ID of the book to download") @PathVariable("bookId") Long bookId) { + public ResponseEntity downloadBook(@Parameter(description = "ID of the book to download") @PathVariable("bookId") Long bookId) { return bookService.downloadBook(bookId); } @@ -202,10 +202,9 @@ public class BookController { @GetMapping("/{bookId}/download-all") @PreAuthorize("@securityUtil.canDownload() or @securityUtil.isAdmin()") @CheckBookAccess(bookIdParam = "bookId") - public void downloadAllBookFiles( - @Parameter(description = "ID of the book") @PathVariable("bookId") Long bookId, - HttpServletResponse response) { - bookService.downloadAllBookFiles(bookId, response); + public ResponseEntity downloadAllBookFiles( + @Parameter(description = "ID of the book") @PathVariable("bookId") Long bookId) { + return bookService.downloadAllBookFiles(bookId); } @Operation(summary = "Get viewer settings", description = "Retrieve viewer settings for a specific book file.") diff --git a/backend/src/main/java/org/booklore/controller/KomgaController.java b/backend/src/main/java/org/booklore/controller/KomgaController.java index f1b284723..3b88f5025 100644 --- a/backend/src/main/java/org/booklore/controller/KomgaController.java +++ b/backend/src/main/java/org/booklore/controller/KomgaController.java @@ -22,6 +22,7 @@ import org.booklore.service.komga.KomgaService; import org.booklore.service.opds.OpdsUserV2Service; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.core.io.Resource; +import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; @@ -185,7 +186,7 @@ public class KomgaController { @Operation(summary = "Download book file") @GetMapping("/v1/books/{bookId}/file") - public ResponseEntity downloadBook( + public ResponseEntity downloadBook( @Parameter(description = "Book ID") @PathVariable Long bookId) { validateBookContentAccess(bookId); diff --git a/backend/src/main/java/org/booklore/controller/OpdsController.java b/backend/src/main/java/org/booklore/controller/OpdsController.java index 369da77a6..53ad2fbec 100644 --- a/backend/src/main/java/org/booklore/controller/OpdsController.java +++ b/backend/src/main/java/org/booklore/controller/OpdsController.java @@ -20,6 +20,7 @@ import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @@ -48,7 +49,7 @@ public class OpdsController { @ApiResponse(responseCode = "404", description = "Book not found") }) @GetMapping("/{bookId}/download") - public ResponseEntity downloadBook( + public ResponseEntity downloadBook( @Parameter(description = "ID of the book to download") @PathVariable("bookId") Long bookId, @Parameter(description = "Optional ID of a specific file format to download") @RequestParam(required = false) Long fileId) { opdsBookService.validateBookContentAccess(bookId, getOpdsUserId()); diff --git a/backend/src/main/java/org/booklore/service/book/BookDownloadService.java b/backend/src/main/java/org/booklore/service/book/BookDownloadService.java index 28cee5f4e..8f6b643ab 100644 --- a/backend/src/main/java/org/booklore/service/book/BookDownloadService.java +++ b/backend/src/main/java/org/booklore/service/book/BookDownloadService.java @@ -15,14 +15,13 @@ import org.booklore.service.kobo.CbxConversionService; import org.booklore.service.kobo.KepubConversionService; import org.booklore.service.kobo.KoboSpanMapService; import org.booklore.util.FileUtils; -import org.springframework.core.io.FileSystemResource; -import org.springframework.core.io.Resource; import org.springframework.http.ContentDisposition; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.util.FileSystemUtils; +import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody; import java.io.File; import java.io.IOException; @@ -37,8 +36,6 @@ import java.util.List; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; -import java.io.ByteArrayOutputStream; -import org.springframework.core.io.ByteArrayResource; @Slf4j @AllArgsConstructor @@ -54,7 +51,7 @@ public class BookDownloadService { private final KoboSpanMapService koboSpanMapService; private final AppSettingService appSettingService; - public ResponseEntity downloadBook(Long bookId) { + public ResponseEntity downloadBook(Long bookId) { try { BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId) .orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); @@ -75,26 +72,14 @@ public class BookDownloadService { return downloadFolderAsZip(file, primaryFile.getFileName()); } - File bookFile = file.toFile(); - - // Use FileSystemResource which properly handles file resources and closing - Resource resource = new FileSystemResource(bookFile); - - return ResponseEntity.ok() - .contentType(MediaType.APPLICATION_OCTET_STREAM) - .contentLength(bookFile.length()) - .header(HttpHeaders.CONTENT_DISPOSITION, getContentDisposition(file)) - .header(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate") - .header(HttpHeaders.PRAGMA, "no-cache") - .header(HttpHeaders.EXPIRES, "0") - .body(resource); + return streamFile(file); } catch (Exception e) { log.error("Failed to download book {}: {}", bookId, e.getMessage(), e); throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId); } } - public ResponseEntity downloadBookFile(Long bookId, Long fileId) { + public ResponseEntity downloadBookFile(Long bookId, Long fileId) { try { BookFileEntity bookFileEntity = bookFileRepository.findByIdWithBookAndLibraryPath(fileId) .orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException(fileId)); @@ -116,23 +101,29 @@ public class BookDownloadService { return downloadFolderAsZip(file, bookFileEntity.getFileName()); } - File bookFile = file.toFile(); - Resource resource = new FileSystemResource(bookFile); - - return ResponseEntity.ok() - .contentType(MediaType.APPLICATION_OCTET_STREAM) - .contentLength(bookFile.length()) - .header(HttpHeaders.CONTENT_DISPOSITION, getContentDisposition(file)) - .header(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate") - .header(HttpHeaders.PRAGMA, "no-cache") - .header(HttpHeaders.EXPIRES, "0") - .body(resource); + return streamFile(file); } catch (Exception e) { log.error("Failed to download book file {}: {}", fileId, e.getMessage(), e); throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(fileId); } } + private ResponseEntity streamFile(Path file) { + StreamingResponseBody body = outputStream -> { + try (InputStream in = Files.newInputStream(file)) { + in.transferTo(outputStream); + } + }; + return ResponseEntity.ok() + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .contentLength(file.toFile().length()) + .header(HttpHeaders.CONTENT_DISPOSITION, getContentDisposition(file)) + .header(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate") + .header(HttpHeaders.PRAGMA, "no-cache") + .header(HttpHeaders.EXPIRES, "0") + .body(body); + } + private String getContentDisposition(File file) { return getContentDisposition(file.getName()); } @@ -151,7 +142,7 @@ public class BookDownloadService { .toString(); } - public void downloadAllBookFiles(Long bookId, HttpServletResponse response) { + public ResponseEntity downloadAllBookFiles(Long bookId) { BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId) .orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); @@ -173,77 +164,71 @@ public class BookDownloadService { // For folder-based audiobooks, let it fall through to ZIP creation if (!singleFile.isFolderBased() || !Files.isDirectory(filePath)) { - File file = filePath.toFile(); - setResponseHeaders(response, file); - streamFileToResponse(file, response); - return; + return streamFile(filePath); } } - // Sort files by filename for consistent ordering - allFiles.sort(Comparator.comparing(BookFileEntity::getFileName)); + // Resolve entity data upfront so streaming only handles file I/O + List sources = allFiles.stream() + .sorted(Comparator.comparing(BookFileEntity::getFileName)) + .map(f -> new ZipSource( + FileUtils.requirePathWithinBase(f.getFullFilePath(), libraryRoot), + f.getFileName(), + f.isFolderBased())) + .toList(); - // Create ZIP with all files String bookTitle = bookEntity.getMetadata() != null && bookEntity.getMetadata().getTitle() != null ? bookEntity.getMetadata().getTitle() : "book-" + bookId; - String safeTitle = NON_ALPHANUMERIC_PATTERN.matcher(bookTitle).replaceAll("_"); - String zipFileName = safeTitle + ".zip"; + String zipFileName = NON_ALPHANUMERIC_PATTERN.matcher(bookTitle).replaceAll("_") + ".zip"; - response.setContentType("application/zip"); + StreamingResponseBody body = outputStream -> { + try (ZipOutputStream zos = new ZipOutputStream(outputStream)) { + for (ZipSource source : sources) { + if (!Files.exists(source.path())) { + log.warn("Skipping missing file during ZIP creation: {}", source.path()); + continue; + } - response.setHeader(HttpHeaders.CONTENT_DISPOSITION, getContentDisposition(zipFileName)); - - try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) { - for (BookFileEntity bookFile : allFiles) { - Path filePath = FileUtils.requirePathWithinBase(bookFile.getFullFilePath(), libraryRoot); - - if (!Files.exists(filePath)) { - log.warn("Skipping missing file during ZIP creation: {}", filePath); - continue; - } - - // Handle folder-based audiobooks - add all files from the folder - if (bookFile.isFolderBased() && Files.isDirectory(filePath)) { - String folderPrefix = bookFile.getFileName() + "/"; - try (var audioFiles = Files.list(filePath)) { - for (Path audioFile : audioFiles - .filter(Files::isRegularFile) - .sorted(Comparator.comparing(p -> p.getFileName().toString())) - .toList()) { - String entryName = folderPrefix + audioFile.getFileName().toString(); - ZipEntry zipEntry = new ZipEntry(entryName); - zipEntry.setSize(Files.size(audioFile)); - zos.putNextEntry(zipEntry); - - try (InputStream fis = Files.newInputStream(audioFile)) { - fis.transferTo(zos); + // Handle folder-based audiobooks - add all files from the folder + if (source.folderBased() && Files.isDirectory(source.path())) { + String folderPrefix = source.name() + "/"; + try (var audioFiles = Files.list(source.path())) { + for (Path audioFile : audioFiles + .filter(Files::isRegularFile) + .sorted(Comparator.comparing(p -> p.getFileName().toString())) + .toList()) { + addZipEntry(zos, folderPrefix + audioFile.getFileName().toString(), audioFile); } - - zos.closeEntry(); } + } else { + addZipEntry(zos, source.name(), source.path()); } - } else { - // Regular file - ZipEntry zipEntry = new ZipEntry(bookFile.getFileName()); - zipEntry.setSize(Files.size(filePath)); - zos.putNextEntry(zipEntry); - - try (InputStream fis = Files.newInputStream(filePath)) { - fis.transferTo(zos); - } - - zos.closeEntry(); } } - zos.finish(); - response.getOutputStream().flush(); + log.info("Successfully streamed ZIP for book {} with {} files", bookId, sources.size()); + }; - log.info("Successfully created and streamed ZIP for book {} with {} files", bookId, allFiles.size()); - } catch (IOException e) { - log.error("Failed to create ZIP for book {}: {}", bookId, e.getMessage(), e); - throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId); + return ResponseEntity.ok() + .contentType(MediaType.valueOf("application/zip")) + .header(HttpHeaders.CONTENT_DISPOSITION, getContentDisposition(zipFileName)) + .header(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate") + .header(HttpHeaders.PRAGMA, "no-cache") + .header(HttpHeaders.EXPIRES, "0") + .body(body); + } + + private void addZipEntry(ZipOutputStream zos, String entryName, Path file) throws IOException { + ZipEntry zipEntry = new ZipEntry(entryName); + zipEntry.setSize(Files.size(file)); + zos.putNextEntry(zipEntry); + try (InputStream in = Files.newInputStream(file)) { + in.transferTo(zos); } + zos.closeEntry(); + } + + private record ZipSource(Path path, String name, boolean folderBased) { } public void downloadKoboBook(Long bookId, HttpServletResponse response) { @@ -333,36 +318,28 @@ public class BookDownloadService { } } - private ResponseEntity downloadFolderAsZip(Path folderPath, String folderName) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - try (ZipOutputStream zos = new ZipOutputStream(baos)) { - // Get all files in the folder, sorted by name - try (var files = Files.list(folderPath)) { + private ResponseEntity downloadFolderAsZip(Path folderPath, String folderName) { + StreamingResponseBody body = outputStream -> { + try (ZipOutputStream zos = new ZipOutputStream(outputStream); + var files = Files.list(folderPath)) { + // Get all files in the folder, sorted by name for (Path audioFile : files .filter(Files::isRegularFile) .sorted(Comparator.comparing(p -> p.getFileName().toString())) .toList()) { - ZipEntry entry = new ZipEntry(audioFile.getFileName().toString()); - zos.putNextEntry(entry); + zos.putNextEntry(new ZipEntry(audioFile.getFileName().toString())); Files.copy(audioFile, zos); zos.closeEntry(); } } - } - - byte[] zipBytes = baos.toByteArray(); - Resource resource = new ByteArrayResource(zipBytes); - - String zipFileName = folderName + ".zip"; + }; return ResponseEntity.ok() .contentType(MediaType.valueOf("application/zip")) - .header(HttpHeaders.CONTENT_DISPOSITION, getContentDisposition(zipFileName)) - .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(zipBytes.length)) + .header(HttpHeaders.CONTENT_DISPOSITION, getContentDisposition(folderName + ".zip")) .header(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate") .header(HttpHeaders.PRAGMA, "no-cache") .header(HttpHeaders.EXPIRES, "0") - .body(resource); + .body(body); } } diff --git a/backend/src/main/java/org/booklore/service/book/BookService.java b/backend/src/main/java/org/booklore/service/book/BookService.java index fd2ab2e64..75abaa31a 100644 --- a/backend/src/main/java/org/booklore/service/book/BookService.java +++ b/backend/src/main/java/org/booklore/service/book/BookService.java @@ -1,7 +1,6 @@ package org.booklore.service.book; import jakarta.persistence.EntityManager; -import jakarta.servlet.http.HttpServletResponse; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.booklore.config.security.service.AuthenticationService; @@ -31,6 +30,7 @@ import org.springframework.core.io.UrlResource; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.*; +import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -346,12 +346,12 @@ public class BookService { } } - public ResponseEntity downloadBook(Long bookId) { + public ResponseEntity downloadBook(Long bookId) { return bookDownloadService.downloadBook(bookId); } - public void downloadAllBookFiles(Long bookId, HttpServletResponse response) { - bookDownloadService.downloadAllBookFiles(bookId, response); + public ResponseEntity downloadAllBookFiles(Long bookId) { + return bookDownloadService.downloadAllBookFiles(bookId); } public ResponseEntity getBookContent(long bookId) { diff --git a/backend/src/main/java/org/booklore/service/file/AdditionalFileService.java b/backend/src/main/java/org/booklore/service/file/AdditionalFileService.java index 7ef4a426a..bf83e22fa 100644 --- a/backend/src/main/java/org/booklore/service/file/AdditionalFileService.java +++ b/backend/src/main/java/org/booklore/service/file/AdditionalFileService.java @@ -8,17 +8,15 @@ import org.booklore.repository.BookAdditionalFileRepository; import org.booklore.service.monitoring.MonitoringRegistrationService; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.springframework.core.io.ByteArrayResource; -import org.springframework.core.io.Resource; -import org.springframework.core.io.UrlResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody; -import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -96,7 +94,7 @@ public class AdditionalFileService { } } - public ResponseEntity downloadAdditionalFile(Long bookId, Long fileId) throws IOException { + public ResponseEntity downloadAdditionalFile(Long bookId, Long fileId) throws IOException { Optional fileOpt = additionalFileRepository.findByIdAndBookIdWithBookAndLibraryPath(fileId, bookId); if (fileOpt.isEmpty()) { return ResponseEntity.notFound().build(); @@ -115,7 +113,11 @@ public class AdditionalFileService { return downloadFolderAsZip(file, filePath); } - Resource resource = new UrlResource(filePath.toUri()); + StreamingResponseBody body = outputStream -> { + try (InputStream in = Files.newInputStream(filePath)) { + in.transferTo(outputStream); + } + }; String encodedFilename = URLEncoder.encode(file.getFileName(), StandardCharsets.UTF_8).replace("+", "%20"); String fallbackFilename = NON_ASCII.matcher(file.getFileName()).replaceAll("_"); @@ -124,29 +126,24 @@ public class AdditionalFileService { return ResponseEntity.ok() .contentType(MediaType.APPLICATION_OCTET_STREAM) .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition) - .body(resource); + .body(body); } - private ResponseEntity downloadFolderAsZip(BookFileEntity file, Path folderPath) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - try (ZipOutputStream zos = new ZipOutputStream(baos)) { - // Get all files in the folder, sorted by name - try (var files = Files.list(folderPath)) { + private ResponseEntity downloadFolderAsZip(BookFileEntity file, Path folderPath) { + StreamingResponseBody body = outputStream -> { + try (ZipOutputStream zos = new ZipOutputStream(outputStream); + var files = Files.list(folderPath)) { + // Get all files in the folder, sorted by name for (Path audioFile : files .filter(Files::isRegularFile) .sorted(Comparator.comparing(p -> p.getFileName().toString())) .toList()) { - ZipEntry entry = new ZipEntry(audioFile.getFileName().toString()); - zos.putNextEntry(entry); + zos.putNextEntry(new ZipEntry(audioFile.getFileName().toString())); Files.copy(audioFile, zos); zos.closeEntry(); } } - } - - byte[] zipBytes = baos.toByteArray(); - Resource resource = new ByteArrayResource(zipBytes); + }; String zipFileName = file.getFileName() + ".zip"; String encodedFilename = URLEncoder.encode(zipFileName, StandardCharsets.UTF_8).replace("+", "%20"); @@ -157,8 +154,7 @@ public class AdditionalFileService { return ResponseEntity.ok() .contentType(MediaType.valueOf("application/zip")) .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition) - .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(zipBytes.length)) - .body(resource); + .body(body); } private void validateAdditionalFile(BookFileEntity file, BookEntity book) { diff --git a/backend/src/test/java/org/booklore/service/AdditionalFileServiceTest.java b/backend/src/test/java/org/booklore/service/AdditionalFileServiceTest.java index 4ab557820..ba09a5be4 100644 --- a/backend/src/test/java/org/booklore/service/AdditionalFileServiceTest.java +++ b/backend/src/test/java/org/booklore/service/AdditionalFileServiceTest.java @@ -16,7 +16,7 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.core.io.Resource; +import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -231,7 +231,7 @@ class AdditionalFileServiceTest { Long fileId = 1L; when(additionalFileRepository.findByIdAndBookIdWithBookAndLibraryPath(fileId, bookId)).thenReturn(Optional.empty()); - ResponseEntity result = additionalFileService.downloadAdditionalFile(bookId, fileId); + ResponseEntity result = additionalFileService.downloadAdditionalFile(bookId, fileId); assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode()); assertNull(result.getBody()); @@ -257,7 +257,7 @@ class AdditionalFileServiceTest { Path actualPath = entityWithNonExistentFile.getFullFilePath(); filesMock.when(() -> Files.exists(actualPath)).thenReturn(false); - ResponseEntity result = additionalFileService.downloadAdditionalFile(bookId, fileId); + ResponseEntity result = additionalFileService.downloadAdditionalFile(bookId, fileId); assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode()); assertNull(result.getBody()); @@ -277,7 +277,7 @@ class AdditionalFileServiceTest { try (MockedStatic filesMock = mockStatic(Files.class)) { filesMock.when(() -> Files.exists(fileEntity.getFullFilePath())).thenReturn(true); - ResponseEntity result = additionalFileService.downloadAdditionalFile(bookId, fileId); + ResponseEntity result = additionalFileService.downloadAdditionalFile(bookId, fileId); assertEquals(HttpStatus.OK, result.getStatusCode()); assertNotNull(result.getBody()); diff --git a/backend/src/test/java/org/booklore/service/book/BookServiceTest.java b/backend/src/test/java/org/booklore/service/book/BookServiceTest.java index eccd58431..ddbdd38cc 100644 --- a/backend/src/test/java/org/booklore/service/book/BookServiceTest.java +++ b/backend/src/test/java/org/booklore/service/book/BookServiceTest.java @@ -29,6 +29,7 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; +import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody; import org.springframework.core.io.UrlResource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -323,10 +324,10 @@ class BookServiceTest { @Test void downloadBook_delegatesToDownloadService() { - ResponseEntity response = ResponseEntity.ok(mock(Resource.class)); + ResponseEntity response = ResponseEntity.ok(mock(StreamingResponseBody.class)); when(bookDownloadService.downloadBook(1L)).thenReturn(response); - ResponseEntity result = bookService.downloadBook(1L); + ResponseEntity result = bookService.downloadBook(1L); assertEquals(response, result); }