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

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

Introduction

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

Prototype

public void finish() throws IOException 

Source Link

Usage

From source file:no.difi.sdp.client.asice.archive.CreateZip.java

public Archive zipIt(List<AsicEAttachable> files) {
    ByteArrayOutputStream archive = null;
    ZipArchiveOutputStream zipOutputStream = null;
    try {/*from  w w  w.j a v  a2  s.  com*/
        archive = new ByteArrayOutputStream();
        zipOutputStream = new ZipArchiveOutputStream(archive);
        zipOutputStream.setEncoding(Charsets.UTF_8.name());
        zipOutputStream.setMethod(ZipArchiveOutputStream.DEFLATED);
        for (AsicEAttachable file : files) {
            log.trace("Adding " + file.getFileName() + " to archive. Size in bytes before compression: "
                    + file.getBytes().length);
            ZipArchiveEntry zipEntry = new ZipArchiveEntry(file.getFileName());
            zipEntry.setSize(file.getBytes().length);

            zipOutputStream.putArchiveEntry(zipEntry);
            IOUtils.copy(new ByteArrayInputStream(file.getBytes()), zipOutputStream);
            zipOutputStream.closeArchiveEntry();
        }
        zipOutputStream.finish();
        zipOutputStream.close();

        return new Archive(archive.toByteArray());
    } catch (IOException e) {
        throw new RuntimeIOException(e);
    } finally {
        IOUtils.closeQuietly(archive);
        IOUtils.closeQuietly(zipOutputStream);
    }
}

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;//from  w  ww .  j  a v  a2 s.c  om
    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;//www. j a va  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.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  ww  w  .j  a  v a 2  s.co  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.eclipse.cbi.maven.plugins.macsigner.SignMojo.java

/**
 * Signs the file.//from w  w  w  .j a  va 2s  .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.envirocar.app.util.Util.java

/**
 * Android devices up to version 2.3.7 have a bug in the native
 * Zip archive creation, making the archive unreadable with some
 * programs./*from  w w w  .  j  av  a 2s . co  m*/
 * 
 * @param files
 *            the list of files of the target archive
 * @param target
 *            the target filename
 * @throws IOException
 */
public static void zipInteroperable(List<File> files, String target) throws IOException {
    ZipArchiveOutputStream aos = null;
    OutputStream out = null;
    try {
        File tarFile = new File(target);
        out = new FileOutputStream(tarFile);

        try {
            aos = (ZipArchiveOutputStream) new ArchiveStreamFactory()
                    .createArchiveOutputStream(ArchiveStreamFactory.ZIP, out);
        } catch (ArchiveException e) {
            throw new IOException(e);
        }

        for (File file : files) {
            ZipArchiveEntry entry = new ZipArchiveEntry(file, file.getName());
            entry.setSize(file.length());
            aos.putArchiveEntry(entry);
            IOUtils.copy(new FileInputStream(file), aos);
            aos.closeArchiveEntry();
        }

    } catch (IOException e) {
        throw e;
    } finally {
        aos.finish();
        out.close();
    }
}

From source file:org.mycore.services.zipper.MCRZipServlet.java

@Override
protected void disposeContainer(ZipArchiveOutputStream container) throws IOException {
    container.finish();
}

From source file:org.onehippo.forge.content.exim.repository.jaxrs.ContentEximExportService.java

@Path("/")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@POST// w  w  w.  j  av a  2s. c o  m
public Response exportContentToZip(@Context SecurityContext securityContext,
        @Context HttpServletRequest request,
        @Multipart(value = "batchSize", required = false) String batchSizeParam,
        @Multipart(value = "throttle", required = false) String throttleParam,
        @Multipart(value = "publishOnImport", required = false) String publishOnImportParam,
        @Multipart(value = "dataUrlSizeThreshold", required = false) String dataUrlSizeThresholdParam,
        @Multipart(value = "docbasePropNames", required = false) String docbasePropNamesParam,
        @Multipart(value = "documentTags", required = false) String documentTagsParam,
        @Multipart(value = "binaryTags", required = false) String binaryTagsParam,
        @Multipart(value = "paramsJson", required = false) String paramsJsonParam,
        @Multipart(value = "params", required = false) Attachment paramsAttachment) {

    Logger procLogger = log;

    File tempLogFile = null;
    PrintStream tempLogOut = null;
    File baseFolder = null;
    Session session = null;
    ExecutionParams params = new ExecutionParams();
    ProcessStatus processStatus = null;

    try {
        tempLogFile = File.createTempFile(TEMP_PREFIX, ".log");
        tempLogOut = new PrintStream(new BufferedOutputStream(new FileOutputStream(tempLogFile)));
        procLogger = createTeeLogger(log, tempLogOut);

        if (getProcessMonitor() != null) {
            processStatus = getProcessMonitor().startProcess();
            fillProcessStatusByRequestInfo(processStatus, securityContext, request);
            processStatus.setLogFile(tempLogFile);
        }

        baseFolder = Files.createTempDirectory(TEMP_PREFIX).toFile();
        procLogger.info("ContentEximService#exportContentToZip begins at {}.", baseFolder);

        if (paramsAttachment != null) {
            final String json = attachmentToString(paramsAttachment, "UTF-8");
            if (StringUtils.isNotBlank(json)) {
                params = getObjectMapper().readValue(json, ExecutionParams.class);
            }
        } else {
            if (StringUtils.isNotBlank(paramsJsonParam)) {
                params = getObjectMapper().readValue(paramsJsonParam, ExecutionParams.class);
            }
        }
        overrideExecutionParamsByParameters(params, batchSizeParam, throttleParam, publishOnImportParam,
                dataUrlSizeThresholdParam, docbasePropNamesParam, documentTagsParam, binaryTagsParam);

        if (processStatus != null) {
            processStatus.setExecutionParams(params);
        }

        session = createSession();
        Result result = ResultItemSetCollector.collectItemsFromExecutionParams(session, params);
        session.refresh(false);

        FileObject baseFolderObject = VFS.getManager().resolveFile(baseFolder.toURI());
        FileObject attachmentsFolderObject = baseFolderObject.resolveFile(BINARY_ATTACHMENT_REL_PATH);

        DocumentManager documentManager = new WorkflowDocumentManagerImpl(session);

        final WorkflowDocumentVariantExportTask documentExportTask = new WorkflowDocumentVariantExportTask(
                documentManager);
        documentExportTask.setLogger(log);
        documentExportTask.setBinaryValueFileFolder(attachmentsFolderObject);
        documentExportTask.setDataUrlSizeThreashold(params.getDataUrlSizeThreshold());

        final DefaultBinaryExportTask binaryExportTask = new DefaultBinaryExportTask(documentManager);
        binaryExportTask.setLogger(log);
        binaryExportTask.setBinaryValueFileFolder(attachmentsFolderObject);
        binaryExportTask.setDataUrlSizeThreashold(params.getDataUrlSizeThreshold());

        int batchCount = 0;

        Set<String> referredNodePaths = new LinkedHashSet<>();

        try {
            documentExportTask.start();
            batchCount = exportDocuments(procLogger, processStatus, params, documentExportTask, result,
                    batchCount, baseFolderObject, referredNodePaths);
        } finally {
            documentExportTask.stop();
        }

        if (!referredNodePaths.isEmpty()) {
            ResultItemSetCollector.fillResultItemsForNodePaths(session, referredNodePaths, true, null, result);
            session.refresh(false);
        }

        try {
            binaryExportTask.start();
            batchCount = exportBinaries(procLogger, processStatus, params, binaryExportTask, result, batchCount,
                    baseFolderObject);
        } finally {
            binaryExportTask.stop();
        }

        session.logout();
        session = null;

        procLogger.info("ContentEximService#exportContentToZip ends.");

        tempLogOut.close();
        tempLogOut = null;
        procLogger = log;

        final String tempLogOutString = FileUtils.readFileToString(tempLogFile, "UTF-8");
        final File zipBaseFolder = baseFolder;

        final StreamingOutput entity = new StreamingOutput() {
            @Override
            public void write(OutputStream output) throws IOException, WebApplicationException {
                ZipArchiveOutputStream zipOutput = null;
                try {
                    zipOutput = new ZipArchiveOutputStream(output);
                    ZipCompressUtils.addEntryToZip(EXIM_EXECUTION_LOG_REL_PATH, tempLogOutString, "UTF-8",
                            zipOutput);
                    ZipCompressUtils.addEntryToZip(EXIM_SUMMARY_BINARIES_LOG_REL_PATH,
                            binaryExportTask.getSummary(), "UTF-8", zipOutput);
                    ZipCompressUtils.addEntryToZip(EXIM_SUMMARY_DOCUMENTS_LOG_REL_PATH,
                            documentExportTask.getSummary(), "UTF-8", zipOutput);
                    ZipCompressUtils.addFileEntriesInFolderToZip(zipBaseFolder, "", zipOutput);
                } finally {
                    zipOutput.finish();
                    IOUtils.closeQuietly(zipOutput);
                    FileUtils.deleteDirectory(zipBaseFolder);
                }
            }
        };

        String fileName = "exim-export-" + DateFormatUtils.format(Calendar.getInstance(), "yyyyMMdd-HHmmss")
                + ".zip";
        return Response.ok().header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
                .entity(entity).build();
    } catch (Exception e) {
        procLogger.error("Failed to export content.", e);
        if (baseFolder != null) {
            try {
                FileUtils.deleteDirectory(baseFolder);
            } catch (Exception ioe) {
                procLogger.error("Failed to delete the temporary folder at {}", baseFolder.getPath(), e);
            }
        }
        final String message = new StringBuilder().append(e.getMessage()).append("\r\n").toString();
        return Response.serverError().entity(message).build();
    } finally {
        procLogger.info("ContentEximService#exportContentToZip finally ends.");

        if (getProcessMonitor() != null) {
            try {
                getProcessMonitor().stopProcess(processStatus);
            } catch (Exception e) {
                procLogger.error("Failed to stop process.", e);
            }
        }

        if (session != null) {
            try {
                session.logout();
            } catch (Exception e) {
                procLogger.error("Failed to logout JCR session.", e);
            }
        }

        if (tempLogOut != null) {
            IOUtils.closeQuietly(tempLogOut);
        }

        if (tempLogFile != null) {
            try {
                tempLogFile.delete();
            } catch (Exception e) {
                log.error("Failed to delete temporary log file.", e);
            }
        }
    }
}

From source file:org.owasp.dependencytrack.util.ZipUtil.java

/**
 * Creates a zip file at the specified path with the contents of the specified directory.
 *
 * @param directoryPath The path of the directory where the archive will be created. eg. c:/temp
 * @param zipPath The full path of the archive to create. eg. c:/temp/archive.zip
 * @throws IOException If anything goes wrong
 *//*  w w w .j  a va 2s  .c  om*/
public static void createZip(String directoryPath, String zipPath) throws IOException {
    FileOutputStream fOut = null;
    BufferedOutputStream bOut = null;
    ZipArchiveOutputStream tOut = null;

    try {
        fOut = new FileOutputStream(new File(zipPath));
        bOut = new BufferedOutputStream(fOut);
        tOut = new ZipArchiveOutputStream(bOut);
        addFileToZip(tOut, directoryPath, "");
        tOut.finish();
    } finally {
        IOUtils.closeQuietly(tOut);
        IOUtils.closeQuietly(bOut);
        IOUtils.closeQuietly(fOut);
    }
}

From source file:org.pepstock.jem.commands.CreateNode.java

private static void zipDirectory(File directoryPath, File zipPath) throws IOException {
    FileOutputStream fOut = new FileOutputStream(zipPath);
    BufferedOutputStream bOut = new BufferedOutputStream(fOut);
    ZipArchiveOutputStream tOut = new ZipArchiveOutputStream(bOut);
    zip(directoryPath, directoryPath, tOut);
    tOut.finish();
    tOut.close();/* ww w .j  av a 2  s.  c om*/
    bOut.close();
    fOut.close();
}