BundleFileTypeDetector extends FileTypeDetector { @Override public String probeContentType(Path path) throws IOException { ByteBuffer buf = ByteBuffer.allocate(256); try (SeekableByteChannel byteChannel = Files.newByteChannel(path, StandardOpenOption.READ)) { int read = byteChannel.read(buf); if (read < 38) { return null; } ; } buf.flip(); byte[] firstBytes = buf.array(); String pk = new String(firstBytes, 0, 2, LATIN1); if (!(pk.equals("PK") && firstBytes[2] == 3 && firstBytes[3] == 4)) { return null; } String mimetype = new String(firstBytes, 30, 8, LATIN1); if (!mimetype.equals(MIMETYPE)) { return APPLICATION_ZIP; } try (ZipInputStream is = new ZipInputStream(new ByteArrayInputStream( firstBytes))) { ZipEntry entry = is.getNextEntry(); if (!MIMETYPE.equals(entry.getName())) { return APPLICATION_ZIP; } byte[] mediaTypeBuffer = new byte[256]; int size = is.read(mediaTypeBuffer); if (size < 1) { return APPLICATION_ZIP; } return new String(mediaTypeBuffer, 0, size, ASCII); } catch (ZipException | ZipError e) { return null; } }  @Override String probeContentType(Path path);  }
@Test public void detectRoBundle() throws Exception { BundleFileTypeDetector detector = new BundleFileTypeDetector(); try (Bundle bundle = Bundles.createBundle()) { assertEquals("application/vnd.wf4ever.robundle+zip", detector.probeContentType(bundle.getSource())); } }
@Test public void detectEmptyZip() throws Exception { BundleFileTypeDetector detector = new BundleFileTypeDetector(); Path zip = Files.createTempFile("test", ".bin"); zip.toFile().deleteOnExit(); try (ZipOutputStream zout = new ZipOutputStream( Files.newOutputStream(zip))) { ZipEntry entry = new ZipEntry("e"); zout.putNextEntry(entry); zout.closeEntry(); } assertEquals("application/zip", detector.probeContentType(zip)); }
@Test public void detectNonZip() throws Exception { BundleFileTypeDetector detector = new BundleFileTypeDetector(); Path file = Files.createTempFile("test", ".bin"); file.toFile().deleteOnExit(); Files.write(file, Arrays.asList("This is just some text", "added here to make the file", "larger than 38 bytes"), Charset .forName("UTF8")); assertTrue(Files.size(file) > 38); assertNull(detector.probeContentType(file)); }
@Test public void detectEmpty() throws Exception { BundleFileTypeDetector detector = new BundleFileTypeDetector(); Path file = Files.createTempFile("test", ".bin"); file.toFile().deleteOnExit(); assertEquals(0, Files.size(file)); assertNull(detector.probeContentType(file)); }
@Test public void detectorSPI() throws Exception { try (Bundle bundle = Bundles.createBundle()) { assertEquals("application/vnd.wf4ever.robundle+zip", Files.probeContentType(bundle.getSource())); } }