Example usage for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream close

List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream close

Introduction

In this page you can find the example usage for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with the stream.

Usage

From source file:org.beangle.commons.archiver.ZipUtils.java

public static File zip(List<String> fileNames, String zipPath, String encoding) {
    try {/*from w  ww  .j a va 2  s  .  c o m*/
        FileOutputStream f = new FileOutputStream(zipPath);
        ZipArchiveOutputStream zos = (ZipArchiveOutputStream) new ArchiveStreamFactory()
                .createArchiveOutputStream(ArchiveStreamFactory.ZIP, f);
        if (null != encoding) {
            zos.setEncoding(encoding);
        }
        for (int i = 0; i < fileNames.size(); i++) {
            String fileName = fileNames.get(i);
            String entryName = StringUtils.substringAfterLast(fileName, File.separator);
            ZipArchiveEntry entry = new ZipArchiveEntry(entryName);
            zos.putArchiveEntry(entry);
            FileInputStream fis = new FileInputStream(fileName);
            IOUtils.copy(fis, zos);
            fis.close();
            zos.closeArchiveEntry();
        }
        zos.close();
        return new File(zipPath);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.beangle.ems.util.ZipUtils.java

/**
 * <p>/*  www.  j  a va  2 s .co m*/
 * zip.
 * </p>
 * 
 * @param fileNames a {@link java.util.List} object.
 * @param zipPath a {@link java.lang.String} object.
 * @param encoding a {@link java.lang.String} object.
 * @return a {@link java.io.File} object.
 */
public static File zip(List<String> fileNames, String zipPath, String encoding) {
    try {
        FileOutputStream f = new FileOutputStream(zipPath);
        ZipArchiveOutputStream zos = (ZipArchiveOutputStream) new ArchiveStreamFactory()
                .createArchiveOutputStream(ArchiveStreamFactory.ZIP, f);
        if (null != encoding) {
            zos.setEncoding(encoding);
        }
        for (int i = 0; i < fileNames.size(); i++) {
            String fileName = fileNames.get(i);
            String entryName = Strings.substringAfterLast(fileName, File.separator);
            ZipArchiveEntry entry = new ZipArchiveEntry(entryName);
            zos.putArchiveEntry(entry);
            FileInputStream fis = new FileInputStream(fileName);
            IOs.copy(fis, zos);
            fis.close();
            zos.closeArchiveEntry();
        }
        zos.close();
        return new File(zipPath);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.betaconceptframework.astroboa.engine.jcr.io.SerializationBean.java

private void serializeContentToZip(SerializationReport serializationReport, Session session,
        SerializationConfiguration serializationConfiguration, String filePath, String filename,
        ContentObjectCriteria contentObjectCriteria) throws Exception {

    File zipFile = createSerializationFile(filePath, filename);

    OutputStream out = null;/*ww w  .  java  2  s.  co m*/
    ZipArchiveOutputStream os = null;

    try {
        out = new FileOutputStream(zipFile);
        os = (ZipArchiveOutputStream) new ArchiveStreamFactory().createArchiveOutputStream("zip", out);

        os.setFallbackToUTF8(true);

        addContentToZip(os, serializationReport, session, serializationConfiguration, filename,
                contentObjectCriteria);

        os.finish();
        os.close();
    } catch (Exception e) {
        serializationReport.getErrors().add(e.getMessage());

        throw e;
    } finally {

        if (out != null) {
            org.apache.commons.io.IOUtils.closeQuietly(out);

            out = null;
        }

        if (os != null) {
            org.apache.commons.io.IOUtils.closeQuietly(os);

            os = null;
        }

        if (CollectionUtils.isNotEmpty(serializationReport.getErrors())) {
            //Delete zipfile
            if (zipFile != null && zipFile.exists()) {
                zipFile.delete();
            }
        }

        zipFile = null;

    }

}

From source file:org.betaconceptframework.astroboa.test.engine.AbstractRepositoryTest.java

protected void serializeUsingJCR(CmsEntityType cmsEntity) {

     long start = System.currentTimeMillis();

     String repositoryHomeDir = AstroboaClientContextHolder.getActiveClientContext().getRepositoryContext()
             .getCmsRepository().getRepositoryHomeDirectory();

     File serializationHomeDir = new File(
             repositoryHomeDir + File.separator + CmsConstants.SERIALIZATION_DIR_NAME);

     File zipFile = new File(serializationHomeDir,
             "document" + DateUtils.format(Calendar.getInstance(), "ddMMyyyyHHmmss.sss") + ".zip");

     OutputStream out = null;//  ww  w  .  j a  v a 2 s.  co  m
     ZipArchiveOutputStream os = null;

     try {

         if (!zipFile.exists()) {
             FileUtils.touch(zipFile);
         }

         out = new FileOutputStream(zipFile);
         os = (ZipArchiveOutputStream) new ArchiveStreamFactory().createArchiveOutputStream("zip", out);

         os.setFallbackToUTF8(true);

         //Serialize all repository using JCR
         os.putArchiveEntry(new ZipArchiveEntry("document-view.xml"));

         final Session session = getSession();

         switch (cmsEntity) {
         case OBJECT:
             session.exportDocumentView(JcrNodeUtils.getContentObjectRootNode(session).getPath(), os, false,
                     false);
             break;
         case REPOSITORY_USER:
             session.exportDocumentView(JcrNodeUtils.getRepositoryUserRootNode(session).getPath(), os, false,
                     false);
             break;
         case TAXONOMY:
             session.exportDocumentView(JcrNodeUtils.getTaxonomyRootNode(session).getPath(), os, false, false);
             break;
         case ORGANIZATION_SPACE:
             session.exportDocumentView(JcrNodeUtils.getOrganizationSpaceNode(session).getPath(), os, false,
                     false);
             break;
         case REPOSITORY:
             session.exportDocumentView(JcrNodeUtils.getCMSSystemNode(session).getPath(), os, false, false);
             break;

         default:
             break;
         }

         os.closeArchiveEntry();

         os.finish();
         os.close();

     } catch (Exception e) {
         throw new CmsException(e);
     } finally {
         if (out != null) {
             IOUtils.closeQuietly(out);
         }

         if (os != null) {
             IOUtils.closeQuietly(os);
         }
         long serialzationDuration = System.currentTimeMillis() - start;

         logger.debug("Export entities using JCR finished in {} ",
                 DurationFormatUtils.formatDurationHMS(serialzationDuration));
     }
 }

From source file:org.codehaus.plexus.archiver.zip.ConcurrentJarCreator.java

public void writeTo(ZipArchiveOutputStream targetStream)
        throws IOException, ExecutionException, InterruptedException {
    metaInfDir.writeTo(targetStream);// w  w w . j  a va 2 s .  c o  m
    manifest.writeTo(targetStream);
    directories.writeTo(targetStream);
    parallelScatterZipCreator.writeTo(targetStream);
    long startAt = System.currentTimeMillis();
    targetStream.close();
    zipCloseElapsed = System.currentTimeMillis() - startAt;
    manifest.close();
    directories.close();
}

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);/* ww  w  .  j a va  2 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.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)
 *//*from  w  w w. j  a va 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  va 2s.  com*/
 * @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  ww .ja  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.ngrinder.common.util.CompressionUtil.java

/**
 * Zip the given src into the given output stream.
 * /*from   ww  w  . j ava  2 s.c o m*/
 * @param src
 *            src to be zipped
 * @param os
 *            output stream
 * @param charsetName
 *            character set to be used
 * @param includeSrc
 *            true if src will be included.
 * @throws IOException
 *             IOException
 */
public static void zip(File src, OutputStream os, String charsetName, boolean includeSrc) throws IOException {
    ZipArchiveOutputStream zos = new ZipArchiveOutputStream(os);
    zos.setEncoding(charsetName);
    FileInputStream fis;

    int length;
    ZipArchiveEntry ze;
    byte[] buf = new byte[8 * 1024];
    String name;

    Stack<File> stack = new Stack<File>();
    File root;
    if (src.isDirectory()) {
        if (includeSrc) {
            stack.push(src);
            root = src.getParentFile();
        } else {
            File[] fs = src.listFiles();
            for (int i = 0; i < fs.length; i++) {
                stack.push(fs[i]);
            }
            root = src;
        }
    } else {
        stack.push(src);
        root = src.getParentFile();
    }

    while (!stack.isEmpty()) {
        File f = stack.pop();
        name = toPath(root, f);
        if (f.isDirectory()) {
            File[] fs = f.listFiles();
            for (int i = 0; i < fs.length; i++) {
                if (fs[i].isDirectory()) {
                    stack.push(fs[i]);
                } else {
                    stack.add(0, fs[i]);
                }
            }
        } else {
            ze = new ZipArchiveEntry(name);
            zos.putArchiveEntry(ze);
            fis = new FileInputStream(f);
            while ((length = fis.read(buf, 0, buf.length)) >= 0) {
                zos.write(buf, 0, length);
            }
            fis.close();
            zos.closeArchiveEntry();
        }
    }
    zos.close();
}