@Test public void packingALargeFileShouldGenerateTheSameOutputWhenOverwritingAsWhenAppending() throws IOException { File reference = File.createTempFile("reference", ".zip"); String packageName = getClass().getPackage().getName().replace(".", "/"); URL sample = Resources.getResource(packageName + "/macbeth.properties"); byte[] input = Resources.toByteArray(sample); try (CustomZipOutputStream out = ZipOutputStreams.newOutputStream(output, OVERWRITE_EXISTING); ZipOutputStream ref = new ZipOutputStream(new FileOutputStream(reference))) { CustomZipEntry entry = new CustomZipEntry("macbeth.properties"); entry.setTime(System.currentTimeMillis()); out.putNextEntry(entry); ref.putNextEntry(entry); out.write(input); ref.write(input); } byte[] seen = Files.readAllBytes(output); byte[] expected = Files.readAllBytes(reference.toPath()); // Make sure the output is valid. try (ZipInputStream in = new ZipInputStream(Files.newInputStream(output))) { ZipEntry entry = in.getNextEntry(); assertEquals("macbeth.properties", entry.getName()); assertNull(in.getNextEntry()); } assertArrayEquals(expected, seen); }
@Test public void testThatExternalAttributesFieldIsFunctional() throws IOException { // Prepare some sample modes to write into the zip file. final ImmutableList<String> samples = ImmutableList.of("rwxrwxrwx", "rw-r--r--", "--x--x--x", "---------"); for (String stringMode : samples) { long mode = MorePosixFilePermissions.toMode(PosixFilePermissions.fromString(stringMode)); // Write a tiny sample zip file, which sets the external attributes per the // permission sample above. try (CustomZipOutputStream out = ZipOutputStreams.newOutputStream(output, OVERWRITE_EXISTING)) { CustomZipEntry entry = new CustomZipEntry("test"); entry.setTime(System.currentTimeMillis()); entry.setExternalAttributes(mode << 16); out.putNextEntry(entry); out.write(new byte[0]); } // Now re-read the zip file using apache's commons-compress, which supports parsing // the external attributes field. try (ZipFile in = new ZipFile(output.toFile())) { Enumeration<ZipArchiveEntry> entries = in.getEntries(); ZipArchiveEntry entry = entries.nextElement(); assertEquals(mode, entry.getExternalAttributes() >> 16); assertFalse(entries.hasMoreElements()); } } }
@Test public void canWriteContentToStoredZips() throws IOException { Path overwriteZip = Files.createTempFile("overwrite", ".zip"); byte[] input = "I like cheese".getBytes(UTF_8); try (CustomZipOutputStream overwrite = ZipOutputStreams.newOutputStream(overwriteZip, OVERWRITE_EXISTING); CustomZipOutputStream appending = ZipOutputStreams.newOutputStream(output, APPEND_TO_ZIP)) { CustomZipEntry entry = new CustomZipEntry("cheese.txt"); entry.setCompressionLevel(NO_COMPRESSION); entry.setTime(0); overwrite.putNextEntry(entry); appending.putNextEntry(entry); overwrite.write(input); appending.write(input); } }