List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream ZipArchiveOutputStream
public ZipArchiveOutputStream(File file) throws IOException
From source file:net.larry1123.elec.util.logger.LoggerDirectoryHandler.java
public void zipLogs() throws IOException { File zipFile = getDirectoryPath().resolve(getDateFormatFromMilli(System.currentTimeMillis()) + ".zip") .toFile();/*from w w w . j a va2 s.c o m*/ ZipArchiveOutputStream archiveOutputStream = new ZipArchiveOutputStream(zipFile); // Collection<File> files = FileUtils.listFiles(directory, new String[] {getConfig().getFileType()}, false); // for (File file : files) { // packFile(file, archiveOutputStream); // } for (Map.Entry<Logger, UtilFileHandler> loggerUtilFileHandlerEntry : streamHandlerHashMap.entrySet()) { Logger logger = loggerUtilFileHandlerEntry.getKey(); UtilFileHandler utilFileHandler = loggerUtilFileHandlerEntry.getValue(); // Stop the steam and make sure it is all to disk first utilFileHandler.close(); File file = getFileForLogger(logger); packFile(file, archiveOutputStream); // Restart the stream utilFileHandler.setOutputStream(makeFileOutputStreamForLogger(logger)); } archiveOutputStream.finish(); archiveOutputStream.close(); }
From source file:fr.acxio.tools.agia.tasks.ZipFilesTasklet.java
@Override public RepeatStatus execute(StepContribution sContribution, ChunkContext sChunkContext) throws Exception { // 1. Destination exists // a. Overwrite => default behaviour // b. Update => copy to temporary file, open, read entries, merge with new entries, write merged entries and stream // 2. New destination => default behaviour Map<String, Object> aSourceParams = new HashMap<String, Object>(); aSourceParams.put(ResourceFactoryConstants.PARAM_STEP_EXEC, ((sChunkContext != null) && (sChunkContext.getStepContext() != null)) ? sChunkContext.getStepContext().getStepExecution() : null);/* w w w . ja va 2s. c o m*/ aSourceParams.put(ResourceFactoryConstants.PARAM_BASE_DIRECTORY, sourceBaseDirectory); Resource[] aSourceResources = sourceFactory.getResources(aSourceParams); Map<String, Object> aDestinationParams = new HashMap<String, Object>(); if (LOGGER.isInfoEnabled()) { LOGGER.info("{} file(s) to zip", aSourceResources.length); } if (aSourceResources.length > 0) { aDestinationParams.put(ResourceFactoryConstants.PARAM_BASE_DIRECTORY, sourceBaseDirectory); aDestinationParams.put(ResourceFactoryConstants.PARAM_STEP_EXEC, ((sChunkContext != null) && (sChunkContext.getStepContext() != null)) ? sChunkContext.getStepContext().getStepExecution() : null); Resource aDestination = destinationFactory.getResource(aDestinationParams); ZipArchiveOutputStream aZipArchiveOutputStream = null; try { aZipArchiveOutputStream = new ZipArchiveOutputStream(aDestination.getFile()); sourceBaseDirectoryPath = sourceBaseDirectory.getFile().getCanonicalPath(); for (Resource aSourceResource : aSourceResources) { zipResource(aSourceResource, aZipArchiveOutputStream, sContribution, sChunkContext); } } finally { if (aZipArchiveOutputStream != null) { aZipArchiveOutputStream.finish(); aZipArchiveOutputStream.close(); } } } return RepeatStatus.FINISHED; }
From source file:com.facebook.buck.zip.UnzipTest.java
@Test public void testExtractSymlink() throws IOException { assumeThat(Platform.detect(), Matchers.is(Matchers.not(Platform.WINDOWS))); // Create a simple zip archive using apache's commons-compress to store executable info. try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) { ZipArchiveEntry entry = new ZipArchiveEntry("link.txt"); entry.setUnixMode((int) MoreFiles.S_IFLNK); String target = "target.txt"; entry.setSize(target.getBytes(Charsets.UTF_8).length); entry.setMethod(ZipEntry.STORED); zip.putArchiveEntry(entry);/*from ww w . j a va 2 s .c om*/ zip.write(target.getBytes(Charsets.UTF_8)); zip.closeArchiveEntry(); } // Now run `Unzip.extractZipFile` on our test zip and verify that the file is executable. Path extractFolder = tmpFolder.newFolder(); Unzip.extractZipFile(zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), Unzip.ExistingFileMode.OVERWRITE); Path link = extractFolder.toAbsolutePath().resolve("link.txt"); assertTrue(Files.isSymbolicLink(link)); assertThat(Files.readSymbolicLink(link).toString(), Matchers.equalTo("target.txt")); }
From source file:at.spardat.xma.xdelta.JarPatcher.java
/** * Main method to make {@link #applyDelta(ZipFile, ZipFile, ZipArchiveOutputStream, BufferedReader)} available at * the command line.<br>// w ww . jav a 2 s . c om * usage JarPatcher source patch output * * @param args the arguments * @throws IOException Signals that an I/O exception has occurred. */ public static void main(String[] args) throws IOException { String patchName = null; String outputName = null; String sourceName = null; if (args.length == 0) { System.err.println("usage JarPatcher patch [output [source]]"); System.exit(1); } else { patchName = args[0]; if (args.length > 1) { outputName = args[1]; if (args.length > 2) { sourceName = args[2]; } } } ZipFile patch = new ZipFile(patchName); ZipArchiveEntry listEntry = patch.getEntry("META-INF/file.list"); if (listEntry == null) { System.err.println("Invalid patch - list entry 'META-INF/file.list' not found"); System.exit(2); } BufferedReader list = new BufferedReader(new InputStreamReader(patch.getInputStream(listEntry))); String next = list.readLine(); if (sourceName == null) { sourceName = next; } next = list.readLine(); if (outputName == null) { outputName = next; } int ignoreSourcePaths = Integer.parseInt(System.getProperty("patcher.ignoreSourcePathElements", "0")); int ignoreOutputPaths = Integer.parseInt(System.getProperty("patcher.ignoreOutputPathElements", "0")); Path sourcePath = Paths.get(sourceName); Path outputPath = Paths.get(outputName); if (ignoreOutputPaths >= outputPath.getNameCount()) { patch.close(); StringBuilder b = new StringBuilder().append("Not enough path elements to ignore in output (") .append(ignoreOutputPaths).append(" in ").append(outputName).append(")"); throw new IOException(b.toString()); } if (ignoreSourcePaths >= sourcePath.getNameCount()) { patch.close(); StringBuilder b = new StringBuilder().append("Not enough path elements to ignore in source (") .append(sourcePath).append(" in ").append(sourceName).append(")"); throw new IOException(b.toString()); } sourcePath = sourcePath.subpath(ignoreSourcePaths, sourcePath.getNameCount()); outputPath = outputPath.subpath(ignoreOutputPaths, outputPath.getNameCount()); File sourceFile = sourcePath.toFile(); File outputFile = outputPath.toFile(); if (!(outputFile.getAbsoluteFile().getParentFile().mkdirs() || outputFile.getAbsoluteFile().getParentFile().exists())) { patch.close(); throw new IOException("Failed to create " + outputFile.getAbsolutePath()); } new JarPatcher(patchName, sourceFile.getName()).applyDelta(patch, new ZipFile(sourceFile), new ZipArchiveOutputStream(new FileOutputStream(outputFile)), list); list.close(); }
From source file:com.silverpeas.util.ZipManager.java
/** * Mthode permettant la cration et l'organisation d'un fichier zip en lui passant directement un * flux d'entre// w w w . j av a 2 s . c om * * @param inputStream - flux de donnes enregistrer dans le zip * @param filePathNameToCreate - chemin et nom du fichier port par les donnes du flux dans le * zip * @param outfilename - chemin et nom du fichier zip creer ou complter * @throws IOException */ public static void compressStreamToZip(InputStream inputStream, String filePathNameToCreate, String outfilename) throws IOException { ZipArchiveOutputStream zos = null; try { zos = new ZipArchiveOutputStream(new FileOutputStream(outfilename)); zos.setFallbackToUTF8(true); zos.setCreateUnicodeExtraFields(NOT_ENCODEABLE); zos.setEncoding("UTF-8"); zos.putArchiveEntry(new ZipArchiveEntry(filePathNameToCreate)); IOUtils.copy(inputStream, zos); zos.closeArchiveEntry(); } finally { if (zos != null) { IOUtils.closeQuietly(zos); } } }
From source file:at.spardat.xma.xdelta.test.JarDeltaJarPatcherTest.java
/** * Writes a modified version of zip_Source into target. * * @author S3460/*w ww . j a v a 2 s. c om*/ * @param zipSource the zip source * @param target the target * @return the zip file * @throws Exception the exception */ private ZipFile makeTargetZipFile(ZipFile zipSource, File target) throws Exception { ZipArchiveOutputStream out = new ZipArchiveOutputStream(new FileOutputStream(target)); for (Enumeration<ZipArchiveEntry> enumer = zipSource.getEntries(); enumer.hasMoreElements();) { ZipArchiveEntry sourceEntry = enumer.nextElement(); out.putArchiveEntry(new ZipArchiveEntry(sourceEntry.getName())); byte[] oldBytes = toBytes(zipSource, sourceEntry); byte[] newBytes = getRandomBytes(); byte[] mixedBytes = mixBytes(oldBytes, newBytes); out.write(mixedBytes, 0, mixedBytes.length); out.flush(); out.closeArchiveEntry(); } out.putArchiveEntry(new ZipArchiveEntry("zipentry" + entryMaxSize + 1)); byte[] bytes = getRandomBytes(); out.write(bytes, 0, bytes.length); out.flush(); out.closeArchiveEntry(); out.putArchiveEntry(new ZipArchiveEntry("zipentry" + (entryMaxSize + 2))); out.closeArchiveEntry(); out.flush(); out.finish(); out.close(); return new ZipFile(targetFile); }
From source file:com.fizzed.stork.deploy.Archive.java
static private ArchiveOutputStream newArchiveOutputStream(Path file, String format) throws IOException { switch (format) { case "tar.gz": TarArchiveOutputStream tgzout = new TarArchiveOutputStream( new GzipCompressorOutputStream(Files.newOutputStream(file))); tgzout.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR); tgzout.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); return tgzout; case "zip": return new ZipArchiveOutputStream(Files.newOutputStream(file)); default:/*w w w. j a v a 2 s.com*/ throw new IOException("Unsupported archive file type (we support .tar.gz and .zip)"); } }
From source file:at.spardat.xma.xdelta.JarPatcher.java
/** * Apply delta./*from ww w. j a va2 s.co m*/ * * @param patch the patch * @param source the source * @param output the output * @param list the list * @param prefix the prefix * @throws IOException Signals that an I/O exception has occurred. */ public void applyDelta(ZipFile patch, ZipFile source, ZipArchiveOutputStream output, BufferedReader list, String prefix) throws IOException { String fileName = null; try { for (fileName = (next == null ? list.readLine() : next); fileName != null; fileName = (next == null ? list.readLine() : next)) { if (next != null) next = null; if (!fileName.startsWith(prefix)) { next = fileName; return; } int crcDelim = fileName.lastIndexOf(':'); int crcStart = fileName.lastIndexOf('|'); long crc = Long.valueOf(fileName.substring(crcStart + 1, crcDelim), 16); long crcSrc = Long.valueOf(fileName.substring(crcDelim + 1), 16); fileName = fileName.substring(prefix.length(), crcStart); if ("META-INF/file.list".equalsIgnoreCase(fileName)) continue; if (fileName.contains("!")) { String[] embeds = fileName.split("\\!"); ZipArchiveEntry original = getEntry(source, embeds[0], crcSrc); File originalFile = File.createTempFile("jardelta-tmp-origin-", ".zip"); File outputFile = File.createTempFile("jardelta-tmp-output-", ".zip"); Exception thrown = null; try (FileOutputStream out = new FileOutputStream(originalFile); InputStream in = source.getInputStream(original)) { int read = 0; while (-1 < (read = in.read(buffer))) { out.write(buffer, 0, read); } out.flush(); applyDelta(patch, new ZipFile(originalFile), new ZipArchiveOutputStream(outputFile), list, prefix + embeds[0] + "!"); } catch (Exception e) { thrown = e; throw e; } finally { originalFile.delete(); try (FileInputStream in = new FileInputStream(outputFile)) { if (thrown == null) { ZipArchiveEntry outEntry = copyEntry(original); output.putArchiveEntry(outEntry); int read = 0; while (-1 < (read = in.read(buffer))) { output.write(buffer, 0, read); } output.flush(); output.closeArchiveEntry(); } } finally { outputFile.delete(); } } } else { try { ZipArchiveEntry patchEntry = getEntry(patch, prefix + fileName, crc); if (patchEntry != null) { // new Entry ZipArchiveEntry outputEntry = JarDelta.entryToNewName(patchEntry, fileName); output.putArchiveEntry(outputEntry); if (!patchEntry.isDirectory()) { try (InputStream in = patch.getInputStream(patchEntry)) { int read = 0; while (-1 < (read = in.read(buffer))) { output.write(buffer, 0, read); } } } closeEntry(output, outputEntry, crc); } else { ZipArchiveEntry sourceEntry = getEntry(source, fileName, crcSrc); if (sourceEntry == null) { throw new FileNotFoundException( fileName + " not found in " + sourceName + " or " + patchName); } if (sourceEntry.isDirectory()) { ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry); output.putArchiveEntry(outputEntry); closeEntry(output, outputEntry, crc); continue; } patchEntry = getPatchEntry(patch, prefix + fileName + ".gdiff", crc); if (patchEntry != null) { // changed Entry ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry); outputEntry.setTime(patchEntry.getTime()); output.putArchiveEntry(outputEntry); byte[] sourceBytes = new byte[(int) sourceEntry.getSize()]; try (InputStream sourceStream = source.getInputStream(sourceEntry)) { for (int erg = sourceStream .read(sourceBytes); erg < sourceBytes.length; erg += sourceStream .read(sourceBytes, erg, sourceBytes.length - erg)) ; } InputStream patchStream = patch.getInputStream(patchEntry); GDiffPatcher diffPatcher = new GDiffPatcher(); diffPatcher.patch(sourceBytes, patchStream, output); patchStream.close(); outputEntry.setCrc(crc); closeEntry(output, outputEntry, crc); } else { // unchanged Entry ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry); output.putArchiveEntry(outputEntry); try (InputStream in = source.getInputStream(sourceEntry)) { int read = 0; while (-1 < (read = in.read(buffer))) { output.write(buffer, 0, read); } } output.flush(); closeEntry(output, outputEntry, crc); } } } catch (PatchException pe) { IOException ioe = new IOException(); ioe.initCause(pe); throw ioe; } } } } catch (Exception e) { System.err.println(prefix + fileName); throw e; } finally { source.close(); output.close(); } }
From source file:es.ucm.fdi.util.archive.ZipFormat.java
public void create(ArrayList<File> sources, File destFile, File baseDir) throws IOException { // to avoid modifying input argument ArrayList<File> toAdd = new ArrayList<>(sources); ZipArchiveOutputStream zos = null;/* w ww . j ava 2 s . co m*/ try { zos = new ZipArchiveOutputStream(new FileOutputStream(destFile)); zos.setMethod(ZipArchiveOutputStream.DEFLATED); byte[] b = new byte[1024]; //log.debug("Creating zip file: "+ficheroZip.getName()); for (int i = 0; i < toAdd.size(); i++) { // note: cannot use foreach because sources gets modified File file = toAdd.get(i); // zip standard uses fw slashes instead of backslashes, always String baseName = baseDir.getAbsolutePath() + '/'; String fileName = file.getAbsolutePath().substring(baseName.length()); if (file.isDirectory()) { fileName += '/'; } ZipArchiveEntry entry = new ZipArchiveEntry(fileName); // skip directories - after assuring that their children *will* be included. if (file.isDirectory()) { //log.debug("\tAdding dir "+fileName); for (File child : file.listFiles()) { toAdd.add(child); } zos.putArchiveEntry(entry); continue; } //log.debug("\tAdding file "+fileName); // Add the zip entry and associated data. zos.putArchiveEntry(entry); int n; try (FileInputStream fis = new FileInputStream(file)) { while ((n = fis.read(b)) > -1) { zos.write(b, 0, n); } zos.closeArchiveEntry(); } } } finally { if (zos != null) { zos.finish(); zos.close(); } } }
From source file:com.facebook.buck.util.unarchive.UnzipTest.java
@Test public void testExtractSymlink() throws InterruptedException, IOException { assumeThat(Platform.detect(), Matchers.is(Matchers.not(Platform.WINDOWS))); // Create a simple zip archive using apache's commons-compress to store executable info. try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) { ZipArchiveEntry entry = new ZipArchiveEntry("link.txt"); entry.setUnixMode((int) MostFiles.S_IFLNK); String target = "target.txt"; entry.setSize(target.getBytes(Charsets.UTF_8).length); entry.setMethod(ZipEntry.STORED); zip.putArchiveEntry(entry);/*from w w w .j a v a 2 s . c o m*/ zip.write(target.getBytes(Charsets.UTF_8)); zip.closeArchiveEntry(); } Path extractFolder = tmpFolder.newFolder(); ArchiveFormat.ZIP.getUnarchiver().extractArchive(new DefaultProjectFilesystemFactory(), zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), ExistingFileMode.OVERWRITE); Path link = extractFolder.toAbsolutePath().resolve("link.txt"); assertTrue(Files.isSymbolicLink(link)); assertThat(Files.readSymbolicLink(link).toString(), Matchers.equalTo("target.txt")); }