Example usage for java.util.zip ZipOutputStream putNextEntry

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

Introduction

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

Prototype

public void putNextEntry(ZipEntry e) throws IOException 

Source Link

Document

Begins writing a new ZIP file entry and positions the stream to the start of the entry data.

Usage

From source file:com.dangdang.config.service.web.mb.PropertyExportManagedBean.java

/**
 * ??ZIP// w ww .j a v  a 2 s.com
 * 
 * @return
 */
public StreamedContent generateFileAll() {
    LOGGER.info("Export all config group");
    StreamedContent file = null;

    String authedNode = ZKPaths.makePath(nodeAuth.getAuthedNode(), versionMB.getSelectedVersion());
    List<String> children = nodeService.listChildren(authedNode);
    if (children != null && !children.isEmpty()) {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ZipOutputStream zipOutputStream = new ZipOutputStream(out);
            for (String groupName : children) {
                String groupPath = ZKPaths.makePath(authedNode, groupName);
                String fileName = ZKPaths.getNodeFromPath(groupPath) + ".properties";

                List<PropertyItemVO> items = nodeBusiness.findPropertyItems(nodeAuth.getAuthedNode(),
                        versionMB.getSelectedVersion(), groupName);
                List<String> lines = formatPropertyLines(groupName, items);
                if (!lines.isEmpty()) {
                    ZipEntry zipEntry = new ZipEntry(fileName);
                    zipOutputStream.putNextEntry(zipEntry);
                    IOUtils.writeLines(lines, "\r\n", zipOutputStream, Charsets.UTF_8.displayName());
                    zipOutputStream.closeEntry();
                }
            }

            zipOutputStream.close();
            byte[] data = out.toByteArray();
            InputStream in = new ByteArrayInputStream(data);

            String fileName = authedNode.replace('/', '-') + ".zip";
            file = new DefaultStreamedContent(in, "application/zip", fileName, Charsets.UTF_8.name());
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    return file;
}

From source file:com.microsoft.tfs.client.common.ui.teambuild.commands.CreateUploadZipCommand.java

/**
 * Copy zip file and remove ignored files
 *
 * @param srcFile//from ww  w . j  av  a 2s.  c  om
 * @param destFile
 * @throws IOException
 */
public void copyZip(final String srcFile, final String destFile) throws Exception {
    loadDefaultExcludePattern(getRootFolderInZip(srcFile));

    final ZipFile zipSrc = new ZipFile(srcFile);
    final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(destFile));

    try {
        final Enumeration<? extends ZipEntry> entries = zipSrc.entries();
        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();
            if (!isExcluded(LocalPath.combine(srcFile, entry.getName()), false, srcFile)) {
                final ZipEntry newEntry = new ZipEntry(entry.getName());
                out.putNextEntry(newEntry);

                final BufferedInputStream in = new BufferedInputStream(zipSrc.getInputStream(entry));
                int len;
                final byte[] buf = new byte[65536];
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();
            }
        }
        out.finish();
    } catch (final IOException e) {
        errorMsg = Messages.getString("CreateUploadZipCommand.CopyArchiveErrorMessageFormat"); //$NON-NLS-1$
        log.error("Exceptions when copying exising archive ", e); //$NON-NLS-1$
        throw e;
    } finally {
        out.close();
        zipSrc.close();
    }
}

From source file:eu.europa.esig.dss.asic.signature.ASiCService.java

private void createZipEntry(final ZipOutputStream outZip, final ZipEntry entrySignature) throws DSSException {
    try {//from ww w  .jav a2  s  .c  o m
        outZip.putNextEntry(entrySignature);
    } catch (IOException e) {
        throw new DSSException(e);
    }
}

From source file:be.fedict.eid.applet.service.signer.ooxml.AbstractOOXMLSignatureService.java

private ZipOutputStream copyOOXMLContent(String signatureZipEntryName, OutputStream signedOOXMLOutputStream)
        throws IOException, ParserConfigurationException, SAXException, TransformerConfigurationException,
        TransformerFactoryConfigurationError, TransformerException {
    ZipOutputStream zipOutputStream = new ZipOutputStream(signedOOXMLOutputStream);
    ZipInputStream zipInputStream = new ZipInputStream(this.getOfficeOpenXMLDocumentURL().openStream());
    ZipEntry zipEntry;//from www. ja va2  s .co m
    boolean hasOriginSigsRels = false;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        LOG.debug("copy ZIP entry: " + zipEntry.getName());
        ZipEntry newZipEntry = new ZipEntry(zipEntry.getName());
        zipOutputStream.putNextEntry(newZipEntry);
        if ("[Content_Types].xml".equals(zipEntry.getName())) {
            Document contentTypesDocument = loadDocumentNoClose(zipInputStream);
            Element typesElement = contentTypesDocument.getDocumentElement();

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

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

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

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

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

            writeDocumentNoClosing(relsDocument, zipOutputStream, false);
        } else if ("_xmlsignatures/_rels/origin.sigs.rels".equals(zipEntry.getName())) {
            hasOriginSigsRels = true;
            Document originSignRelsDocument = loadDocumentNoClose(zipInputStream);

            Element relationshipElement = originSignRelsDocument.createElementNS(
                    "http://schemas.openxmlformats.org/package/2006/relationships", "Relationship");
            String relationshipId = "rel-" + UUID.randomUUID().toString();
            relationshipElement.setAttribute("Id", relationshipId);
            relationshipElement.setAttribute("Type",
                    "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/signature");
            String target = FilenameUtils.getName(signatureZipEntryName);
            LOG.debug("target: " + target);
            relationshipElement.setAttribute("Target", target);
            originSignRelsDocument.getDocumentElement().appendChild(relationshipElement);

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

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

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

From source file:com.joliciel.csvLearner.CSVEventListWriter.java

public void writeFile(GenericEvents events) {
    try {//from w  ww .  ja  v a2s . co  m
        LOG.debug("writeFile: " + file.getName());
        file.delete();
        file.createNewFile();
        if (file.getName().endsWith(".zip"))
            isZip = true;
        Writer writer = null;
        ZipOutputStream zos = null;
        try {
            if (isZip) {
                zos = new ZipOutputStream(new FileOutputStream(file, false));
                writer = new BufferedWriter(new OutputStreamWriter(zos));
            } else {
                writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), "UTF8"));
            }
            Set<String> features = new TreeSet<String>();
            if (!filePerEvent) {
                if (isZip) {
                    zos.putNextEntry(new ZipEntry(
                            file.getName().substring(0, file.getName().lastIndexOf('.')) + ".csv"));
                }

                for (GenericEvent event : events) {
                    if (LOG.isTraceEnabled())
                        LOG.trace("Writing event: " + event.getIdentifier());
                    for (String feature : event.getFeatures()) {
                        int classIndex = feature.indexOf(CSVLearner.NOMINAL_MARKER);
                        if (classIndex < 0 || denominalise)
                            features.add(feature);
                        else
                            features.add(feature.substring(0, classIndex));
                    }
                }

                writer.append("ID,");

                if (includeOutcomes)
                    writer.append("outcome,");
                for (String feature : features) {
                    writer.append(CSVFormatter.format(feature) + ",");
                }

                writer.append("\n");
                writer.flush();
            }

            for (GenericEvent event : events) {
                if (filePerEvent) {
                    features = new TreeSet<String>();
                    for (String feature : event.getFeatures()) {
                        int classIndex = feature.indexOf(CSVLearner.NOMINAL_MARKER);
                        if (classIndex < 0 || denominalise)
                            features.add(feature);
                        else
                            features.add(feature.substring(0, classIndex));
                    }

                    if (isZip)
                        zos.putNextEntry(new ZipEntry(event.getIdentifier() + ".csv"));
                    writer.append("ID,");
                    if (includeOutcomes)
                        writer.append("outcome,");

                    for (String feature : features) {
                        writer.append(CSVFormatter.format(feature) + ",");
                    }

                    writer.append("\n");
                    writer.flush();
                }
                writer.append(CSVFormatter.format(identifierPrefix + event.getIdentifier()) + ",");
                if (includeOutcomes)
                    writer.append(CSVFormatter.format(event.getOutcome()) + ",");

                for (String feature : features) {
                    Integer featureIndexObj = event.getFeatureIndex(feature);
                    int featureIndex = featureIndexObj == null ? -1 : featureIndexObj.intValue();

                    if (featureIndex < 0) {
                        writer.append(missingValueString + ",");
                    } else {
                        String eventFeature = event.getFeatures().get(featureIndex);
                        if (!eventFeature.equals(feature)) {
                            int classIndex = eventFeature.indexOf(CSVLearner.NOMINAL_MARKER);
                            String clazz = eventFeature
                                    .substring(classIndex + CSVLearner.NOMINAL_MARKER.length());
                            writer.append(CSVFormatter.format(clazz) + ",");
                        } else {
                            double value = event.getWeights().get(featureIndex);
                            writer.append(CSVFormatter.format(value) + ",");
                        }
                    }
                }
                writer.append("\n");
                writer.flush();
                if (filePerEvent && isZip)
                    zos.closeEntry();
            }
            if (!filePerEvent && isZip)
                zos.closeEntry();
        } finally {
            if (zos != null) {
                zos.flush();
                zos.close();
            }
            if (writer != null) {
                writer.flush();
                writer.close();
            }
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}

From source file:gov.nih.nci.cacis.nav.AbstractSendMail.java

/**
 * Creates MimeMessage with supplied values
 * /*from   www. ja  v a 2s .co  m*/
 * @param to - to email address
 * @param docType - String value for the attached document type
 * @param subject - Subject for the email
 * @param instructions - email body
 * @param content - content to be sent as attachment
 * @return MimeMessage instance
 */
public MimeMessage createMessage(String to, String docType, String subject, String instructions, String content,
        String metadataXMl, String title, String indexBodyToken, String readmeToken) {
    final MimeMessage msg = mailSender.createMimeMessage();
    UUID uniqueID = UUID.randomUUID();
    tempZipFolder = new File(secEmailTempZipLocation + "/" + uniqueID);
    try {
        msg.setFrom(new InternetAddress(getFrom()));
        msg.setSubject(subject);
        msg.setSentDate(new Date());
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));

        // The readable part
        final MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(instructions);
        mbp1.setHeader("Content-Type", "text/plain");

        // The notification
        final MimeBodyPart mbp2 = new MimeBodyPart();

        final String contentType = "application/xml; charset=UTF-8";

        String extension;

        // HL7 messages should be a txt file, otherwise xml
        if (StringUtils.contains(instructions, "HL7_V2_CLINICAL_NOTE")) {
            extension = TXT_EXT;
        } else {
            extension = XML_EXT;
        }

        final String fileName = docType + UUID.randomUUID() + extension;

        //            final DataSource ds = new AttachmentDS(fileName, content, contentType);
        //            mbp2.setDataHandler(new DataHandler(ds));

        /******** START NHIN COMPLIANCE CHANGES *****/

        boolean isTempZipFolderCreated = tempZipFolder.mkdirs();
        if (!isTempZipFolderCreated) {
            LOG.error("Error creating temp folder for NHIN zip file: " + tempZipFolder.getAbsolutePath());
            throw new ApplicationRuntimeException(
                    "Error creating temp folder for NHIN zip file: " + tempZipFolder.getAbsolutePath());
        }

        String indexFileString = FileUtils.readFileToString(new File(secEmailTempZipLocation + "/INDEX.HTM"));
        String readmeFileString = FileUtils.readFileToString(new File(secEmailTempZipLocation + "/README.TXT"));

        indexFileString = StringUtils.replace(indexFileString, "@document_title@", title);
        indexFileString = StringUtils.replace(indexFileString, "@indexBodyToken@", indexBodyToken);
        FileUtils.writeStringToFile(new File(tempZipFolder + "/INDEX.HTM"), indexFileString);

        readmeFileString = StringUtils.replace(readmeFileString, "@readmeToken@", readmeToken);
        FileUtils.writeStringToFile(new File(tempZipFolder + "/README.TXT"), readmeFileString);

        // move template files & replace tokens
        //            FileUtils.copyFileToDirectory(new File(secEmailTempZipLocation + "/INDEX.HTM"), tempZipFolder, false);
        //            FileUtils.copyFileToDirectory(new File(secEmailTempZipLocation + "/README.TXT"), tempZipFolder, false);

        // create sub-directories
        String nhinSubDirectoryPath = tempZipFolder + "/IHE_XDM/SUBSET01";
        File nhinSubDirectory = new File(nhinSubDirectoryPath);
        boolean isNhinSubDirectoryCreated = nhinSubDirectory.mkdirs();
        if (!isNhinSubDirectoryCreated) {
            LOG.error("Error creating NHIN sub-directory: " + nhinSubDirectory.getAbsolutePath());
            throw new ApplicationRuntimeException(
                    "Error creating NHIN sub-directory: " + nhinSubDirectory.getAbsolutePath());
        }
        FileOutputStream metadataStream = new FileOutputStream(
                new File(nhinSubDirectoryPath + "/METADATA.XML"));
        metadataStream.write(metadataXMl.getBytes());
        metadataStream.flush();
        metadataStream.close();
        FileOutputStream documentStream = new FileOutputStream(
                new File(nhinSubDirectoryPath + "/DOCUMENT" + extension));
        documentStream.write(content.getBytes());
        documentStream.flush();
        documentStream.close();

        String zipFile = secEmailTempZipLocation + "/" + tempZipFolder.getName() + ".ZIP";
        byte[] buffer = new byte[1024];
        //            FileOutputStream fos = new FileOutputStream(zipFile);
        //            ZipOutputStream zos = new ZipOutputStream(fos);

        List<String> fileList = generateFileList(tempZipFolder);
        ByteArrayOutputStream bout = new ByteArrayOutputStream(fileList.size());
        ZipOutputStream zos = new ZipOutputStream(bout);
        //            LOG.info("File List size: "+fileList.size());
        for (String file : fileList) {
            ZipEntry ze = new ZipEntry(file);
            zos.putNextEntry(ze);
            FileInputStream in = new FileInputStream(tempZipFolder + File.separator + file);
            int len;
            while ((len = in.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
            in.close();
        }
        zos.closeEntry();
        // remember close it
        zos.close();

        DataSource source = new ByteArrayDataSource(bout.toByteArray(), "application/zip");
        mbp2.setDataHandler(new DataHandler(source));
        mbp2.setFileName(docType + ".ZIP");

        /******** END NHIN COMPLIANCE CHANGES *****/

        //            mbp2.setFileName(fileName);
        //            mbp2.setHeader("Content-Type", contentType);

        final Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
        msg.setContent(mp);
        msg.setSentDate(new Date());

        //            FileUtils.deleteDirectory(tempZipFolder);
    } catch (AddressException e) {
        LOG.error("Error creating email message!");
        throw new ApplicationRuntimeException("Error creating message!", e);
    } catch (MessagingException e) {
        LOG.error("Error creating email message!");
        throw new ApplicationRuntimeException("Error creating message!", e);
    } catch (IOException e) {
        LOG.error(e.getMessage());
        throw new ApplicationRuntimeException(e.getMessage());
    } finally {
        //reset filelist contents
        fileList = new ArrayList<String>();
    }
    return msg;
}

From source file:de.unisaarland.swan.export.ExportUtil.java

private void marshalScheme(Project proj, ZipOutputStream zos) throws IOException {
    final Scheme schemeOrig = proj.getScheme();
    final de.unisaarland.swan.export.model.xml.scheme.Scheme schemeExport = (de.unisaarland.swan.export.model.xml.scheme.Scheme) mapperFacade
            .map(schemeOrig, SCHEME_EXPORT_CLASS);

    String fileName = schemeExport.getName() + ".xml";
    File schemefile = new File(fileName);

    marshalXMLToSingleFile(schemeExport, schemefile);

    zos.putNextEntry(new ZipEntry(fileName));
    zos.write(FileUtils.readFileToByteArray(schemefile));
    zos.closeEntry();//from w w w.  ja v  a  2 s  . c o  m
}

From source file:com.webpagebytes.cms.controllers.FlatStorageImporterExporter.java

protected void exportUris(ZipOutputStream zos, String path) throws WPBIOException {
    try {//  w w w.j  a va 2s .c  o m
        List<WPBUri> uris = dataStorage.getAllRecords(WPBUri.class);
        ZipEntry zeExternalGuid = new ZipEntry(path);
        zos.putNextEntry(zeExternalGuid);
        zos.closeEntry();
        for (WPBUri uri : uris) {
            String guidPath = PATH_URIS + uri.getExternalKey() + "/";
            Map<String, Object> map = new HashMap<String, Object>();
            exporter.export(uri, map);
            String metadataXml = guidPath + "metadata.xml";
            ZipEntry metadataZe = new ZipEntry(metadataXml);
            zos.putNextEntry(metadataZe);
            exportToXMLFormat(map, zos);
            zos.closeEntry();

            String parametersPath = String.format(PATH_URI_PARAMETERS, uri.getExternalKey());
            ZipEntry paramsZe = new ZipEntry(parametersPath);
            zos.putNextEntry(paramsZe);
            zos.closeEntry();

            exportParameters(uri.getExternalKey(), zos, parametersPath);
        }
    } catch (IOException e) {
        log.log(Level.SEVERE, e.getMessage(), e);
        throw new WPBIOException("Cannot export uri's to Zip", e);
    }
}

From source file:cn.edu.sdust.silence.itransfer.filemanage.FileManager.java

private void zip_folder(File file, ZipOutputStream zout) throws IOException {
    byte[] data = new byte[BUFFER];
    int read;/*from   w w w . j  a v  a2s  .com*/

    if (file.isFile()) {
        ZipEntry entry = new ZipEntry(file.getName());
        zout.putNextEntry(entry);
        BufferedInputStream instream = new BufferedInputStream(new FileInputStream(file));

        while ((read = instream.read(data, 0, BUFFER)) != -1)
            zout.write(data, 0, read);

        zout.closeEntry();
        instream.close();

    } else if (file.isDirectory()) {
        String[] list = file.list();
        int len = list.length;

        for (int i = 0; i < len; i++)
            zip_folder(new File(file.getPath() + "/" + list[i]), zout);
    }
}

From source file:com.taobao.android.tpatch.utils.JarSplitUtils.java

/**
 * 2jar?,??jar//  w  w  w .j a va  2 s.  c o  m
 * @param baseJar
 * @param diffJar
 * @param outJar
 */
public static void unionJar(File baseJar, File diffJar, File outJar) throws IOException {
    File outParentFolder = outJar.getParentFile();
    if (!outParentFolder.exists()) {
        outParentFolder.mkdirs();
    }
    List<String> diffEntries = getZipEntries(diffJar);
    FileOutputStream fos = new FileOutputStream(outJar);
    ZipOutputStream jos = new ZipOutputStream(fos);
    final byte[] buffer = new byte[8192];
    FileInputStream fis = new FileInputStream(baseJar);
    ZipInputStream zis = new ZipInputStream(fis);

    try {
        // loop on the entries of the jar file package and put them in the final jar
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            // do not take directories or anything inside a potential META-INF folder.
            if (entry.isDirectory()) {
                continue;
            }
            String name = entry.getName();
            if (diffEntries.contains(name)) {
                continue;
            }
            JarEntry newEntry;
            // Preserve the STORED method of the input entry.
            if (entry.getMethod() == JarEntry.STORED) {
                newEntry = new JarEntry(entry);
            } else {
                // Create a new entry so that the compressed len is recomputed.
                newEntry = new JarEntry(name);
            }
            // add the entry to the jar archive
            jos.putNextEntry(newEntry);

            // read the content of the entry from the input stream, and write it into the archive.
            int count;
            while ((count = zis.read(buffer)) != -1) {
                jos.write(buffer, 0, count);
            }
            // close the entries for this file
            jos.closeEntry();
            zis.closeEntry();
        }
    } finally {
        zis.close();
    }
    fis.close();
    jos.close();

}