TarGzArchiver { public void createArchive() throws IOException { validate(); log.info("Building tar: " + destFile); TarArchiveOutputStream tarStream = null; try { destFile.getAbsoluteFile().getParentFile().mkdirs(); GzipCompressorOutputStream gzipStream = new GzipCompressorOutputStream( new BufferedOutputStream(new FileOutputStream(destFile))); tarStream = new TarArchiveOutputStream(gzipStream, "UTF-8"); tarStream.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); for (File sourceDir : sourceDirs) { for (File child : sourceDir.listFiles()) { addToTarRecursively(sourceDir, child, tarStream); } } } finally { if (tarStream != null) { tarStream.close(); } } } TarGzArchiver(); void setLog(Log log); void setDestFile(File destFile); void addDirectory(File directory); void createArchive();  }
@Test public void testCreateArchiveEntriesPresent() throws Exception { archiver.createArchive(); Map<String, TarArchiveEntry> tarEntries = getTarEntries(); assertEquals(7, tarEntries.size()); assertThat(tarEntries.keySet(), hasItems("dir2/", "dir2/test.txt", "dir2/dir3/", "dir2/dir3/test.sh", "dir2/testPermissions", "dir2/testLastModified", "dir2/testOwnerAndGroupName")); TarArchiveEntry dirArchiveEntry = tarEntries.get("dir2/"); assertTrue(dirArchiveEntry.isDirectory()); TarArchiveEntry textFileEntry = tarEntries.get("dir2/test.txt"); assertTrue(textFileEntry.isFile()); byte[] content = getTarEntry("dir2/test.txt"); assertEquals("hello", new String(content, StandardCharsets.UTF_8)); }
@Test public void testCreateArchiveEntriesLastModifiedPreserved() throws Exception { archiver.createArchive(); Map<String, TarArchiveEntry> tarEntries = getTarEntries(); assertEquals(new Date(0L), tarEntries.get("dir2/testLastModified").getModTime()); }
@Test public void testCreateArchivePermissionsPreserved() throws Exception { setPermissionsTo700(); archiver.createArchive(); assertEquals(0700, getTarEntries().get("dir2/testPermissions").getMode()); }
@Test public void testLongPathEntry() throws Exception { final String longPath = "very/long/path/exceeding/100/chars/very/long/path/exceeding/100/chars/very/long/path/exceeding/100/chars/test.txt"; File longPathFile = new File(archiveRoot, longPath); assertTrue(longPathFile.getParentFile().mkdirs()); assertTrue(longPathFile.createNewFile()); archiver.createArchive(); assertTrue(getTarEntries().containsKey(longPath)); }