fix(streaming): rewrite file streaming with NIO and HTTP caching (#512)

* fix(streaming): rewrite file streaming with NIO and HTTP caching

* fix(streaming): improve file transfer handling and enhance client disconnect detection

* fix(streaming): improve If-None-Match header evaluation for improved caching

* fix(streaming): improve chapter tracking and loading in audiobook player

* fix(streaming): remove unused imports in audiobook player component

* fix(streaming): improve chapter tracking and state management in audiobook player (again)

* fix: fix merge conflict errors and update code
This commit is contained in:
brios
2026-04-22 17:27:35 -04:00
committed by Zach Yale
parent ba6eb4f64c
commit 5bd2e9ad3f
7 changed files with 526 additions and 158 deletions
@@ -3,21 +3,40 @@ package org.booklore.service;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.booklore.exception.ApiError;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.async.AsyncRequestNotUsableException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.SocketTimeoutException;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Locale;
@Slf4j
@Service
public class FileStreamingService {
private static final int BUFFER_SIZE = 64 * 1024;
private static final DateTimeFormatter HTTP_DATE_FORMAT = DateTimeFormatter
.ofPattern("EEE, dd MMM yyyy HH:mm:ss z", Locale.US)
.withZone(ZoneId.of("GMT"));
/**
* Streams a file with HTTP Range support for seeking.
* Uses Java NIO FileChannel for zero-copy transfer (sendfile) where supported.
* Supports conditional requests via ETag / If-None-Match and If-Range (RFC 7233).
*/
public void streamWithRangeSupport(
Path filePath,
String contentType,
@@ -25,46 +44,63 @@ public class FileStreamingService {
HttpServletResponse response
) throws IOException {
if (!Files.exists(filePath)) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
// Single syscall: existence check + size + last-modified
BasicFileAttributes attrs;
try {
attrs = Files.readAttributes(filePath, BasicFileAttributes.class);
} catch (NoSuchFileException _) {
throw ApiError.FILE_NOT_FOUND.createException(filePath.toString());
}
long fileSize = attrs.size();
Instant lastModified = attrs.lastModifiedTime().toInstant();
String etag = generateETag(fileSize, lastModified);
String rangeHeader = request.getHeader("Range");
// Standard headers for media streaming
response.setHeader("Accept-Ranges", "bytes");
response.setContentType(contentType);
response.setHeader("ETag", etag);
response.setDateHeader("Last-Modified", lastModified.toEpochMilli());
// Allow caching with mandatory revalidation via ETag eliminates
// redundant byte transfers on seeks while keeping access-control checks.
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Content-Disposition", "inline");
// Conditional: If-None-Match, 304
String ifNoneMatch = request.getHeader("If-None-Match");
if (evaluateIfNoneMatch(ifNoneMatch, etag)) {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
long fileSize = Files.size(filePath);
String rangeHeader = request.getHeader("Range");
response.setHeader("Accept-Ranges", "bytes");
response.setHeader("Cache-Control", "no-store");
response.setHeader("Content-Disposition", "inline");
response.setContentType(contentType);
// -------------------------
// HEAD
// -------------------------
// HEAD request 200 with Content-Length, no body
if ("HEAD".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
response.setHeader(
"Content-Range",
"bytes 0-" + (fileSize - 1) + "/" + fileSize
);
response.setStatus(HttpServletResponse.SC_OK);
response.setContentLengthLong(fileSize);
return;
}
try {
// -------------------------
// NO RANGE
// -------------------------
if (rangeHeader == null) {
try (var fileChannel = FileChannel.open(filePath, StandardOpenOption.READ)) {
String ifRange = request.getHeader("If-Range");
if (rangeHeader != null && ifRange != null && !validateIfRange(ifRange, etag, lastModified)) {
// If-Range failed: return full file
response.setStatus(HttpServletResponse.SC_OK);
response.setContentLengthLong(fileSize);
streamBytes(filePath, 0, fileSize - 1, response.getOutputStream());
transferFile(fileChannel, 0, fileSize, response.getOutputStream());
return;
}
// NO RANGE
if (rangeHeader == null) {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentLengthLong(fileSize);
transferFile(fileChannel, 0, fileSize, response.getOutputStream());
return;
}
// -------------------------
// RANGE
// -------------------------
Range range = parseRange(rangeHeader, fileSize);
if (range == null) {
response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
@@ -73,28 +109,124 @@ public class FileStreamingService {
}
long length = range.end - range.start + 1;
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
response.setHeader(
"Content-Range",
"bytes " + range.start + "-" + range.end + "/" + fileSize
);
response.setHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + fileSize);
response.setContentLengthLong(length);
streamBytes(filePath, range.start, range.end, response.getOutputStream());
transferFile(fileChannel, range.start, length, response.getOutputStream());
} catch (NoSuchFileException _) {
throw ApiError.FILE_NOT_FOUND.createException(filePath.toString());
} catch (IOException e) {
if (isClientDisconnect(e)) {
log.debug("Client disconnected during streaming: {}", e.getMessage());
} else {
throw e;
log.error("Error during file streaming: {}", filePath, e);
if (!response.isCommitted()) {
throw ApiError.INTERNAL_SERVER_ERROR.createException("Streaming error: " + e.getMessage());
}
}
}
}
// ------------------------------------------------------------
// RANGE PARSER — RFC 7233 compliant
// ------------------------------------------------------------
/**
* Validates the If-Range header against current ETag and lastModified.
* RFC 7233: If-Range can be a strong ETag OR an HTTP-date.
*/
private boolean validateIfRange(String ifRange, String etag, Instant lastModified) {
if (!ifRange.isEmpty() && ifRange.charAt(0) == '\"') {
// ETag comparison (Strong match required)
return etag.equals(ifRange);
} else {
// HTTP-date comparison
try {
Instant ifRangeDate = Instant.from(HTTP_DATE_FORMAT.parse(ifRange));
// Exact match on seconds required by RFC
return lastModified.getEpochSecond() == ifRangeDate.getEpochSecond();
} catch (DateTimeParseException e) {
log.trace("Failed to parse If-Range date: {}", ifRange);
return false;
}
}
}
/**
* Evaluates the If-None-Match header against the current ETag.
* RFC 7232: If-None-Match can be "*", a single entity-tag, or a list of them.
*/
private boolean evaluateIfNoneMatch(String ifNoneMatch, String currentEtag) {
if (ifNoneMatch == null || ifNoneMatch.isBlank()) {
return false;
}
String trimmedValue = ifNoneMatch.trim();
if ("*".equals(trimmedValue)) {
return true;
}
// Split by comma. Entity-tags are [weak] opaque-tag.
String[] parts = trimmedValue.split(",");
for (String part : parts) {
String tag = part.trim();
if (tag.isEmpty()) {
continue;
}
if (isWeakMatch(tag, currentEtag)) {
return true;
}
}
return false;
}
/**
* Weak comparison of two ETags.
* RFC 7232 Section 2.3.2: Two entity-tags are a weak match if their opaque-tags are equal,
* regardless of whether either or both have a "W/" prefix.
*/
private boolean isWeakMatch(String tag1, String tag2) {
String opaque1 = tag1.startsWith("W/") ? tag1.substring(2) : tag1;
String opaque2 = tag2.startsWith("W/") ? tag2.substring(2) : tag2;
return opaque1.equals(opaque2);
}
/**
* Zero-copy transfer from file channel to output stream via NIO.
* Delegates to sendfile(2) on Linux / equivalent on macOS when the
* servlet container's OutputStream maps to a socket channel.
* Closes the output stream upon completion as the channel wrapper propagates close.
*/
private void transferFile(FileChannel source, long position, long count, OutputStream out) throws IOException {
try (WritableByteChannel destination = Channels.newChannel(out)) {
long remaining = count;
long currentPos = position;
int zeroTransferCount = 0;
while (remaining > 0) {
long transferred = source.transferTo(currentPos, remaining, destination);
if (transferred <= 0) {
++zeroTransferCount;
if (zeroTransferCount > 100) {
throw new IOException("File transfer stalled with " + remaining + " bytes remaining");
}
Thread.onSpinWait();
continue;
}
zeroTransferCount = 0;
currentPos += transferred;
remaining -= transferred;
}
}
}
/**
* Strong ETag derived from file size and last-modified epoch millis.
* Sufficient for static-file identity without content hashing overhead.
*/
String generateETag(long fileSize, Instant lastModified) {
return "\"" + Long.toHexString(fileSize) + "-" + Long.toHexString(lastModified.toEpochMilli()) + "\"";
}
// RANGE PARSER (not) RFC 7233 compliant
Range parseRange(String header, long size) {
if (header == null || !header.startsWith("bytes=")) {
return null;
@@ -136,45 +268,23 @@ public class FileStreamingService {
}
}
// ------------------------------------------------------------
// STREAM BYTES
// ------------------------------------------------------------
private void streamBytes(Path path, long start, long end, OutputStream out)
throws IOException {
try (RandomAccessFile raf = new RandomAccessFile(path.toFile(), "r")) {
raf.seek(start);
long remaining = end - start + 1;
byte[] buffer = new byte[BUFFER_SIZE];
while (remaining > 0) {
int read = raf.read(buffer, 0, (int) Math.min(buffer.length, remaining));
if (read == -1) break;
out.write(buffer, 0, read);
remaining -= read;
}
out.flush();
}
}
// ------------------------------------------------------------
// DISCONNECT DETECTION
// ------------------------------------------------------------
boolean isClientDisconnect(IOException e) {
if (e instanceof SocketTimeoutException) return true;
String msg = e.getMessage();
if (msg == null) return false;
return msg.contains("Broken pipe")
|| msg.contains("Connection reset")
|| msg.contains("connection was aborted")
|| msg.contains("An established connection was aborted")
|| msg.contains("SocketTimeout")
|| msg.contains("timed out");
return switch (e) {
case SocketTimeoutException _, AsyncRequestNotUsableException _ -> true;
case IOException io when io.getMessage() != null -> {
String msg = io.getMessage();
yield msg.contains("Broken pipe")
|| msg.contains("Connection reset")
|| msg.contains("connection was aborted")
|| msg.contains("An established connection was aborted")
|| msg.contains("Response not usable")
|| msg.contains("SocketTimeout")
|| msg.contains("timed out");
}
default -> false;
};
}
record Range(long start, long end) {}
}
}
@@ -110,10 +110,23 @@ public class AudioFileUtilityService {
while (i2 < s2.length() && Character.isDigit(s2.charAt(i2))) {
b2.append(s2.charAt(i2++));
}
String n1 = b1.toString();
String n2 = b2.toString();
long v1 = Long.parseLong(b1.toString());
long v2 = Long.parseLong(b2.toString());
if (v1 != v2) return Long.compare(v1, v2);
// Strip leading zeros for numeric comparison
int start1 = 0;
while (start1 < n1.length() - 1 && n1.charAt(start1) == '0') start1++;
int start2 = 0;
while (start2 < n2.length() - 1 && n2.charAt(start2) == '0') start2++;
String s1_norm = n1.substring(start1);
String s2_norm = n2.substring(start2);
if (s1_norm.length() != s2_norm.length()) {
return s1_norm.length() - s2_norm.length();
}
int cmp = s1_norm.compareTo(s2_norm);
if (cmp != 0) return cmp;
} else {
int cmp = Character.compare(Character.toLowerCase(c1), Character.toLowerCase(c2));
if (cmp != 0) return cmp;
@@ -3,6 +3,8 @@ package org.booklore.service;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.booklore.exception.APIException;
import org.springframework.http.HttpStatus;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -15,6 +17,8 @@ import java.io.IOException;
import java.net.SocketTimeoutException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Instant;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@@ -46,10 +50,10 @@ class FileStreamingServiceTest {
@Test
void streamWithRangeSupport_noRangeHeader_streamsFullFile() throws IOException {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ServletOutputStream servletOutputStream = createServletOutputStream(outputStream);
var request = mock(HttpServletRequest.class);
var response = mock(HttpServletResponse.class);
var outputStream = new ByteArrayOutputStream();
var servletOutputStream = createServletOutputStream(outputStream);
when(request.getHeader("Range")).thenReturn(null);
when(response.getOutputStream()).thenReturn(servletOutputStream);
@@ -65,24 +69,25 @@ class FileStreamingServiceTest {
@Test
void streamWithRangeSupport_fileNotFound_sends404() throws IOException {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
var request = mock(HttpServletRequest.class);
var response = mock(HttpServletResponse.class);
Path nonexistent = tempDir.resolve("nonexistent.bin");
fileStreamingService.streamWithRangeSupport(nonexistent, "audio/mp4", request, response);
verify(response).sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
APIException exception = assertThrows(APIException.class, () ->
fileStreamingService.streamWithRangeSupport(nonexistent, "audio/mp4", request, response)
);
assertEquals(HttpStatus.NOT_FOUND, exception.getStatus());
}
// ==================== streamWithRangeSupport - Range request tests ====================
@Test
void streamWithRangeSupport_fullRange_streamsPartialContent() throws IOException {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ServletOutputStream servletOutputStream = createServletOutputStream(outputStream);
var request = mock(HttpServletRequest.class);
var response = mock(HttpServletResponse.class);
var outputStream = new ByteArrayOutputStream();
var servletOutputStream = createServletOutputStream(outputStream);
when(request.getHeader("Range")).thenReturn("bytes=0-99");
when(response.getOutputStream()).thenReturn(servletOutputStream);
@@ -100,10 +105,10 @@ class FileStreamingServiceTest {
@Test
void streamWithRangeSupport_openEndedRange_streamsToEnd() throws IOException {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ServletOutputStream servletOutputStream = createServletOutputStream(outputStream);
var request = mock(HttpServletRequest.class);
var response = mock(HttpServletResponse.class);
var outputStream = new ByteArrayOutputStream();
var servletOutputStream = createServletOutputStream(outputStream);
when(request.getHeader("Range")).thenReturn("bytes=9900-");
when(response.getOutputStream()).thenReturn(servletOutputStream);
@@ -121,10 +126,10 @@ class FileStreamingServiceTest {
@Test
void streamWithRangeSupport_suffixRange_streamsLastNBytes() throws IOException {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ServletOutputStream servletOutputStream = createServletOutputStream(outputStream);
var request = mock(HttpServletRequest.class);
var response = mock(HttpServletResponse.class);
var outputStream = new ByteArrayOutputStream();
var servletOutputStream = createServletOutputStream(outputStream);
when(request.getHeader("Range")).thenReturn("bytes=-500");
when(response.getOutputStream()).thenReturn(servletOutputStream);
@@ -142,8 +147,8 @@ class FileStreamingServiceTest {
@Test
void streamWithRangeSupport_invalidRange_sends416() throws IOException {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
var request = mock(HttpServletRequest.class);
var response = mock(HttpServletResponse.class);
when(request.getHeader("Range")).thenReturn("bytes=50000-60000"); // Beyond file size
@@ -155,10 +160,10 @@ class FileStreamingServiceTest {
@Test
void streamWithRangeSupport_rangeEndBeyondFileSize_clampsToFileSize() throws IOException {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ServletOutputStream servletOutputStream = createServletOutputStream(outputStream);
var request = mock(HttpServletRequest.class);
var response = mock(HttpServletResponse.class);
var outputStream = new ByteArrayOutputStream();
var servletOutputStream = createServletOutputStream(outputStream);
when(request.getHeader("Range")).thenReturn("bytes=9990-99999"); // End beyond file
when(response.getOutputStream()).thenReturn(servletOutputStream);
@@ -169,20 +174,163 @@ class FileStreamingServiceTest {
verify(response).setContentLengthLong(10); // 9990 to 9999
verify(response).setHeader("Content-Range", "bytes 9990-9999/" + testContent.length);
}
@Test
void streamWithRangeSupport_setsCacheControlHeader() throws IOException {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ServletOutputStream servletOutputStream = createServletOutputStream(outputStream);
void streamWithRangeSupport_setsETagAndCacheHeaders() throws IOException {
var request = mock(HttpServletRequest.class);
var response = mock(HttpServletResponse.class);
var outputStream = new ByteArrayOutputStream();
var servletOutputStream = createServletOutputStream(outputStream);
when(request.getHeader("Range")).thenReturn(null);
when(response.getOutputStream()).thenReturn(servletOutputStream);
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
verify(response).setHeader("Cache-Control", "no-store");
String expectedETag = computeExpectedETag(testFile);
verify(response).setHeader("ETag", expectedETag);
verify(response).setHeader("Cache-Control", "no-cache");
verify(response, never()).setHeader(eq("Pragma"), any());
}
@Test
void streamWithRangeSupport_ifNoneMatchMatchingEtag_returns304() throws IOException {
var request = mock(HttpServletRequest.class);
var response = mock(HttpServletResponse.class);
String etag = computeExpectedETag(testFile);
when(request.getHeader("If-None-Match")).thenReturn(etag);
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
verify(response).setStatus(HttpServletResponse.SC_NOT_MODIFIED);
verify(response, never()).getOutputStream();
}
@Test
void streamWithRangeSupport_ifNoneMatchStaleEtag_streamsNormally() throws IOException {
var request = mock(HttpServletRequest.class);
var response = mock(HttpServletResponse.class);
var outputStream = new ByteArrayOutputStream();
var servletOutputStream = createServletOutputStream(outputStream);
when(request.getHeader("If-None-Match")).thenReturn("\"stale-etag\"");
when(request.getHeader("Range")).thenReturn(null);
when(response.getOutputStream()).thenReturn(servletOutputStream);
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
verify(response).setStatus(HttpServletResponse.SC_OK);
assertArrayEquals(testContent, outputStream.toByteArray());
}
@Test
void streamWithRangeSupport_ifNoneMatchWildcard_returns304() throws IOException {
var request = mock(HttpServletRequest.class);
var response = mock(HttpServletResponse.class);
when(request.getHeader("If-None-Match")).thenReturn("*");
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
verify(response).setStatus(HttpServletResponse.SC_NOT_MODIFIED);
verify(response, never()).getOutputStream();
}
@Test
void streamWithRangeSupport_ifNoneMatchList_returns304() throws IOException {
var request = mock(HttpServletRequest.class);
var response = mock(HttpServletResponse.class);
String etag = computeExpectedETag(testFile);
when(request.getHeader("If-None-Match")).thenReturn("\"other\", " + etag);
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
verify(response).setStatus(HttpServletResponse.SC_NOT_MODIFIED);
}
@Test
void streamWithRangeSupport_ifNoneMatchWeakTag_returns304() throws IOException {
var request = mock(HttpServletRequest.class);
var response = mock(HttpServletResponse.class);
String etag = computeExpectedETag(testFile);
String weakEtag = "W/" + etag;
when(request.getHeader("If-None-Match")).thenReturn(weakEtag);
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
verify(response).setStatus(HttpServletResponse.SC_NOT_MODIFIED);
}
@Test
void streamWithRangeSupport_headRequest_returns200WithContentLength() throws IOException {
var request = mock(HttpServletRequest.class);
var response = mock(HttpServletResponse.class);
when(request.getMethod()).thenReturn("HEAD");
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
verify(response).setStatus(HttpServletResponse.SC_OK);
verify(response).setContentLengthLong(testContent.length);
verify(response).setHeader("Accept-Ranges", "bytes");
verify(response, never()).getOutputStream();
}
@Test
void streamWithRangeSupport_ifRangeMatchingEtag_servesRange() throws IOException {
var request = mock(HttpServletRequest.class);
var response = mock(HttpServletResponse.class);
var outputStream = new ByteArrayOutputStream();
var servletOutputStream = createServletOutputStream(outputStream);
String etag = computeExpectedETag(testFile);
when(request.getHeader("Range")).thenReturn("bytes=0-99");
when(request.getHeader("If-Range")).thenReturn(etag);
when(response.getOutputStream()).thenReturn(servletOutputStream);
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
verify(response).setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
verify(response).setContentLengthLong(100);
assertEquals(100, outputStream.size());
}
@Test
void streamWithRangeSupport_ifRangeStaleEtag_servesFullFile() throws IOException {
var request = mock(HttpServletRequest.class);
var response = mock(HttpServletResponse.class);
var outputStream = new ByteArrayOutputStream();
var servletOutputStream = createServletOutputStream(outputStream);
when(request.getHeader("Range")).thenReturn("bytes=0-99");
when(request.getHeader("If-Range")).thenReturn("\"stale-etag\"");
when(response.getOutputStream()).thenReturn(servletOutputStream);
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
// Stale If-Range ignore range, return full file
verify(response).setStatus(HttpServletResponse.SC_OK);
verify(response).setContentLengthLong(testContent.length);
assertArrayEquals(testContent, outputStream.toByteArray());
}
@Test
void streamWithRangeSupport_setsLastModifiedHeader() throws IOException {
var request = mock(HttpServletRequest.class);
var response = mock(HttpServletResponse.class);
var outputStream = new ByteArrayOutputStream();
var servletOutputStream = createServletOutputStream(outputStream);
when(request.getHeader("Range")).thenReturn(null);
when(response.getOutputStream()).thenReturn(servletOutputStream);
fileStreamingService.streamWithRangeSupport(testFile, "audio/mp4", request, response);
var attrs = Files.readAttributes(testFile, BasicFileAttributes.class);
long expectedMs = attrs.lastModifiedTime().toInstant().toEpochMilli();
verify(response).setDateHeader("Last-Modified", expectedMs);
}
// ==================== parseRange tests ====================
@@ -263,7 +411,6 @@ class FileStreamingServiceTest {
@Test
void parseRange_withLeadingTrailingWhitespace_parsesCorrectly() {
// Leading/trailing whitespace around the range spec is trimmed
var result = fileStreamingService.parseRange("bytes=100-199", 1000);
assertNotNull(result);
@@ -307,7 +454,6 @@ class FileStreamingServiceTest {
@Test
void isClientDisconnect_nullMessage_checksClassName() {
// Create an IOException with null message but class name containing "Timeout"
IOException timeoutException = new SocketTimeoutException();
assertTrue(fileStreamingService.isClientDisconnect(timeoutException));
}
@@ -324,15 +470,14 @@ class FileStreamingServiceTest {
Path emptyFile = tempDir.resolve("empty.bin");
Files.createFile(emptyFile);
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ServletOutputStream servletOutputStream = createServletOutputStream(outputStream);
var request = mock(HttpServletRequest.class);
var response = mock(HttpServletResponse.class);
var outputStream = new ByteArrayOutputStream();
var servletOutputStream = createServletOutputStream(outputStream);
when(request.getHeader("Range")).thenReturn(null);
when(response.getOutputStream()).thenReturn(servletOutputStream);
// This should handle empty file gracefully - the stream will be empty
fileStreamingService.streamWithRangeSupport(emptyFile, "audio/mp4", request, response);
verify(response).setStatus(HttpServletResponse.SC_OK);
@@ -341,10 +486,10 @@ class FileStreamingServiceTest {
@Test
void streamWithRangeSupport_singleByteRange_streamsOneByte() throws IOException {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ServletOutputStream servletOutputStream = createServletOutputStream(outputStream);
var request = mock(HttpServletRequest.class);
var response = mock(HttpServletResponse.class);
var outputStream = new ByteArrayOutputStream();
var servletOutputStream = createServletOutputStream(outputStream);
when(request.getHeader("Range")).thenReturn("bytes=50-50");
when(response.getOutputStream()).thenReturn(servletOutputStream);
@@ -365,10 +510,10 @@ class FileStreamingServiceTest {
"9999, 9999"
})
void streamWithRangeSupport_variousValidRanges_streamsCorrectContent(int start, int end) throws IOException {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ServletOutputStream servletOutputStream = createServletOutputStream(outputStream);
var request = mock(HttpServletRequest.class);
var response = mock(HttpServletResponse.class);
var outputStream = new ByteArrayOutputStream();
var servletOutputStream = createServletOutputStream(outputStream);
when(request.getHeader("Range")).thenReturn("bytes=" + start + "-" + end);
when(response.getOutputStream()).thenReturn(servletOutputStream);
@@ -383,7 +528,14 @@ class FileStreamingServiceTest {
assertArrayEquals(expected, outputStream.toByteArray());
}
// Helper method to create a mock ServletOutputStream
// ==================== Helpers ====================
private String computeExpectedETag(Path file) throws IOException {
var attrs = Files.readAttributes(file, BasicFileAttributes.class);
return fileStreamingService.generateETag(
attrs.size(), attrs.lastModifiedTime().toInstant());
}
private ServletOutputStream createServletOutputStream(ByteArrayOutputStream outputStream) {
return new ServletOutputStream() {
@Override
@@ -296,6 +296,20 @@ class AudioFileUtilityServiceTest {
assertEquals("100.mp3", result.get(3).getFileName().toString());
}
@Test
void listAudioFiles_handlesVeryLongNumericStrings() throws IOException {
String longNum1 = "track-12345678901234567890.mp3";
String longNum2 = "track-12345678901234567891.mp3";
Files.createFile(tempDir.resolve(longNum2));
Files.createFile(tempDir.resolve(longNum1));
List<Path> result = audioFileUtility.listAudioFiles(tempDir);
assertEquals(2, result.size());
assertEquals(longNum1, result.get(0).getFileName().toString());
assertEquals(longNum2, result.get(1).getFileName().toString());
}
@Test
void listAudioFiles_sortsCaseInsensitively() throws IOException {
Files.createFile(tempDir.resolve("Alpha.mp3"));