List of usage examples for org.apache.commons.compress.archivers ArchiveOutputStream createArchiveEntry
public abstract ArchiveEntry createArchiveEntry(File inputFile, String entryName) throws IOException;
From source file:com.fizzed.stork.deploy.Archive.java
static public void packEntry(ArchiveOutputStream aos, Path dirOrFile, String base, boolean appendName) throws IOException { String entryName = base;/*from w ww. jav a 2 s . co m*/ if (appendName) { if (!entryName.equals("")) { if (!entryName.endsWith("/")) { entryName += "/" + dirOrFile.getFileName(); } else { entryName += dirOrFile.getFileName(); } } else { entryName += dirOrFile.getFileName(); } } ArchiveEntry entry = aos.createArchiveEntry(dirOrFile.toFile(), entryName); if (Files.isRegularFile(dirOrFile)) { if (entry instanceof TarArchiveEntry && Files.isExecutable(dirOrFile)) { // -rwxr-xr-x ((TarArchiveEntry) entry).setMode(493); } else { // keep default mode } } aos.putArchiveEntry(entry); if (Files.isRegularFile(dirOrFile)) { Files.copy(dirOrFile, aos); aos.closeArchiveEntry(); } else { aos.closeArchiveEntry(); List<Path> children = Files.list(dirOrFile).collect(Collectors.toList()); if (children != null) { for (Path childFile : children) { packEntry(aos, childFile, entryName + "/", true); } } } }
From source file:com.geewhiz.pacify.utils.ArchiveUtils.java
private static File manifestWorkaround(File archive, String archiveType, ArchiveOutputStream aos, ChangeSet changes, List<FileInputStream> streamsToClose) throws IOException { String manifestPath = "META-INF/MANIFEST.MF"; if (!archiveContainsFile(archive, archiveType, manifestPath)) { return null; }/*w w w .ja v a 2 s.co m*/ File originalManifestFile = extractFile(archive, archiveType, manifestPath); ArchiveEntry archiveEntry = aos.createArchiveEntry(originalManifestFile, manifestPath); FileInputStream fis = new FileInputStream(originalManifestFile); streamsToClose.add(fis); changes.add(archiveEntry, fis, true); return originalManifestFile; }
From source file:com.mirth.connect.util.ArchiveUtils.java
/** * Recursively copies folders/files into the given ArchiveOutputStream. *//*from w w w. j a va 2 s. c om*/ private static void createFolderArchive(File folder, ArchiveOutputStream archiveOutputStream, String rootFolder) throws CompressException { byte[] buffer = new byte[BUFFER_SIZE]; for (File file : folder.listFiles()) { if (file.isDirectory()) { createFolderArchive(file, archiveOutputStream, rootFolder); } else { try { // extract/remove the rootFolder from the file's absolute path before adding it to the archive String entryName = file.getAbsolutePath(); if (entryName.substring(0, rootFolder.length()).equals(rootFolder)) { entryName = entryName.substring(rootFolder.length()); } archiveOutputStream.putArchiveEntry(archiveOutputStream.createArchiveEntry(file, entryName)); InputStream inputStream = new FileInputStream(file); logger.debug("Adding \"" + entryName + "\" to archive"); try { IOUtils.copyLarge(inputStream, archiveOutputStream, buffer); } finally { IOUtils.closeQuietly(inputStream); archiveOutputStream.closeArchiveEntry(); } } catch (Exception e) { throw new CompressException(e); } } } }
From source file:com.geewhiz.pacify.utils.ArchiveUtils.java
public static void replaceFilesInArchive(File archive, String archiveType, Map<String, File> filesToReplace) { ArchiveStreamFactory factory = new ArchiveStreamFactory(); File manifest = null;// ww w . j av a 2 s .co m InputStream archiveStream = null; ArchiveInputStream ais = null; ArchiveOutputStream aos = null; List<FileInputStream> streamsToClose = new ArrayList<FileInputStream>(); File tmpArchive = FileUtils.createEmptyFileWithSamePermissions(archive); try { aos = factory.createArchiveOutputStream(archiveType, new FileOutputStream(tmpArchive)); ChangeSet changes = new ChangeSet(); if (ArchiveStreamFactory.JAR.equalsIgnoreCase(archiveType)) { manifest = manifestWorkaround(archive, archiveType, aos, changes, streamsToClose); } for (String filePath : filesToReplace.keySet()) { File replaceWithFile = filesToReplace.get(filePath); ArchiveEntry archiveEntry = aos.createArchiveEntry(replaceWithFile, filePath); FileInputStream fis = new FileInputStream(replaceWithFile); streamsToClose.add(fis); changes.add(archiveEntry, fis, true); } archiveStream = new FileInputStream(archive); ais = factory.createArchiveInputStream(archiveType, archiveStream); ChangeSetPerformer performer = new ChangeSetPerformer(changes); performer.perform(ais, aos); } catch (IOException e) { throw new RuntimeException(e); } catch (ArchiveException e) { throw new RuntimeException(e); } finally { for (FileInputStream fis : streamsToClose) { IOUtils.closeQuietly(fis); } IOUtils.closeQuietly(aos); IOUtils.closeQuietly(ais); IOUtils.closeQuietly(archiveStream); } if (manifest != null) { manifest.delete(); } if (!archive.delete()) { throw new RuntimeException("Couldn't delete file [" + archive.getPath() + "]... Aborting!"); } if (!tmpArchive.renameTo(archive)) { throw new RuntimeException("Couldn't rename filtered file from [" + tmpArchive.getPath() + "] to [" + archive.getPath() + "]... Aborting!"); } }
From source file:net.shopxx.util.CompressUtils.java
public static void archive(File[] srcFiles, File destFile, String archiverName) { Assert.notNull(destFile);//from w w w. j av a 2 s . c o m Assert.state(!destFile.exists() || destFile.isFile()); Assert.hasText(archiverName); File parentFile = destFile.getParentFile(); if (parentFile != null) { parentFile.mkdirs(); } ArchiveOutputStream archiveOutputStream = null; try { archiveOutputStream = new ArchiveStreamFactory().createArchiveOutputStream(archiverName, new BufferedOutputStream(new FileOutputStream(destFile))); if (ArrayUtils.isNotEmpty(srcFiles)) { for (File srcFile : srcFiles) { if (srcFile == null || !srcFile.exists()) { continue; } Set<File> files = new HashSet<File>(); if (srcFile.isFile()) { files.add(srcFile); } if (srcFile.isDirectory()) { files.addAll(FileUtils.listFilesAndDirs(srcFile, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE)); } String basePath = FilenameUtils.getFullPath(srcFile.getCanonicalPath()); for (File file : files) { try { String entryName = FilenameUtils.separatorsToUnix( StringUtils.substring(file.getCanonicalPath(), basePath.length())); ArchiveEntry archiveEntry = archiveOutputStream.createArchiveEntry(file, entryName); archiveOutputStream.putArchiveEntry(archiveEntry); if (file.isFile()) { InputStream inputStream = null; try { inputStream = new BufferedInputStream(new FileInputStream(file)); IOUtils.copy(inputStream, archiveOutputStream); } catch (FileNotFoundException e) { throw new RuntimeException(e.getMessage(), e); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { IOUtils.closeQuietly(inputStream); } } } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { archiveOutputStream.closeArchiveEntry(); } } } } } catch (ArchiveException e) { throw new RuntimeException(e.getMessage(), e); } catch (FileNotFoundException e) { throw new RuntimeException(e.getMessage(), e); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { IOUtils.closeQuietly(archiveOutputStream); } }
From source file:com.iorga.webappwatcher.EventLogManager.java
private void writeEventLogToHttpServletResponse(final ArchiveOutputStream outputStream, final InputStream inputStream, final File file, final String fileName) throws IOException { ArchiveEntry archiveEntry = outputStream.createArchiveEntry(file, fileName); if (!file.getName().equals(fileName)) { // the original file is not the same as the final file, i.e. an original .gz which is uncompressed on the fly, we can't know the file size archiveEntry = new ZipArchiveEntry(fileName); }// w w w.j av a 2 s . co m outputStream.putArchiveEntry(archiveEntry); try { IOUtils.copy(inputStream, outputStream); } catch (final Exception e) { log.warn("Problem while copying file " + fileName, e); } finally { outputStream.closeArchiveEntry(); inputStream.close(); } }
From source file:com.streamsets.pipeline.lib.parser.TestCompressionInputBuilder.java
@SuppressWarnings("unchecked") private void testArchive(String archiveType) throws Exception { //create an archive with multiple files, files containing multiple objects File dir = new File("target", UUID.randomUUID().toString()); dir.mkdirs();//from www . j a v a 2 s .co m OutputStream archiveOut = new FileOutputStream(new File(dir, "myArchive")); ArchiveOutputStream archiveOutputStream = new ArchiveStreamFactory().createArchiveOutputStream(archiveType, archiveOut); File inputFile; ArchiveEntry archiveEntry; FileOutputStream fileOutputStream; for (int i = 0; i < 5; i++) { String fileName = "file-" + i + ".txt"; inputFile = new File(dir, fileName); fileOutputStream = new FileOutputStream(inputFile); IOUtils.write(("StreamSets" + i).getBytes(), fileOutputStream); fileOutputStream.close(); archiveEntry = archiveOutputStream.createArchiveEntry(inputFile, fileName); archiveOutputStream.putArchiveEntry(archiveEntry); IOUtils.copy(new FileInputStream(inputFile), archiveOutputStream); archiveOutputStream.closeArchiveEntry(); } archiveOutputStream.finish(); archiveOut.close(); //create compression input FileInputStream fileInputStream = new FileInputStream(new File(dir, "myArchive")); CompressionDataParser.CompressionInputBuilder compressionInputBuilder = new CompressionDataParser.CompressionInputBuilder( Compression.ARCHIVE, "*.txt", fileInputStream, "0"); CompressionDataParser.CompressionInput input = compressionInputBuilder.build(); // before reading Assert.assertNotNull(input); // The default wrapped offset before reading any file String wrappedOffset = "{\"fileName\": \"myfile\", \"fileOffset\":\"0\"}"; Map<String, Object> archiveInputOffset = OBJECT_MAPPER.readValue(wrappedOffset, Map.class); Assert.assertNotNull(archiveInputOffset); Assert.assertEquals("myfile", archiveInputOffset.get("fileName")); Assert.assertEquals("0", archiveInputOffset.get("fileOffset")); Assert.assertEquals("0", input.getStreamPosition(wrappedOffset)); // read and check wrapped offset BufferedReader reader = new BufferedReader(new InputStreamReader(input.getNextInputStream())); Assert.assertEquals("StreamSets0", reader.readLine()); wrappedOffset = input.wrapOffset("4567"); archiveInputOffset = OBJECT_MAPPER.readValue(wrappedOffset, Map.class); Assert.assertNotNull(archiveInputOffset); Assert.assertEquals("file-0.txt", archiveInputOffset.get("fileName")); Assert.assertEquals("4567", archiveInputOffset.get("fileOffset")); String recordIdPattern = "myFile/file-0.txt"; Assert.assertEquals(recordIdPattern, input.wrapRecordId("myFile")); }
From source file:org.deventropy.shared.utils.DirectoryArchiverUtil.java
private static void createArchiveOfDirectory(final String archiveFile, final File srcDirectory, final String rootPathPrefix, final String archiveStreamFactoryConstant, final String encoding, final ArchiverCreateProcessor archiverCreateProcessorIn) throws IOException { /*//from ww w .j a v a 2 s .c o m * NOTE ON CHARSET ENCODING: Traditionally the ZIP archive format uses CodePage 437 as encoding for file name, * which is not sufficient for many international character sets. * Over time different archivers have chosen different ways to work around the limitation - the java.util.zip * packages simply uses UTF-8 as its encoding for example. * Ant has been offering the encoding attribute of the zip and unzip task as a way to explicitly specify the * encoding to use (or expect) since Ant 1.4. It defaults to the platform's default encoding for zip and UTF-8 * for jar and other jar-like tasks (war, ear, ...) as well as the unzip family of tasks. */ final ArchiverCreateProcessor archiveCreateProcessor = (null != archiverCreateProcessorIn) ? archiverCreateProcessorIn : new ArchiverCreateProcessor(); ArchiveOutputStream aos = null; try { final ArchiveStreamFactory archiveStreamFactory = new ArchiveStreamFactory(encoding); final FileOutputStream archiveFileOutputStream = new FileOutputStream(archiveFile); final OutputStream decoratedArchiveFileOutputStream = archiveCreateProcessor .decorateFileOutputStream(archiveFileOutputStream); aos = archiveStreamFactory.createArchiveOutputStream(archiveStreamFactoryConstant, decoratedArchiveFileOutputStream); archiveCreateProcessor.processArchiverPostCreate(aos, encoding); final String normalizedRootPathPrefix = (null == rootPathPrefix || rootPathPrefix.isEmpty()) ? "" : normalizeName(rootPathPrefix, true); if (!normalizedRootPathPrefix.isEmpty()) { final ArchiveEntry archiveEntry = aos.createArchiveEntry(srcDirectory, normalizedRootPathPrefix); aos.putArchiveEntry(archiveEntry); aos.closeArchiveEntry(); } final Path srcRootPath = Paths.get(srcDirectory.toURI()); final ArchiverFileVisitor visitor = new ArchiverFileVisitor(srcRootPath, normalizedRootPathPrefix, aos); Files.walkFileTree(srcRootPath, visitor); aos.flush(); } catch (ArchiveException e) { throw new IOException("Error creating archive", e); } finally { if (null != aos) { aos.close(); } } }
From source file:org.interreg.docexplore.util.ZipUtils.java
static int zip(File[] files, Deque<File> queue, URI base, int cnt, int nEntries, float[] progress, float progressOffset, float progressAmount, ArchiveOutputStream zout) throws IOException { for (File kid : files) { String name = base.relativize(kid.toURI()).getPath(); if (kid.isDirectory()) { queue.push(kid);/*from w ww. j a v a 2 s . c o m*/ name = name.endsWith("/") ? name : name + "/"; ArchiveEntry entry = zout.createArchiveEntry(kid, name); zout.putArchiveEntry(entry); zout.closeArchiveEntry(); } else { ArchiveEntry entry = zout.createArchiveEntry(kid, name); zout.putArchiveEntry(entry); copy(kid, zout); zout.closeArchiveEntry(); cnt++; if (progress != null) progress[0] = progressOffset + cnt * progressAmount / nEntries; } } return cnt; }
From source file:org.openengsb.connector.git.internal.GitServiceImpl.java
/** * Packs the files and directories of a passed {@link File} to a passed * {@link ArchiveOutputStream}./*from www . j av a 2 s . co m*/ * * @throws IOException */ private void packRepository(File source, ArchiveOutputStream aos) throws IOException { int bufferSize = 2048; byte[] readBuffer = new byte[bufferSize]; int bytesIn = 0; File[] files = source.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return !pathname.getName().equals(Constants.DOT_GIT); } }); for (File file : files) { if (file.isDirectory()) { ArchiveEntry ae = aos.createArchiveEntry(file, getRelativePath(file.getAbsolutePath())); aos.putArchiveEntry(ae); aos.closeArchiveEntry(); packRepository(file, aos); } else { FileInputStream fis = new FileInputStream(file); ArchiveEntry ae = aos.createArchiveEntry(file, getRelativePath(file.getAbsolutePath())); aos.putArchiveEntry(ae); while ((bytesIn = fis.read(readBuffer)) != -1) { aos.write(readBuffer, 0, bytesIn); } aos.closeArchiveEntry(); fis.close(); } } }