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

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

Introduction

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

Prototype

public ZipArchiveOutputStream(File file) throws IOException 

Source Link

Document

Creates a new ZIP OutputStream writing to a File.

Usage

From source file:org.fabrician.maven.plugins.GridlibPackageMojo.java

private void createZip(File distroSourceFile, FilenamePatternFilter filter) throws MojoExecutionException {
    distroFilename.getParentFile().mkdirs();
    ZipArchiveOutputStream out = null;/*from  w  ww.  j  a  v a2 s.c  o m*/
    try {
        out = new ZipArchiveOutputStream(distroFilename);
        if (distroSourceFile.isDirectory()) {
            CompressUtils.copyDirToArchiveOutputStream(distroSourceFile, filter, out,
                    distroAlternateRootDirectory);
        } else if (CompressUtils.isZip(distroSourceFile)) {
            CompressUtils.copyZipToArchiveOutputStream(distroSourceFile, filter, out,
                    distroAlternateRootDirectory);
        } else if (CompressUtils.isTargz(distroSourceFile)) {
            CompressUtils.copyTargzToArchiveOutputStream(distroSourceFile, filter, out,
                    distroAlternateRootDirectory);
        } else {
            throw new MojoExecutionException("Unspported source type: " + distroSource);
        }
        if (distroResources != null && !"".equals(distroResources)) {
            if (filtered) {
                CompressUtils.copyFilteredDirToArchiveOutputStream(distroResources, getFilterProperties(), out);
            } else {
                CompressUtils.copyDirToArchiveOutputStream(distroResources, out, distroAlternateRootDirectory);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new MojoExecutionException(e.getMessage());
    } finally {
        CompressUtils.close(out);
    }
}

From source file:org.fl.modules.excel.poi.exportExcel.multi.SXSSFWorkBookOperation.java

public void compressFiles2Zip() {
    org.apache.commons.io.output.ByteArrayOutputStream byteArrayOutputStream = new org.apache.commons.io.output.ByteArrayOutputStream();
    try {//from   w w w.j  a  va 2s .c om
        byteArrayOutputStream = write(byteArrayOutputStream);
        ZipArchiveOutputStream zaos = null;
        zaos = new ZipArchiveOutputStream(byteArrayOutputStream);
        // Use Zip64 extensions for all entries where they are required
        zaos.setUseZip64(Zip64Mode.AsNeeded);
        if (byteArrayOutputStream != null) {
            ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry("excel");
            zaos.putArchiveEntry(zipArchiveEntry);
            try {
                byteArrayOutputStream.writeTo(zaos);
                zaos.closeArchiveEntry();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.itstechupnorth.walrus.zip.ArchiveSaver.java

public synchronized void open() throws IOException {
    if (!open) {//from  w w w. j  a v a 2s.  c  o  m
        open = true;
        out = new ZipArchiveOutputStream(archive);
        out.setLevel(level);
        out.setFallbackToUTF8(true);
    }
}

From source file:org.jboss.tools.windup.ui.internal.archiver.ZipFileExporter.java

/**
 * @see org.jboss.tools.windup.ui.internal.archiver.AbstractArchiveFileExporter#createOutputStream(java.lang.String, boolean)
 *///from  www  .  j a  v a  2s . c om
@Override
protected ArchiveOutputStream createOutputStream(String archiveName, boolean compress) throws IOException {

    ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(new FileOutputStream(archiveName));
    zipOut.setMethod(compress ? ZipEntry.DEFLATED : ZipEntry.STORED);
    return zipOut;
}

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

@Override
protected ZipArchiveOutputStream createContainer(ServletOutputStream sout, String comment) {
    ZipArchiveOutputStream zout = new ZipArchiveOutputStream(new BufferedOutputStream(sout));
    zout.setComment(comment);/*from ww  w. j a  va2s. c o  m*/
    zout.setLevel(Deflater.BEST_COMPRESSION);
    return zout;
}

From source file:org.ngrinder.common.util.CompressionUtil.java

/**
 * Zip the given src into the given output stream.
 * /*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();
}

From source file:org.ngrinder.common.util.CompressionUtils.java

/**
 * Zip the given src into the given output stream.
 *
 * @param src         src to be zipped/*from   www . ja  va 2s  . co m*/
 * @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 = null;

    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 = checkNotNull(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 = checkNotNull(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);
            try {
                fis = new FileInputStream(f);
                while ((length = fis.read(buf, 0, buf.length)) >= 0) {
                    zos.write(buf, 0, length);
                }
            } finally {
                IOUtils.closeQuietly(fis);
            }
            zos.closeArchiveEntry();
        }
    }
    zos.close();
}

From source file:org.ngrinder.script.util.CompressionUtil.java

public void zip(File src, OutputStream os, String charsetName, boolean includeSrc) throws IOException {
    ZipArchiveOutputStream zos = new ZipArchiveOutputStream(os);
    zos.setEncoding(charsetName);//from w w  w  . j  ava2 s.  c o  m
    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();
}

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

@Path("/")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@POST/*from  w  w  w  . j ava 2s .co  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.openengsb.connector.git.internal.GitServiceImpl.java

@Override
public File export() {
    try {//from w  w  w. ja  v  a  2s. c om
        if (repository == null) {
            initRepository();
        }

        LOGGER.debug("Exporting repository to archive");
        File tmp = File.createTempFile("repository", ".zip");
        ZipArchiveOutputStream zos = new ZipArchiveOutputStream(tmp);
        packRepository(localWorkspace, zos);
        zos.close();
        return tmp;
    } catch (IOException e) {
        throw new ScmException(e);
    }
}