List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream setLevel
public void setLevel(int level)
From source file:cz.muni.fi.xklinec.zipstream.App.java
/** * Entry point. //from w ww . j av a2 s . c o m * * @param args * @throws FileNotFoundException * @throws IOException * @throws NoSuchFieldException * @throws ClassNotFoundException * @throws NoSuchMethodException */ public static void main(String[] args) throws FileNotFoundException, IOException, NoSuchFieldException, ClassNotFoundException, NoSuchMethodException, InterruptedException { OutputStream fos = null; InputStream fis = null; if ((args.length != 0 && args.length != 2)) { System.err.println(String.format("Usage: app.jar source.apk dest.apk")); return; } else if (args.length == 2) { System.err.println( String.format("Will use file [%s] as input file and [%s] as output file", args[0], args[1])); fis = new FileInputStream(args[0]); fos = new FileOutputStream(args[1]); } else if (args.length == 0) { System.err.println(String.format("Will use file [STDIN] as input file and [STDOUT] as output file")); fis = System.in; fos = System.out; } final Deflater def = new Deflater(9, true); ZipArchiveInputStream zip = new ZipArchiveInputStream(fis); // List of postponed entries for further "processing". List<PostponedEntry> peList = new ArrayList<PostponedEntry>(6); // Output stream ZipArchiveOutputStream zop = new ZipArchiveOutputStream(fos); zop.setLevel(9); // Read the archive ZipArchiveEntry ze = zip.getNextZipEntry(); while (ze != null) { ZipExtraField[] extra = ze.getExtraFields(true); byte[] lextra = ze.getLocalFileDataExtra(); UnparseableExtraFieldData uextra = ze.getUnparseableExtraFieldData(); byte[] uextrab = uextra != null ? uextra.getLocalFileDataData() : null; // ZipArchiveOutputStream.DEFLATED // // Data for entry byte[] byteData = Utils.readAll(zip); byte[] deflData = new byte[0]; int infl = byteData.length; int defl = 0; // If method is deflated, get the raw data (compress again). if (ze.getMethod() == ZipArchiveOutputStream.DEFLATED) { def.reset(); def.setInput(byteData); def.finish(); byte[] deflDataTmp = new byte[byteData.length * 2]; defl = def.deflate(deflDataTmp); deflData = new byte[defl]; System.arraycopy(deflDataTmp, 0, deflData, 0, defl); } System.err.println(String.format( "ZipEntry: meth=%d " + "size=%010d isDir=%5s " + "compressed=%07d extra=%d lextra=%d uextra=%d " + "comment=[%s] " + "dataDesc=%s " + "UTF8=%s " + "infl=%07d defl=%07d " + "name [%s]", ze.getMethod(), ze.getSize(), ze.isDirectory(), ze.getCompressedSize(), extra != null ? extra.length : -1, lextra != null ? lextra.length : -1, uextrab != null ? uextrab.length : -1, ze.getComment(), ze.getGeneralPurposeBit().usesDataDescriptor(), ze.getGeneralPurposeBit().usesUTF8ForNames(), infl, defl, ze.getName())); final String curName = ze.getName(); // META-INF files should be always on the end of the archive, // thus add postponed files right before them if (curName.startsWith("META-INF") && peList.size() > 0) { System.err.println( "Now is the time to put things back, but at first, I'll perform some \"facelifting\"..."); // Simulate som evil being done Thread.sleep(5000); System.err.println("OK its done, let's do this."); for (PostponedEntry pe : peList) { System.err.println( "Adding postponed entry at the end of the archive! deflSize=" + pe.deflData.length + "; inflSize=" + pe.byteData.length + "; meth: " + pe.ze.getMethod()); pe.dump(zop, false); } peList.clear(); } // Capturing interesting files for us and store for later. // If the file is not interesting, send directly to the stream. if ("classes.dex".equalsIgnoreCase(curName) || "AndroidManifest.xml".equalsIgnoreCase(curName)) { System.err.println("### Interesting file, postpone sending!!!"); PostponedEntry pe = new PostponedEntry(ze, byteData, deflData); peList.add(pe); } else { // Write ZIP entry to the archive zop.putArchiveEntry(ze); // Add file data to the stream zop.write(byteData, 0, infl); zop.closeArchiveEntry(); } ze = zip.getNextZipEntry(); } // Cleaning up stuff zip.close(); fis.close(); zop.finish(); zop.close(); fos.close(); System.err.println("THE END!"); }
From source file:jetbrains.exodus.util.CompressBackupUtil.java
@NotNull public static File backup(@NotNull final Backupable target, @NotNull final File backupRoot, @Nullable final String backupNamePrefix, final boolean zip) throws Exception { if (!backupRoot.exists() && !backupRoot.mkdirs()) { throw new IOException("Failed to create " + backupRoot.getAbsolutePath()); }/*from w ww . j a va 2s .c om*/ final File backupFile; final BackupStrategy strategy = target.getBackupStrategy(); strategy.beforeBackup(); try { final ArchiveOutputStream archive; if (zip) { final String fileName = getTimeStampedZipFileName(); backupFile = new File(backupRoot, backupNamePrefix == null ? fileName : backupNamePrefix + fileName); final ZipArchiveOutputStream zipArchive = new ZipArchiveOutputStream( new BufferedOutputStream(new FileOutputStream(backupFile))); zipArchive.setLevel(Deflater.BEST_COMPRESSION); archive = zipArchive; } else { final String fileName = getTimeStampedTarGzFileName(); backupFile = new File(backupRoot, backupNamePrefix == null ? fileName : backupNamePrefix + fileName); archive = new TarArchiveOutputStream( new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(backupFile)))); } try (ArchiveOutputStream aos = archive) { for (final BackupStrategy.FileDescriptor fd : strategy.listFiles()) { if (strategy.isInterrupted()) { break; } final File file = fd.getFile(); if (file.isFile()) { final long fileSize = Math.min(fd.getFileSize(), strategy.acceptFile(file)); if (fileSize > 0L) { archiveFile(aos, fd.getPath(), file, fileSize); } } } } if (strategy.isInterrupted()) { logger.info("Backup interrupted, deleting \"" + backupFile.getName() + "\"..."); IOUtil.deleteFile(backupFile); } else { logger.info("Backup file \"" + backupFile.getName() + "\" created."); } } catch (Throwable t) { strategy.onError(t); throw ExodusException.toExodusException(t, "Backup failed"); } finally { strategy.afterBackup(); } return backupFile; }
From source file:com.atolcd.web.scripts.ZipContents.java
public void createZipFile(List<String> nodeIds, OutputStream os, boolean noaccent) throws IOException { File zip = null;/* w w w . j a v a2 s . c om*/ try { if (nodeIds != null && !nodeIds.isEmpty()) { zip = TempFileProvider.createTempFile(TEMP_FILE_PREFIX, ZIP_EXTENSION); FileOutputStream stream = new FileOutputStream(zip); CheckedOutputStream checksum = new CheckedOutputStream(stream, new Adler32()); BufferedOutputStream buff = new BufferedOutputStream(checksum); ZipArchiveOutputStream out = new ZipArchiveOutputStream(buff); out.setEncoding(encoding); out.setMethod(ZipArchiveOutputStream.DEFLATED); out.setLevel(Deflater.BEST_COMPRESSION); if (logger.isDebugEnabled()) { logger.debug("Using encoding '" + encoding + "' for zip file."); } try { for (String nodeId : nodeIds) { NodeRef node = new NodeRef(storeRef, nodeId); addToZip(node, out, noaccent, ""); } } catch (Exception e) { logger.error(e.getMessage(), e); throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } finally { out.close(); buff.close(); checksum.close(); stream.close(); if (nodeIds.size() > 0) { InputStream in = new FileInputStream(zip); try { byte[] buffer = new byte[BUFFER_SIZE]; int len; while ((len = in.read(buffer)) > 0) { os.write(buffer, 0, len); } } finally { IOUtils.closeQuietly(in); } } } } } catch (Exception e) { logger.error(e.getMessage(), e); throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } finally { // try and delete the temporary file if (zip != null) { zip.delete(); } } }
From source file:cz.cuni.mff.ufal.AllBitstreamZipArchiveReader.java
@Override public void generate() throws IOException, SAXException, ProcessingException { if (redirect != NO_REDIRECTION) { return;//w w w . ja v a 2s . c o m } String name = item.getName() + ".zip"; try { // first write everything to a temp file String tempDir = ConfigurationManager.getProperty("upload.temp.dir"); String fn = tempDir + File.separator + "SWORD." + item.getID() + "." + UUID.randomUUID().toString() + ".zip"; OutputStream outStream = new FileOutputStream(new File(fn)); ZipArchiveOutputStream zip = new ZipArchiveOutputStream(outStream); zip.setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy.ALWAYS); zip.setLevel(Deflater.NO_COMPRESSION); ConcurrentMap<String, AtomicInteger> usedFilenames = new ConcurrentHashMap<String, AtomicInteger>(); Bundle[] originals = item.getBundles("ORIGINAL"); if (needsZip64) { zip.setUseZip64(Zip64Mode.Always); } for (Bundle original : originals) { Bitstream[] bss = original.getBitstreams(); for (Bitstream bitstream : bss) { String filename = bitstream.getName(); String uniqueName = createUniqueFilename(filename, usedFilenames); ZipArchiveEntry ze = new ZipArchiveEntry(uniqueName); zip.putArchiveEntry(ze); InputStream is = bitstream.retrieve(); Utils.copy(is, zip); zip.closeArchiveEntry(); is.close(); } } zip.close(); File file = new File(fn); zipFileSize = file.length(); zipInputStream = new TempFileInputStream(file); } catch (AuthorizeException e) { log.error(e.getMessage(), e); throw new ProcessingException("You do not have permissions to access one or more files."); } catch (Exception e) { log.error(e.getMessage(), e); throw new ProcessingException("Could not create ZIP, please download the files one by one. " + "The error has been stored and will be solved by our technical team."); } // Log download statistics for (int bitstreamID : bitstreamIDs) { DSpaceApi.updateFileDownloadStatistics(userID, bitstreamID); } response.setDateHeader("Last-Modified", item.getLastModified().getTime()); // Try and make the download file name formated for each browser. try { String agent = request.getHeader("USER-AGENT"); if (agent != null && agent.contains("MSIE")) { name = URLEncoder.encode(name, "UTF8"); } else if (agent != null && agent.contains("Mozilla")) { name = MimeUtility.encodeText(name, "UTF8", "B"); } } catch (UnsupportedEncodingException see) { name = "item_" + item.getID() + ".zip"; } response.setHeader("Content-Disposition", "attachment;filename=" + name); byte[] buffer = new byte[BUFFER_SIZE]; int length = -1; try { response.setHeader("Content-Length", String.valueOf(this.zipFileSize)); while ((length = this.zipInputStream.read(buffer)) > -1) { out.write(buffer, 0, length); } out.flush(); } finally { try { if (this.zipInputStream != null) { this.zipInputStream.close(); } if (out != null) { out.close(); } } catch (IOException ioe) { // Closing the stream threw an IOException but do we want this to propagate up to Cocoon? // No point since the user has already got the file contents. log.warn("Caught IO exception when closing a stream: " + ioe.getMessage()); } } }
From source file:fr.itldev.koya.alfservice.KoyaContentService.java
/** * * @param nodeRefs//from w ww .j a v a2 s . c o m * @return * @throws KoyaServiceException */ public File zip(List<String> nodeRefs) throws KoyaServiceException { File tmpZipFile = null; try { tmpZipFile = TempFileProvider.createTempFile("tmpDL", ".zip"); FileOutputStream fos = new FileOutputStream(tmpZipFile); CheckedOutputStream checksum = new CheckedOutputStream(fos, new Adler32()); BufferedOutputStream buff = new BufferedOutputStream(checksum); ZipArchiveOutputStream zipStream = new ZipArchiveOutputStream(buff); // NOTE: This encoding allows us to workaround bug... // http://bugs.sun.com/bugdatabase/view_bug.do;:WuuT?bug_id=4820807 zipStream.setEncoding("UTF-8"); zipStream.setMethod(ZipArchiveOutputStream.DEFLATED); zipStream.setLevel(Deflater.BEST_COMPRESSION); zipStream.setCreateUnicodeExtraFields(ZipArchiveOutputStream.UnicodeExtraFieldPolicy.ALWAYS); zipStream.setUseLanguageEncodingFlag(true); zipStream.setFallbackToUTF8(true); try { for (String nodeRef : nodeRefs) { addToZip(koyaNodeService.getNodeRef(nodeRef), zipStream, ""); } } catch (IOException e) { logger.error(e.getMessage(), e); throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } finally { zipStream.close(); buff.close(); checksum.close(); fos.close(); } } catch (IOException | WebScriptException e) { logger.error(e.getMessage(), e); throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } return tmpZipFile; }
From source file:com.naryx.tagfusion.expression.function.file.Zip.java
/** * Performing Zip() operation/*from ww w . j ava 2 s. c om*/ * * @param session * @param zipfile * @param src * @param recurse * @param prefixx * @param compLvl * @param filter * @param overwrite * @param newpath * @throws cfmRunTimeException * @throws IOException */ protected void zipOperation(cfSession session, ZipArchiveOutputStream zipOut, File src, boolean recurse, String prefix, int compLvl, FilenameFilter filter, String newpath) throws cfmRunTimeException { if (src != null) { FileInputStream nextFileIn; ZipArchiveEntry nextEntry = null; byte[] buffer = new byte[4096]; int readBytes; zipOut.setLevel(compLvl); try { List<File> files = new ArrayList<File>(); int srcDirLen; if (src.isFile()) { String parentPath = src.getParent(); srcDirLen = parentPath.endsWith(File.separator) ? parentPath.length() : parentPath.length() + 1; files.add(src); } else { String parentPath = src.getAbsolutePath(); srcDirLen = parentPath.endsWith(File.separator) ? parentPath.length() : parentPath.length() + 1; getFiles(src, files, recurse, filter); } int noFiles = files.size(); File nextFile; boolean isDir; for (int i = 0; i < noFiles; i++) { nextFile = (File) files.get(i); isDir = nextFile.isDirectory(); if (noFiles == 1 && newpath != null) { // NEWPATH nextEntry = new ZipArchiveEntry(newpath.replace('\\', '/') + (isDir ? "/" : "")); } else { // PREFIX nextEntry = new ZipArchiveEntry( prefix + nextFile.getAbsolutePath().substring(srcDirLen).replace('\\', '/') + (isDir ? "/" : "")); } try { zipOut.putArchiveEntry(nextEntry); } catch (IOException e) { throwException(session, "Failed to add entry to zip file [" + nextEntry + "]. Reason: " + e.getMessage()); } if (!isDir) { nextEntry.setTime(nextFile.lastModified()); nextFileIn = new FileInputStream(nextFile); try { while (nextFileIn.available() > 0) { readBytes = nextFileIn.read(buffer); zipOut.write(buffer, 0, readBytes); } zipOut.flush(); } catch (IOException e) { throwException(session, "Failed to write entry [" + nextEntry + "] to zip file. Reason: " + e.getMessage()); } finally { // nextEntry close StreamUtil.closeStream(nextFileIn); } } zipOut.closeArchiveEntry(); } } catch (IOException ioe) { throwException(session, "Failed to create zip file: " + ioe.getMessage()); } } }
From source file:fr.gael.dhus.datastore.processing.impl.ProcessProductPrepareDownload.java
/** * Creates a zip file at the specified path with the contents of the * specified directory./*from w ww .j a v a 2s .c o m*/ * @param Input directory path. The directory were is located directory to archive. * @param The full path of the zip file. * @return the checksum accordig to fr.gael.dhus.datastore.processing.impl.zip.digest variable. * @throws IOException If anything goes wrong */ protected Map<String, String> processZip(String inpath, File output) throws IOException { // Retrieve configuration settings String[] algorithms = cfgManager.getDownloadConfiguration().getChecksumAlgorithms().split(","); int compressionLevel = cfgManager.getDownloadConfiguration().getCompressionLevel(); FileOutputStream fOut = null; BufferedOutputStream bOut = null; ZipArchiveOutputStream tOut = null; MultipleDigestOutputStream dOut = null; try { fOut = new FileOutputStream(output); if ((algorithms != null) && (algorithms.length > 0)) { try { dOut = new MultipleDigestOutputStream(fOut, algorithms); bOut = new BufferedOutputStream(dOut); } catch (NoSuchAlgorithmException e) { logger.error("Problem computing checksum algorithms.", e); dOut = null; bOut = new BufferedOutputStream(fOut); } } else bOut = new BufferedOutputStream(fOut); tOut = new ZipArchiveOutputStream(bOut); tOut.setLevel(compressionLevel); addFileToZip(tOut, inpath, ""); } finally { try { tOut.finish(); tOut.close(); bOut.close(); if (dOut != null) dOut.close(); fOut.close(); } catch (Exception e) { logger.error("Exception raised during ZIP stream close", e); } } if (dOut != null) { Map<String, String> checksums = new HashMap<String, String>(); for (String algorithm : algorithms) { String chk = dOut.getMessageDigestAsHexadecimalString(algorithm); if (chk != null) checksums.put(algorithm, chk); } return checksums; } return null; }
From source file:fr.gael.dhus.datastore.processing.ProcessingManager.java
/** * Creates a zip file at the specified path with the contents of the * specified directory./*from w w w . j a va 2s .co m*/ * * @param Input directory path. The directory were is located directory to * archive. * @param The full path of the zip file. * @return the checksum accordig to * fr.gael.dhus.datastore.processing.impl.zip.digest variable. * @throws IOException If anything goes wrong */ private Map<String, String> processZip(String inpath, File output) throws IOException { // Retrieve configuration settings String[] algorithms = cfgManager.getDownloadConfiguration().getChecksumAlgorithms().split(","); int compressionLevel = cfgManager.getDownloadConfiguration().getCompressionLevel(); FileOutputStream fOut = null; BufferedOutputStream bOut = null; ZipArchiveOutputStream tOut = null; MultipleDigestOutputStream dOut = null; try { fOut = new FileOutputStream(output); if ((algorithms != null) && (algorithms.length > 0)) { try { dOut = new MultipleDigestOutputStream(fOut, algorithms); bOut = new BufferedOutputStream(dOut); } catch (NoSuchAlgorithmException e) { LOGGER.error("Problem computing checksum algorithms.", e); dOut = null; bOut = new BufferedOutputStream(fOut); } } else bOut = new BufferedOutputStream(fOut); tOut = new ZipArchiveOutputStream(bOut); tOut.setLevel(compressionLevel); addFileToZip(tOut, inpath, ""); } finally { try { tOut.finish(); tOut.close(); bOut.close(); if (dOut != null) dOut.close(); fOut.close(); } catch (Exception e) { LOGGER.error("Exception raised during ZIP stream close", e); } } if (dOut != null) { Map<String, String> checksums = new HashMap<String, String>(); for (String algorithm : algorithms) { String chk = dOut.getMessageDigestAsHexadecimalString(algorithm); if (chk != null) checksums.put(algorithm, chk); } return checksums; } return null; }
From source file:org.apache.ant.compress.taskdefs.Zip.java
private void configure(ZipArchiveOutputStream o) { o.setLevel(level); o.setComment(comment);/*from w w w. j ava 2 s. c o m*/ o.setFallbackToUTF8(fallBackToUTF8); o.setUseLanguageEncodingFlag(useLanguageEncodingFlag); o.setCreateUnicodeExtraFields(createUnicodeExtraFields.getPolicy()); o.setUseZip64(zip64Mode.getPolicy()); }
From source file:org.apache.sis.internal.maven.Assembler.java
/** * Creates the distribution file./*from ww w .jav a 2 s. c o m*/ * * @throws MojoExecutionException if the plugin execution failed. */ @Override public void execute() throws MojoExecutionException { final File sourceDirectory = new File(rootDirectory, ARTIFACT_PATH); if (!sourceDirectory.isDirectory()) { throw new MojoExecutionException("Directory not found: " + sourceDirectory); } final File targetDirectory = new File(rootDirectory, TARGET_DIRECTORY); final String version = project.getVersion(); final String artifactBase = FINALNAME_PREFIX + version; try { final File targetFile = new File(distributionDirectory(targetDirectory), artifactBase + ".zip"); final ZipArchiveOutputStream zip = new ZipArchiveOutputStream(targetFile); try { zip.setLevel(9); appendRecursively(sourceDirectory, artifactBase, zip, new byte[8192]); /* * At this point, all the "application/sis-console/src/main/artifact" and sub-directories * have been zipped. Now generate the Pack200 file and zip it directly (without creating * a temporary "sis.pack.gz" file). */ final Packer packer = new Packer(project.getName(), project.getUrl(), version, targetDirectory); final ZipArchiveEntry entry = new ZipArchiveEntry( artifactBase + '/' + LIB_DIRECTORY + '/' + FATJAR_FILE + PACK_EXTENSION); entry.setMethod(ZipArchiveEntry.STORED); zip.putArchiveEntry(entry); packer.preparePack200(FATJAR_FILE + ".jar").pack(new FilterOutputStream(zip) { /* * Closes the archive entry, not the ZIP file. */ @Override public void close() throws IOException { zip.closeArchiveEntry(); } }); } finally { zip.close(); } } catch (IOException e) { throw new MojoExecutionException(e.getLocalizedMessage(), e); } }