Example usage for java.util.zip ZipOutputStream ZipOutputStream

List of usage examples for java.util.zip ZipOutputStream ZipOutputStream

Introduction

In this page you can find the example usage for java.util.zip ZipOutputStream ZipOutputStream.

Prototype

public ZipOutputStream(OutputStream out) 

Source Link

Document

Creates a new ZIP output stream.

Usage

From source file:de.fu_berlin.inf.dpp.core.zip.FileZipper.java

private static void internalZipFiles(List<FileWrapper> files, File archive, boolean compress,
        boolean includeDirectories, long totalSize, ZipListener listener)
        throws IOException, OperationCanceledException {

    byte[] buffer = new byte[BUFFER_SIZE];

    OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(archive), BUFFER_SIZE);

    ZipOutputStream zipStream = new ZipOutputStream(outputStream);

    zipStream.setLevel(compress ? Deflater.DEFAULT_COMPRESSION : Deflater.NO_COMPRESSION);

    boolean cleanup = true;
    boolean isCanceled = false;

    StopWatch stopWatch = new StopWatch();
    stopWatch.start();/*w ww.  j a v a  2s  .  c  o  m*/

    long totalRead = 0L;

    try {
        for (FileWrapper file : files) {
            String entryName = includeDirectories ? file.getPath() : file.getName();

            if (listener != null) {
                isCanceled = listener.update(file.getPath());
            }

            log.trace("compressing file: " + entryName);

            zipStream.putNextEntry(new ZipEntry(entryName));

            InputStream in = null;

            try {
                int read = 0;
                in = file.getInputStream();
                while (-1 != (read = in.read(buffer))) {

                    if (isCanceled) {
                        throw new OperationCanceledException(
                                "compressing of file '" + entryName + "' was canceled");
                    }

                    zipStream.write(buffer, 0, read);

                    totalRead += read;

                    if (listener != null) {
                        listener.update(totalRead, totalSize);
                    }

                }
            } finally {
                IOUtils.closeQuietly(in);
            }
            zipStream.closeEntry();
        }
        cleanup = false;
    } finally {
        IOUtils.closeQuietly(zipStream);
        if (cleanup && archive != null && archive.exists() && !archive.delete()) {
            log.warn("could not delete archive file: " + archive);
        }
    }

    stopWatch.stop();

    log.debug(String.format("created archive %s I/O: [%s]", archive.getAbsolutePath(),
            CoreUtils.throughput(archive.length(), stopWatch.getTime())));

}

From source file:eu.esdihumboldt.hale.common.core.io.project.impl.ArchiveProjectWriter.java

/**
 * Creates the project archive.//from w w  w  .  ja  va2 s  .  c  om
 * 
 * @param target {@link OutputStream} to write the archive to
 * @param reporter the reporter to use for the execution report
 * @param progress the progress indicator
 * @return the execution report
 * @throws IOException if an I/O operation fails
 * @throws IOProviderConfigurationException if the I/O provider was not
 *             configured properly
 */
public IOReport createProjectArchive(OutputStream target, IOReporter reporter, ProgressIndicator progress)
        throws IOException, IOProviderConfigurationException {

    ZipOutputStream zip = new ZipOutputStream(target);

    // all files related to the project are copied into a temporary
    // directory first and then packed into a zip file

    // create temporary directory and project file
    File tempDir = Files.createTempDir();
    File baseFile = new File(tempDir, "project.halex");

    // mark the temporary directory for clean-up if the project is closed
    CleanupService clean = HalePlatform.getService(CleanupService.class);
    if (clean != null) {
        clean.addTemporaryFiles(CleanupContext.PROJECT, tempDir);
    }

    LocatableOutputSupplier<OutputStream> out = new FileIOSupplier(baseFile);

    // false is correct if getParameter is null because false is default
    boolean includeWebresources = getParameter(INCLUDE_WEB_RESOURCES).as(Boolean.class, false);
    SubtaskProgressIndicator subtask = new SubtaskProgressIndicator(progress);

    // save old IO configurations
    List<IOConfiguration> oldResources = new ArrayList<IOConfiguration>();
    for (int i = 0; i < getProject().getResources().size(); i++) {
        // clone all IO configurations to work on different objects
        oldResources.add(getProject().getResources().get(i).clone());
    }
    IOConfiguration config = getProject().getSaveConfiguration();
    if (config == null) {
        config = new IOConfiguration();
    }
    IOConfiguration oldSaveConfig = config.clone();

    // copy resources to the temp directory and update xml schemas
    updateResources(tempDir, includeWebresources, subtask, reporter);

    // update target save configuration of the project
    config.getProviderConfiguration().put(PARAM_TARGET, Value.of(baseFile.toURI().toString()));

    // write project file via XMLProjectWriter
    XMLProjectWriter writer = new XMLProjectWriter();
    writer.setTarget(out);
    writer.setProject(getProject());
    writer.setProjectFiles(getProjectFiles());
    IOReport report = writer.execute(progress, reporter);

    // now after the project with its project files is written, look for the
    // alignment file and update it
    ProjectFileInfo newAlignmentInfo = getAlignmentFile(getProject());
    if (newAlignmentInfo != null) {
        URI newAlignment = tempDir.toURI().resolve(newAlignmentInfo.getLocation());
        XMLAlignmentUpdater.update(new File(newAlignment), newAlignment, includeWebresources, reporter);
    }

    // put the complete temp directory into a zip file
    IOUtils.zipDirectory(tempDir, zip);
    zip.close();

    // the files may not be deleted now as they will be needed if the
    // project is saved again w/o loading it first

    // update the relative resource locations
    LocationUpdater updater = new LocationUpdater(getProject(), out.getLocation());
    // resources are made absolute (else they can't be found afterwards),
    // e.g. when saving the project again before loading it
    updater.updateProject(false);

    // reset the save configurations that has been overridden by the XML
    // project writer
    getProject().setSaveConfiguration(oldSaveConfig);

    if (clean == null) {
        // if no clean service is available, assume the directory is not
        // needed anymore
        FileUtils.deleteDirectory(tempDir);
    }

    return report;
}

From source file:edu.harvard.med.screensaver.service.cherrypicks.CherryPickRequestPlateMapFilesBuilder.java

@SuppressWarnings("unchecked")
private InputStream doBuildZip(CherryPickRequest cherryPickRequest, Set<CherryPickAssayPlate> forPlates)
        throws IOException {
    ByteArrayOutputStream zipOutRaw = new ByteArrayOutputStream();
    ZipOutputStream zipOut = new ZipOutputStream(zipOutRaw);
    MultiMap/*<String,SortedSet<CherryPick>>*/ files2CherryPicks = buildCherryPickFiles(cherryPickRequest,
            forPlates);// w  ww  . j av a2 s . c  om
    buildReadme(cherryPickRequest, zipOut);
    buildDistinctPlateCopyFile(cherryPickRequest, forPlates, zipOut);
    PrintWriter out = new CSVPrintWriter(new OutputStreamWriter(zipOut), NEWLINE);
    for (Iterator iter = files2CherryPicks.keySet().iterator(); iter.hasNext();) {
        String fileName = (String) iter.next();
        ZipEntry zipEntry = new ZipEntry(fileName);
        zipOut.putNextEntry(zipEntry);
        writeHeadersRow(out);
        for (LabCherryPick cherryPick : (SortedSet<LabCherryPick>) files2CherryPicks.get(fileName)) {
            writeCherryPickRow(out, cherryPick);
        }
        out.flush();
    }
    out.close();
    return new ByteArrayInputStream(zipOutRaw.toByteArray());
}

From source file:gov.nih.nci.caarray.services.external.v1_0.data.AbstractDataApiUtils.java

/**
 * {@inheritDoc}//from w w w  . j  a  v a2s  . co m
 */
public void copyMageTabZipToOutputStream(CaArrayEntityReference experimentRef, OutputStream ostream)
        throws InvalidReferenceException, DataTransferException, IOException {
    MageTabFileSet mtset = exportMageTab(experimentRef);
    ZipOutputStream zos = new ZipOutputStream(ostream);
    zos.putNextEntry(new ZipEntry(mtset.getIdf().getMetadata().getName()));
    IOUtils.write(mtset.getIdf().getContents(), zos);
    zos.putNextEntry(new ZipEntry(mtset.getSdrf().getMetadata().getName()));
    IOUtils.write(mtset.getSdrf().getContents(), zos);
    for (gov.nih.nci.caarray.external.v1_0.data.File dataFile : mtset.getDataFiles()) {
        zos.putNextEntry(new ZipEntry(dataFile.getMetadata().getName()));
        copyFileContentsToOutputStream(dataFile.getReference(), false, zos);
    }
    zos.finish();
}

From source file:es.gob.afirma.signers.ooxml.be.fedict.eid.applet.service.signer.ooxml.AbstractOOXMLSignatureService.java

private ZipOutputStream copyOOXMLContent(final String signatureZipEntryName,
        final OutputStream signedOOXMLOutputStream)
        throws IOException, ParserConfigurationException, SAXException, TransformerException {
    final ZipOutputStream zipOutputStream = new ZipOutputStream(signedOOXMLOutputStream);
    final ZipInputStream zipInputStream = new ZipInputStream(
            new ByteArrayInputStream(this.getOfficeOpenXMLDocument()));
    ZipEntry zipEntry;//www.  j  av  a  2  s .com
    boolean hasOriginSigsRels = false;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        zipOutputStream.putNextEntry(new ZipEntry(zipEntry.getName()));
        if ("[Content_Types].xml".equals(zipEntry.getName())) { //$NON-NLS-1$
            final Document contentTypesDocument = loadDocumentNoClose(zipInputStream);
            final Element typesElement = contentTypesDocument.getDocumentElement();

            // We need to add an Override element.
            final Element overrideElement = contentTypesDocument.createElementNS(
                    "http://schemas.openxmlformats.org/package/2006/content-types", "Override"); //$NON-NLS-1$ //$NON-NLS-2$
            overrideElement.setAttribute("PartName", "/" + signatureZipEntryName); //$NON-NLS-1$ //$NON-NLS-2$
            overrideElement.setAttribute("ContentType", //$NON-NLS-1$
                    "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml"); //$NON-NLS-1$
            typesElement.appendChild(overrideElement);

            final Element nsElement = contentTypesDocument.createElement("ns"); //$NON-NLS-1$
            nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", //$NON-NLS-1$
                    "http://schemas.openxmlformats.org/package/2006/content-types"); //$NON-NLS-1$
            final NodeList nodeList = XPathAPI.selectNodeList(contentTypesDocument,
                    "/tns:Types/tns:Default[@Extension='sigs']", nsElement); //$NON-NLS-1$
            if (0 == nodeList.getLength()) {
                // Add Default element for 'sigs' extension.
                final Element defaultElement = contentTypesDocument.createElementNS(
                        "http://schemas.openxmlformats.org/package/2006/content-types", "Default"); //$NON-NLS-1$ //$NON-NLS-2$
                defaultElement.setAttribute("Extension", "sigs"); //$NON-NLS-1$ //$NON-NLS-2$
                defaultElement.setAttribute("ContentType", //$NON-NLS-1$
                        "application/vnd.openxmlformats-package.digital-signature-origin"); //$NON-NLS-1$
                typesElement.appendChild(defaultElement);
            }

            writeDocumentNoClosing(contentTypesDocument, zipOutputStream, false);
        } else if ("_rels/.rels".equals(zipEntry.getName())) { //$NON-NLS-1$
            final Document relsDocument = loadDocumentNoClose(zipInputStream);

            final Element nsElement = relsDocument.createElement("ns"); //$NON-NLS-1$
            nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", RELATIONSHIPS_SCHEMA); //$NON-NLS-1$
            final NodeList nodeList = XPathAPI.selectNodeList(relsDocument,
                    "/tns:Relationships/tns:Relationship[@Type='http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/origin']", //$NON-NLS-1$
                    nsElement);
            if (0 == nodeList.getLength()) {
                final Element relationshipElement = relsDocument.createElementNS(RELATIONSHIPS_SCHEMA,
                        "Relationship"); //$NON-NLS-1$
                relationshipElement.setAttribute("Id", "rel-id-" + UUID.randomUUID().toString()); //$NON-NLS-1$ //$NON-NLS-2$
                relationshipElement.setAttribute("Type", //$NON-NLS-1$
                        "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/origin"); //$NON-NLS-1$
                relationshipElement.setAttribute("Target", "_xmlsignatures/origin.sigs"); //$NON-NLS-1$ //$NON-NLS-2$

                relsDocument.getDocumentElement().appendChild(relationshipElement);
            }

            writeDocumentNoClosing(relsDocument, zipOutputStream, false);
        } else if (zipEntry.getName().startsWith("_xmlsignatures/_rels/") //$NON-NLS-1$
                && zipEntry.getName().endsWith(".rels")) { //$NON-NLS-1$

            hasOriginSigsRels = true;
            final Document originSignRelsDocument = loadDocumentNoClose(zipInputStream);

            final Element relationshipElement = originSignRelsDocument.createElementNS(RELATIONSHIPS_SCHEMA,
                    "Relationship"); //$NON-NLS-1$
            relationshipElement.setAttribute("Id", "rel-" + UUID.randomUUID().toString()); //$NON-NLS-1$ //$NON-NLS-2$
            relationshipElement.setAttribute("Type", //$NON-NLS-1$
                    "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/signature"); //$NON-NLS-1$

            relationshipElement.setAttribute("Target", FilenameUtils.getName(signatureZipEntryName)); //$NON-NLS-1$
            originSignRelsDocument.getDocumentElement().appendChild(relationshipElement);

            writeDocumentNoClosing(originSignRelsDocument, zipOutputStream, false);
        } else {
            IOUtils.copy(zipInputStream, zipOutputStream);
        }
    }

    if (!hasOriginSigsRels) {
        // Add signature relationships document.
        addOriginSigsRels(signatureZipEntryName, zipOutputStream);
        addOriginSigs(zipOutputStream);
    }

    // Return.
    zipInputStream.close();
    return zipOutputStream;
}

From source file:fr.gael.dhus.service.job.SendLogsJob.java

@Override
protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
    if (!configurationManager.getSendLogsCronConfiguration().isActive())
        return;// ww w .j  a v  a2  s  .  c om
    long start = System.currentTimeMillis();
    logger.info("SCHEDULER : Send Administrative logs.");
    if (!DHuS.isStarted()) {
        logger.warn("SCHEDULER : Not run while system not fully initialized.");
        return;
    }

    String[] addresses = configurationManager.getSendLogsCronConfiguration().getAddresses().split(",");
    // Case of no addresses available: use system support
    if ((addresses == null) || (addresses.length == 0) || "".equals(addresses[0].trim())) {
        String email = configurationManager.getSupportConfiguration().getMail();
        if ((email == null) || "".equals(email)) {
            throw new MailException("Support e-mail not configured, " + "system logs will not be send");
        }
        addresses = new String[] { email };
    }

    RollingFileAppender rollingFileAppender = (RollingFileAppender) ((org.apache.logging.log4j.core.Logger) LogManager
            .getRootLogger()).getAppenders().get("RollingFile");
    if (rollingFileAppender == null) {
        throw new MailException("No rolling log file defined");
    }

    String logPath = rollingFileAppender.getFileName();

    if ((logPath == null) || logPath.trim().equals("")) {
        throw new MailException("Log file not defined");
    }

    File logs = new File(logPath);
    if (!logs.exists()) {
        throw new MailException("Log file not present : " + logs.getPath());
    }

    Date now = new Date();
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'@'HH:mm:ss");
    df.setTimeZone(TimeZone.getTimeZone("GMT"));
    String docFilename = configurationManager.getNameConfiguration().getShortName().toLowerCase() + "-"
            + df.format(now);

    File zipLogs;
    try {
        zipLogs = File.createTempFile(docFilename, ".zip");
    } catch (IOException e) {
        throw new MailException("Cannot create temporary zip log file.", e);
    }

    // compress logs file to zip format
    FileOutputStream fos;
    ZipOutputStream zos = null;
    FileInputStream fis = null;
    try {
        int length;
        byte[] buffer = new byte[1024];
        ZipEntry entry = new ZipEntry(docFilename + ".txt");

        fos = new FileOutputStream(zipLogs);
        zos = new ZipOutputStream(fos);
        fis = new FileInputStream(logs);

        zos.setLevel(Deflater.BEST_COMPRESSION);
        zos.putNextEntry(entry);
        while ((length = fis.read(buffer)) > 0) {
            zos.write(buffer, 0, length);
        }
    } catch (IOException e) {
        throw new MailException("An error occurred during compression " + "logs file, cannot send logs !", e);
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            if (zos != null) {
                zos.closeEntry();
                zos.close();
            }
        } catch (IOException e) {
            throw new MailException("An error occurred during compression " + "logs file, cannot send logs !",
                    e);
        }
    }

    EmailAttachment attachment = new EmailAttachment();
    attachment.setDescription(
            configurationManager.getNameConfiguration().getShortName() + " Logs " + now.toString());
    attachment.setPath(zipLogs.getPath());
    attachment.setName(zipLogs.getName());

    // Prepare the addresses
    List<String> ads = new ArrayList<String>();
    for (String email : addresses) {
        StringTokenizer tk = new StringTokenizer(email, ", ");
        while (tk.hasMoreTokens()) {
            String token = tk.nextToken().trim();
            if (!token.isEmpty())
                ads.add(token);
        }
    }
    for (String email : ads) {
        try {
            String server = configurationManager.getServerConfiguration().getExternalHostname();
            String url = configurationManager.getServerConfiguration().getExternalUrl();

            mailServer.send(email, null, null,
                    "[" + configurationManager.getNameConfiguration().getShortName().toLowerCase() + "@"
                            + server + "] logs of " + df.format(now),
                    "Here is attached " + configurationManager.getNameConfiguration().getShortName()
                            + " logs of \"" + url + "\" host.\n\n" + "Kind Regards.\nThe "
                            + configurationManager.getNameConfiguration().getShortName() + " Team.",
                    attachment);
            logger.info("Logs Sent to " + email);
        } catch (EmailException e) {
            throw new MailException("Cannot send logs to " + email, e);
        }
    }

    if (!zipLogs.delete()) {
        logger.warn("Cannot remove mail attachment: " + zipLogs.getAbsolutePath());
    }

    logger.info("SCHEDULER : Send Administrative logs done - " + (System.currentTimeMillis() - start) + "ms");
}

From source file:io.sledge.core.impl.installer.SledgePackageConfigurer.java

private void createNewZipfileWithReplacedPlaceholders(InputStream packageStream, Path configurationPackagePath,
        Properties envProps) throws IOException {

    // For reading the original configuration package
    ZipInputStream configPackageZipStream = new ZipInputStream(new BufferedInputStream(packageStream),
            Charset.forName("UTF-8"));

    // For outputting the configured (placeholders replaced) version of the package as zip file
    File outZipFile = configurationPackagePath.toFile();
    ZipOutputStream outConfiguredZipStream = new ZipOutputStream(new FileOutputStream(outZipFile));

    ZipEntry zipEntry;/*from   w w  w  .  j a  v a2 s .c  o  m*/
    while ((zipEntry = configPackageZipStream.getNextEntry()) != null) {

        if (zipEntry.isDirectory()) {
            configPackageZipStream.closeEntry();
            continue;
        } else {
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            int length;
            byte[] buffer = new byte[2048];
            while ((length = configPackageZipStream.read(buffer, 0, buffer.length)) >= 0) {
                output.write(buffer, 0, length);
            }

            InputStream zipEntryInputStream = new BufferedInputStream(
                    new ByteArrayInputStream(output.toByteArray()));

            if (zipEntry.getName().endsWith("instance.properties")) {
                ByteArrayOutputStream envPropsOut = new ByteArrayOutputStream();
                envProps.store(envPropsOut, "Environment configurations");
                zipEntryInputStream = new BufferedInputStream(
                        new ByteArrayInputStream(envPropsOut.toByteArray()));

            } else if (isTextFile(zipEntry.getName(), zipEntryInputStream)) {
                String configuredContent = StrSubstitutor.replace(output, envProps);
                zipEntryInputStream = new BufferedInputStream(
                        new ByteArrayInputStream(configuredContent.getBytes()));
            }

            // Add to output zip file
            addToZipFile(zipEntry.getName(), zipEntryInputStream, outConfiguredZipStream);

            zipEntryInputStream.close();
            configPackageZipStream.closeEntry();
        }
    }

    outConfiguredZipStream.close();
    configPackageZipStream.close();
}

From source file:com.mgmtp.jfunk.common.util.ExtendedFile.java

/**
 * Zips all included objects into the specified file.
 * /* w ww . j  a  v a2  s  .com*/
 * @param zipFile
 *            the zip file to be created
 */
public void zip(final File zipFile) throws IOException {
    File[] files = listFiles();
    if (files.length == 0) {
        return;
    }
    LOG.info("Creating zip file " + zipFile + " from directory " + this);
    ZipOutputStream zipOut = null;
    try {
        zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
        for (File file : files) {
            zip("", file, zipOut);
        }
    } finally {
        IOUtils.closeQuietly(zipOut);
    }
}

From source file:be.fedict.eid.dss.portal.control.bean.UploadBean.java

@Override
public void listener(UploadEvent event) throws Exception {
    this.log.debug("listener");
    UploadItem item = event.getUploadItem();
    this.log.debug("filename: #0", item.getFileName());
    this.filename = item.getFileName();
    this.log.debug("content type: #0", item.getContentType());
    String extension = FilenameUtils.getExtension(this.filename).toLowerCase();
    this.contentType = supportedFileExtensions.get(extension);
    if (null == this.contentType) {
        /*/*  w w  w.  j  a va 2s  .c  om*/
         * Unsupported content-type is converted to a ZIP container.
         */
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
        ZipEntry zipEntry = new ZipEntry(this.filename);
        zipOutputStream.putNextEntry(zipEntry);
        IOUtils.write(item.getData(), zipOutputStream);
        zipOutputStream.close();
        this.filename = FilenameUtils.getBaseName(this.filename) + ".zip";
        this.document = outputStream.toByteArray();
        this.contentType = "application/zip";
        return;
    }
    this.log.debug("file size: #0", item.getFileSize());
    this.log.debug("data bytes available: #0", (null != item.getData()));
    if (null != item.getData()) {
        this.document = item.getData();
        return;
    }
    File file = item.getFile();
    if (null != file) {
        this.log.debug("tmp file: #0", file.getAbsolutePath());
        this.document = FileUtils.readFileToByteArray(file);
    }
}

From source file:ZipUtilTest.java

public void testUnpackEntryFromStream() throws IOException {
    final String name = "foo";
    final byte[] contents = "bar".getBytes();

    File file = File.createTempFile("temp", null);
    try {/*  ww  w .  j  av a2 s  . c  om*/
        // Create the ZIP file
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file));
        try {
            zos.putNextEntry(new ZipEntry(name));
            zos.write(contents);
            zos.closeEntry();
        } finally {
            IOUtils.closeQuietly(zos);
        }

        FileInputStream fis = new FileInputStream(file);
        // Test the ZipUtil
        byte[] actual = ZipUtil.unpackEntry(fis, name);
        assertNotNull(actual);
        assertEquals(new String(contents), new String(actual));
    } finally {
        FileUtils.deleteQuietly(file);
    }
}