For a {@link ByteArrayInputStream}, detection inspects the full content and restores + * the original position without copying it. Other markable streams up to 1 MiB are + * buffered for complete detection and then reset. Larger streams are passed directly + * to Tika for full detection; like non-markable streams, their position may advance. + * This method does not close the caller's stream.
+ * * @param inputStream the input stream (may be {@code null}) * @return the detected MIME type, or {@code null} if the stream is {@code null} * @throws IOException if detection fails @@ -54,7 +63,37 @@ public static MimeType detectMimeType(InputStream inputStream) throws IOExceptio if (Objects.isNull(inputStream)) { return null; } - return toMimeType(TIKA.detect(inputStream)); + if (inputStream instanceof ByteArrayInputStream) { + inputStream.mark(0); + try { + return toMimeType(TIKA.detect(nonClosing(inputStream))); + } finally { + inputStream.reset(); + } + } + if (inputStream.markSupported()) { + inputStream.mark(MAX_BUFFERED_DETECTION_BYTES + 1); + byte[] content; + try { + content = inputStream.readNBytes(MAX_BUFFERED_DETECTION_BYTES + 1); + } finally { + inputStream.reset(); + } + if (content.length <= MAX_BUFFERED_DETECTION_BYTES) { + return toMimeType(TIKA.detect(new ByteArrayInputStream(content))); + } + return toMimeType(TIKA.detect(nonClosing(inputStream))); + } + return toMimeType(TIKA.detect(nonClosing(inputStream))); + } + + private static InputStream nonClosing(InputStream inputStream) { + return new FilterInputStream(inputStream) { + @Override + public void close() { + // The caller owns the supplied stream. + } + }; } /** diff --git a/src/test/java/io/github/easy4j/validation/utils/TikaUtilTest.java b/src/test/java/io/github/easy4j/validation/utils/TikaUtilTest.java index e0dac04..9240574 100644 --- a/src/test/java/io/github/easy4j/validation/utils/TikaUtilTest.java +++ b/src/test/java/io/github/easy4j/validation/utils/TikaUtilTest.java @@ -6,9 +6,18 @@ import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.Random; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; import static org.junit.jupiter.api.Assertions.*; @@ -31,10 +40,182 @@ void shouldReturnNullForNullInputStream() throws IOException { @Test void shouldDetectMimeTypeFromInputStream() throws IOException { - byte[] pdfContent = "%PDF-1.7\n%%EOF".getBytes(); + byte[] pdfContent = "%PDF-1.7\n%%EOF".getBytes(StandardCharsets.US_ASCII); try (InputStream is = new ByteArrayInputStream(pdfContent)) { MimeType mimeType = TikaUtil.detectMimeType(is); - assertNotNull(mimeType); + assertEquals("application/pdf", mimeType.getName()); + } + } + + @Test + void shouldPreserveMarkableCallerStreamPositionAndOwnership() throws IOException { + byte[] pdfContent = "%PDF-1.7\n%%EOF".getBytes(StandardCharsets.US_ASCII); + AtomicBoolean closed = new AtomicBoolean(); + InputStream stream = new ByteArrayInputStream(pdfContent) { + @Override + public void close() throws IOException { + closed.set(true); + super.close(); + } + }; + + assertEquals("application/pdf", TikaUtil.detectMimeType(stream).getName()); + assertFalse(closed.get(), "the caller owns the stream"); + assertArrayEquals(pdfContent, stream.readAllBytes(), "detection must restore the stream position"); + } + + @Test + void shouldRestoreBufferedStreamWithoutReadingUnboundedContent() throws IOException { + byte[] content = new byte[128 * 1024]; + byte[] header = "%PDF-1.7\n%%EOF".getBytes(StandardCharsets.US_ASCII); + System.arraycopy(header, 0, content, 0, header.length); + try (InputStream stream = new BufferedInputStream(new ByteArrayInputStream(content))) { + assertEquals("application/pdf", TikaUtil.detectMimeType(stream).getName()); + assertArrayEquals(header, stream.readNBytes(header.length)); + } + } + + @Test + void shouldRecognizeJarWithManifestBeyondFirst64KiB() throws IOException { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + try (ZipOutputStream archive = new ZipOutputStream(output)) { + archive.putNextEntry(new ZipEntry("payload.bin")); + byte[] filler = new byte[70 * 1024]; + new Random(1234).nextBytes(filler); + archive.write(filler); + archive.closeEntry(); + archive.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF")); + archive.write("Manifest-Version: 1.0\r\n\r\n".getBytes(StandardCharsets.US_ASCII)); + archive.closeEntry(); + } + byte[] jar = output.toByteArray(); + assertTrue(jar.length > 64 * 1024); + try (InputStream stream = new ByteArrayInputStream(jar)) { + assertEquals("application/java-archive", TikaUtil.detectMimeType(stream).getName()); + assertArrayEquals(jar, stream.readAllBytes()); + } + } + + @Test + void shouldRecognizeLargeJarFromBufferedStream() throws IOException { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + try (ZipOutputStream archive = new ZipOutputStream(output)) { + byte[] filler = new byte[1024 * 1024 + 64 * 1024]; + new Random(1234).nextBytes(filler); + writeZipEntry(archive, "payload.bin", filler); + writeZipEntry(archive, "META-INF/MANIFEST.MF", + "Manifest-Version: 1.0\r\n\r\n".getBytes(StandardCharsets.US_ASCII)); + } + byte[] jar = output.toByteArray(); + assertTrue(jar.length > 1024 * 1024); + try (InputStream stream = new BufferedInputStream(new ByteArrayInputStream(jar))) { + assertEquals("application/java-archive", TikaUtil.detectMimeType(stream).getName()); + } + } + + @Test + void shouldRecognizeOfficeContainersWithMediaBeforeContentTypes() throws IOException { + byte[] docx = officeArchive("word", "document.xml", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", + "