List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream ZipArchiveOutputStream
public ZipArchiveOutputStream(File file) throws IOException
From source file:org.cloudfoundry.util.FileUtils.java
/** * Converts a the contents of a {@link Path} to a {@link InputStream}. If the {@link Path} is a directory, compresses the full contents of the directory into the stream. If the {@link Path} * is a file, the contents of the file are examined using {@link FileSystems#newFileSystem} starting at the root. This allows both exploded and compressed artifacts to be used interchangeably. * * @param path a {@link Path} representing either a compressed <i>or</i> exploded artifact * @param filter a {@link Predicate} to filter the {@link Path}s that will be added to the {@link InputStream} * @return a {@link InputStream} containing the compressed contents of the {@code path} *//*from www. j av a2s . co m*/ public static InputStream toInputStream(Path path, Predicate<Path> filter) { Path root = normalize(path); try { Path staging = Files.createTempFile(null, null); try (Stream<Path> contents = Files.walk(root); ZipArchiveOutputStream out = new ZipArchiveOutputStream(staging.toFile())) { contents.filter(filter).forEach(p -> write(root, p, out)); } return Files.newInputStream(staging); } catch (IOException e) { throw Exceptions.propagate(e); } }
From source file:org.codehaus.plexus.archiver.jar.JarArchiver.java
/** *//* w w w .j a va 2 s . co m*/ protected boolean createEmptyZip(File zipFile) throws ArchiverException { if (!createEmpty) { return true; } try { getLogger().debug("Building MANIFEST-only jar: " + getDestFile().getAbsolutePath()); zipArchiveOutputStream = new ZipArchiveOutputStream( bufferedOutputStream(fileOutputStream(getDestFile(), "jar"))); zipArchiveOutputStream.setEncoding(getEncoding()); if (isCompress()) { zipArchiveOutputStream.setMethod(ZipArchiveOutputStream.DEFLATED); } else { zipArchiveOutputStream.setMethod(ZipArchiveOutputStream.STORED); } ConcurrentJarCreator ps = new ConcurrentJarCreator(Runtime.getRuntime().availableProcessors()); initZipOutputStream(ps); finalizeZipOutputStream(ps); } catch (IOException ioe) { throw new ArchiverException("Could not create almost empty JAR archive (" + ioe.getMessage() + ")", ioe); } finally { // Close the output stream. //IOUtil.close( zOut ); createEmpty = false; } return true; }
From source file:org.codehaus.plexus.archiver.zip.AbstractZipArchiver.java
private void createArchiveMain() throws ArchiverException, IOException { //noinspection deprecation if (!Archiver.DUPLICATES_SKIP.equals(duplicate)) { //noinspection deprecation setDuplicateBehavior(duplicate); }/*from w w w . j a va 2 s . co m*/ ResourceIterator iter = getResources(); if (!iter.hasNext() && !hasVirtualFiles()) { throw new ArchiverException("You must set at least one file."); } zipFile = getDestFile(); if (zipFile == null) { throw new ArchiverException("You must set the destination " + archiveType + "file."); } if (zipFile.exists() && !zipFile.isFile()) { throw new ArchiverException(zipFile + " isn't a file."); } if (zipFile.exists() && !zipFile.canWrite()) { throw new ArchiverException(zipFile + " is read-only."); } // Whether or not an actual update is required - // we don't need to update if the original file doesn't exist addingNewFiles = true; if (doUpdate && !zipFile.exists()) { doUpdate = false; getLogger().debug("ignoring update attribute as " + archiveType + " doesn't exist."); } success = false; if (doUpdate) { renamedFile = FileUtils.createTempFile("zip", ".tmp", zipFile.getParentFile()); renamedFile.deleteOnExit(); try { FileUtils.rename(zipFile, renamedFile); } catch (SecurityException e) { getLogger().debug(e.toString()); throw new ArchiverException( "Not allowed to rename old file (" + zipFile.getAbsolutePath() + ") to temporary file", e); } catch (IOException e) { getLogger().debug(e.toString()); throw new ArchiverException( "Unable to rename old file (" + zipFile.getAbsolutePath() + ") to temporary file", e); } } String action = doUpdate ? "Updating " : "Building "; getLogger().info(action + archiveType + ": " + zipFile.getAbsolutePath()); if (!skipWriting) { zipArchiveOutputStream = new ZipArchiveOutputStream( bufferedOutputStream(fileOutputStream(zipFile, "zip"))); zipArchiveOutputStream.setEncoding(encoding); zipArchiveOutputStream .setCreateUnicodeExtraFields(ZipArchiveOutputStream.UnicodeExtraFieldPolicy.NOT_ENCODEABLE); zipArchiveOutputStream .setMethod(doCompress ? ZipArchiveOutputStream.DEFLATED : ZipArchiveOutputStream.STORED); zOut = new ConcurrentJarCreator(Runtime.getRuntime().availableProcessors()); } initZipOutputStream(zOut); // Add the new files to the archive. addResources(iter, zOut); // If we've been successful on an update, delete the // temporary file if (doUpdate) { if (!renamedFile.delete()) { getLogger().warn("Warning: unable to delete temporary file " + renamedFile.getName()); } } success = true; }
From source file:org.dataconservancy.packaging.tool.impl.AnnotationDrivenPackageStateSerializerTest.java
@Test public void testDeserializeZipArchiveSimple() throws Exception { // produce a zip archive containing a single serialized stream for this test. ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(baos); ZipArchiveEntry zipEntry = new ZipArchiveEntry(StreamId.APPLICATION_VERSION.name()); zipOut.putArchiveEntry(zipEntry);//from www .j a v a2 s. c om IOUtils.copy(APPLICATION_VERSION_1.getInputStream(), zipOut); zipOut.closeArchiveEntry(); zipOut.close(); state = new PackageState(); when(mockedMarshallerMap.get(StreamId.APPLICATION_VERSION).getUnmarshaller().unmarshal(any(Source.class))) .thenReturn(applicationVersion); ByteArrayInputStream zipIn = new ByteArrayInputStream(baos.toByteArray()); underTest.deserialize(state, StreamId.APPLICATION_VERSION, zipIn); assertNotNull(state.getCreationToolVersion()); assertEquals(applicationVersion, state.getCreationToolVersion()); verify(mockedMarshallerMap.get(StreamId.APPLICATION_VERSION).getUnmarshaller()) .unmarshal(any(Source.class)); }
From source file:org.dataconservancy.packaging.tool.impl.ZipArchiveStreamFactory.java
public ZipArchiveOutputStream newArchiveOutputStream(OutputStream out) { ZipArchiveOutputStream zipOs = new ZipArchiveOutputStream(out); zipOs.setEncoding(encoding);//from w w w . ja va2 s . c o m zipOs.setFallbackToUTF8(fallbackToUTF8); zipOs.setUseLanguageEncodingFlag(useLanguageEncodingFlag); zipOs.setLevel(level); zipOs.setMethod(method); zipOs.setUseZip64(useZip64); return zipOs; }
From source file:org.dbflute.helper.io.compress.DfZipArchiver.java
/** * Compress the directory's elements to archive file. * @param baseDir The base directory to compress. (NotNull) * @param filter The file filter, which doesn't need to accept the base directory. (NotNull) *///www . j a v a 2s .c o m public void compress(File baseDir, FileFilter filter) { if (baseDir == null) { String msg = "The argument 'baseDir' should not be null."; throw new IllegalArgumentException(msg); } if (!baseDir.isDirectory()) { String msg = "The baseDir should be directory but not: " + baseDir; throw new IllegalArgumentException(msg); } if (!baseDir.exists()) { String msg = "Not found the baseDir in the file system: " + baseDir; throw new IllegalArgumentException(msg); } OutputStream out = null; ZipArchiveOutputStream archive = null; try { out = new BufferedOutputStream(new FileOutputStream(_zipFile)); archive = new ZipArchiveOutputStream(out); archive.setEncoding("UTF-8"); addAll(archive, baseDir, baseDir, filter); archive.finish(); archive.flush(); out.flush(); } catch (IOException e) { String msg = "Failed to compress the files to " + _zipFile.getPath(); throw new IllegalStateException(msg, e); } finally { if (archive != null) { try { archive.close(); } catch (IOException ignored) { } } if (out != null) { try { out.close(); } catch (IOException ignored) { } } } }
From source file:org.dspace.content.packager.AbstractMETSDisseminator.java
/** * Make a Zipped up METS package for the given DSpace Object * * @param context DSpace Context/*from ww w. j a v a 2s . c o m*/ * @param dso The DSpace Object * @param params Parameters to the Packager script * @param pkg Package output stream * @throws PackageValidationException * @throws AuthorizeException * @throws SQLException * @throws IOException */ protected void writeZipPackage(Context context, DSpaceObject dso, PackageParameters params, OutputStream pkg) throws PackageValidationException, CrosswalkException, MetsException, AuthorizeException, SQLException, IOException { long lmTime = 0; if (dso.getType() == Constants.ITEM) { lmTime = ((Item) dso).getLastModified().getTime(); } // map of extra streams to put in Zip (these are located during makeManifest()) MdStreamCache extraStreams = new MdStreamCache(); ZipArchiveOutputStream zip = new ZipArchiveOutputStream(pkg); zip.setComment("METS archive created by DSpace " + Util.getSourceVersion()); Mets manifest = makeManifest(context, dso, params, extraStreams); // copy extra (metadata, license, etc) bitstreams into zip, update manifest if (extraStreams != null) { for (Map.Entry<MdRef, InputStream> ment : extraStreams.getMap().entrySet()) { MdRef ref = ment.getKey(); // Both Deposit Licenses & CC Licenses which are referenced as "extra streams" may already be // included in our Package (if their bundles are already included in the <filSec> section of manifest). // So, do a special check to see if we need to link up extra License <mdRef> entries to the bitstream in the <fileSec>. // (this ensures that we don't accidentally add the same License file to our package twice) linkLicenseRefsToBitstreams(context, params, dso, ref); //If this 'mdRef' is NOT already linked up to a file in the package, // then its file must be missing. So, we are going to add a new // file to the Zip package. if (ref.getXlinkHref() == null || ref.getXlinkHref().isEmpty()) { InputStream is = ment.getValue(); // create a hopefully unique filename within the Zip String fname = gensym("metadata"); // link up this 'mdRef' to point to that file ref.setXlinkHref(fname); if (log.isDebugEnabled()) { log.debug("Writing EXTRA stream to Zip: " + fname); } //actually add the file to the Zip package ZipArchiveEntry ze = new ZipArchiveEntry(fname); if (lmTime != 0) { ze.setTime(lmTime); } else //Set a default modified date so that checksum of Zip doesn't change if Zip contents are unchanged { ze.setTime(DEFAULT_MODIFIED_DATE); } zip.putArchiveEntry(ze); Utils.copy(is, zip); zip.closeArchiveEntry(); is.close(); } } } // write manifest after metadata. ZipArchiveEntry me = new ZipArchiveEntry(METSManifest.MANIFEST_FILE); if (lmTime != 0) { me.setTime(lmTime); } else //Set a default modified date so that checksum of Zip doesn't change if Zip contents are unchanged { me.setTime(DEFAULT_MODIFIED_DATE); } zip.putArchiveEntry(me); // can only validate now after fixing up extraStreams // note: only validate METS if specified (default = true) if (params.getBooleanProperty("validate", true)) { manifest.validate(new MetsValidator()); } manifest.write(new MetsWriter(zip)); zip.closeArchiveEntry(); //write any bitstreams associated with DSpace object to zip package addBitstreamsToZip(context, dso, params, zip); zip.close(); }
From source file:org.eclipse.cbi.maven.plugins.macsigner.SignMojo.java
/** * Signs the file./* w w w .j a v a 2 s. c o m*/ * @param file * @throws MojoExecutionException */ protected void signArtifact(File file) throws MojoExecutionException { try { if (!file.isDirectory()) { getLog().warn(file + " is a not a directory, the artifact is not signed."); return; // Expecting the .app directory } workdir.mkdirs(); //zipping the directory getLog().debug("Building zip: " + file); File zipFile = File.createTempFile(UNSIGNED_ZIP_FILE_NAME, ZIP_EXT, workdir); ZipArchiveOutputStream zos = new ZipArchiveOutputStream(new FileOutputStream(zipFile)); createZip(file, zos); zos.finish(); zos.close(); final long start = System.currentTimeMillis(); String base_path = getParentDirAbsolutePath(file); File zipDir = new File(base_path); File tempSigned = File.createTempFile(SIGNED_ZIP_FILE_NAME, ZIP_EXT, workdir); File tempSignedCopy = new File(base_path + File.separator + tempSigned.getName()); if (tempSignedCopy.exists()) { String msg = "Could not copy signed file because a file with the same name already exists: " + tempSignedCopy; if (continueOnFail) { getLog().warn(msg); } else { throw new MojoExecutionException(msg); } } tempSignedCopy.createNewFile(); FileUtils.copyFile(tempSigned, tempSignedCopy); try { signFile(zipFile, tempSigned); if (!tempSigned.canRead() || tempSigned.length() <= 0) { String msg = "Could not sign artifact " + file; if (continueOnFail) { getLog().warn(msg); } else { throw new MojoExecutionException(msg); } } // unzipping response getLog().debug("Decompressing zip: " + file); unZip(tempSigned, zipDir); } finally { if (!zipFile.delete()) { getLog().warn("Temporary file failed to delete: " + zipFile); } if (!tempSigned.delete()) { getLog().warn("Temporary file failed to delete: " + tempSigned); } if (!tempSignedCopy.delete()) { getLog().warn("Temporary file failed to delete: " + tempSignedCopy); } } getLog().info("Signed " + file + " in " + ((System.currentTimeMillis() - start) / 1000) + " seconds."); } catch (IOException e) { String msg = "Could not sign file " + file + ": " + e.getMessage(); if (continueOnFail) { getLog().warn(msg); } else { throw new MojoExecutionException(msg, e); } } finally { executableFiles.clear(); } }
From source file:org.eclipse.jgit.archive.ZipFormat.java
/** * @since 4.0//from w w w .j a v a 2 s . c om */ public ArchiveOutputStream createArchiveOutputStream(OutputStream s, Map<String, Object> o) throws IOException { return applyFormatOptions(new ZipArchiveOutputStream(s), o); }
From source file:org.egov.infra.utils.FileUtils.java
public static Path addFilesToZip(File... files) { try {//www. j a va 2 s . co m Path zipFile = Files.createTempFile(UUID.randomUUID().toString(), ZIP_FILE_EXTN); try (FileOutputStream zipFileStream = new FileOutputStream(zipFile.toFile()); ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(zipFileStream)) { for (File file : files) { zipOutput.putArchiveEntry(new ZipArchiveEntry(file, file.getName())); zipOutput.write(IOUtils.toByteArray(file.toURI())); zipOutput.closeArchiveEntry(); } return zipFile; } } catch (IOException e) { throw new ApplicationRuntimeException("Error occurred while adding files to ZIP", e); } }