Example usage for java.util.zip ZipEntry ZipEntry

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

Introduction

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

Prototype

public ZipEntry(ZipEntry e) 

Source Link

Document

Creates a new zip entry with fields taken from the specified zip entry.

Usage

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) {
        /*//from w  ww .  j a v a2 s  . com
         * 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:io.fabric8.support.impl.SupportServiceImpl.java

private void collectFromResource(ZipOutputStream zip, Resource resource) {
    ZipEntry entry = null;/*from w w  w . j a va2 s . co m*/
    try {
        entry = new ZipEntry(resource.getName());
        zip.putNextEntry(entry);
        resource.write(zip);
    } catch (Exception e) {
        LOGGER.warn("Unable to add support resource " + resource, e);
    } finally {
        safeClose(zip);
    }
}

From source file:mediathek.controller.IoXmlSchreiben.java

private void xmlSchreibenStart() throws IOException, XMLStreamException {
    Log.systemMeldung("Start Schreiben nach: " + xmlFilePath.toAbsolutePath());
    final OutputStream outputStream = Files.newOutputStream(xmlFilePath);
    if (xmlFilePath.endsWith(GuiKonstanten.FORMAT_BZ2)) {
        bZip2CompressorOutputStream = new BZip2CompressorOutputStream(outputStream, 2);
        out = new OutputStreamWriter(bZip2CompressorOutputStream, Konstanten.KODIERUNG_UTF);
    } else if (xmlFilePath.endsWith(GuiKonstanten.FORMAT_ZIP)) {
        zipOutputStream = new ZipOutputStream(outputStream);
        ZipEntry entry = new ZipEntry(Konstanten.PROGRAMMNAME);
        zipOutputStream.putNextEntry(entry);
        out = new OutputStreamWriter(zipOutputStream, Konstanten.KODIERUNG_UTF);
    } else {//from  w w  w .  j av  a 2  s  .c  o m
        out = new OutputStreamWriter(outputStream, Konstanten.KODIERUNG_UTF);
    }

    XMLOutputFactory outFactory = XMLOutputFactory.newInstance();
    writer = outFactory.createXMLStreamWriter(out);
    writer.writeStartDocument(Konstanten.KODIERUNG_UTF, "1.0");
    writer.writeCharacters("\n");//neue Zeile
    writer.writeStartElement(Konstanten.XML_START);
    writer.writeCharacters("\n");//neue Zeile
}

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 {/*from  www.  jav 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);
    }
}

From source file:com.mc.printer.model.utils.ZipHelper.java

private static void writeZip(File file, String parentPath, ZipOutputStream zos) {
    if (file.exists()) {
        if (file.isDirectory()) {//?
            parentPath += file.getName() + File.separator;
            File[] files = file.listFiles();
            for (File f : files) {
                writeZip(f, parentPath, zos);
            }/*from w w  w.  j  a  v  a2s .c  o m*/
        } else {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(file);
                ZipEntry ze = new ZipEntry(parentPath + file.getName());
                zos.putNextEntry(ze);
                byte[] content = new byte[1024];
                int len;
                while ((len = fis.read(content)) != -1) {
                    zos.write(content, 0, len);
                    zos.flush();
                }

            } catch (FileNotFoundException e) {
                log.error("create zip file failed.", e);
            } catch (IOException e) {
                log.error("create zip file failed.", e);
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                } catch (IOException e) {
                    log.error("create zip file failed.", e);
                }
            }
        }
    }
}

From source file:it.polimi.diceH2020.launcher.utility.FileUtility.java

private @NotNull ZipEntry makeEntry(@NotNull File path, @NotNull File file) {
    String cleanPath = new File(path, file.getName()).toString()
            .replace(settings.getWorkingDirectory().toString(), "");
    return new ZipEntry(cleanPath);
}

From source file:net.sourceforge.jweb.maven.mojo.InWarMinifyMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (disabled)
        return;//www  . ja v a  2s  .c o m
    processConfiguration();
    String name = this.getBuilddir().getAbsolutePath() + File.separator + this.getFinalName() + "."
            + this.getPacking();
    this.getLog().info(name);
    MinifyFileFilter fileFilter = new MinifyFileFilter();
    int counter = 0;
    try {
        File finalWarFile = new File(name);
        File tempFile = File.createTempFile(finalWarFile.getName(), null);
        tempFile.delete();//check deletion
        boolean renameOk = finalWarFile.renameTo(tempFile);
        if (!renameOk) {
            getLog().error("Can not rename file, please check.");
        }

        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(finalWarFile));
        ZipFile zipFile = new ZipFile(tempFile);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            //no compress, just transfer to war
            if (!fileFilter.accept(entry)) {
                getLog().debug("nocompress entry: " + entry.getName());
                out.putNextEntry(entry);
                InputStream inputStream = zipFile.getInputStream(entry);
                byte[] buf = new byte[512];
                int len = -1;
                while ((len = inputStream.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                inputStream.close();
                continue;
            }

            File sourceTmp = new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"
                    + File.separator + counter + ".tmp");
            File destTmp = new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"
                    + File.separator + counter + ".min.tmp");
            FileUtils.writeStringToFile(sourceTmp, "");
            FileUtils.writeStringToFile(destTmp, "");

            //assemble arguments
            String[] provied = getYuiArguments();
            int length = (provied == null ? 0 : provied.length);
            length += 5;
            int i = 0;

            String[] ret = new String[length];

            ret[i++] = "--type";
            ret[i++] = (entry.getName().toLowerCase().endsWith(".css") ? "css" : "js");

            if (provied != null) {
                for (String s : provied) {
                    ret[i++] = s;
                }
            }

            ret[i++] = sourceTmp.getAbsolutePath();
            ret[i++] = "-o";
            ret[i++] = destTmp.getAbsolutePath();

            try {
                InputStream in = zipFile.getInputStream(entry);
                FileUtils.copyInputStreamToFile(in, sourceTmp);
                in.close();

                YUICompressorNoExit.main(ret);
            } catch (Exception e) {
                this.getLog().warn("compress error, this file will not be compressed:" + buildStack(e));
                FileUtils.copyFile(sourceTmp, destTmp);
            }

            out.putNextEntry(new ZipEntry(entry.getName()));
            InputStream compressedIn = new FileInputStream(destTmp);
            byte[] buf = new byte[512];
            int len = -1;
            while ((len = compressedIn.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            compressedIn.close();

            String sourceSize = decimalFormat.format(sourceTmp.length() * 1.0d / 1024) + " KB";
            String destSize = decimalFormat.format(destTmp.length() * 1.0d / 1024) + " KB";
            getLog().info("compressed entry:" + entry.getName() + " [" + sourceSize + " ->" + destSize + "/"
                    + numberFormat.format(1 - destTmp.length() * 1.0d / sourceTmp.length()) + "]");

            counter++;
        }
        zipFile.close();
        out.close();

        FileUtils.cleanDirectory(new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"));
        FileUtils.forceDelete(new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp"));
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:br.univali.celine.lms.utils.zip.Zip.java

private void addDir(File dirObj, ZipOutputStream out, int rootLen) throws IOException {
    File[] files = dirObj.listFiles();
    byte[] tmpBuf = new byte[1024];

    for (int i = 0; i < files.length; i++) {
        if (files[i].isDirectory()) {
            addDir(files[i], out, rootLen);
            continue;
        }//  ww  w . j a  v  a2  s.c o  m

        FileInputStream in = new FileInputStream(files[i].getAbsolutePath());

        out.putNextEntry(new ZipEntry(files[i].getAbsolutePath().substring(rootLen)));

        int len;
        while ((len = in.read(tmpBuf)) > 0) {
            out.write(tmpBuf, 0, len);
        }

        out.closeEntry();
        in.close();
    }
}

From source file:com.stehno.oxy.ZipBuilder.java

/**
 * Used to add an entry with the given parameters. The input stream will be read and closed in this
 * method.//from  w  w w .jav  a  2  s  .  c o m
 *
 * @param name the entry name
 * @param comment the entry comment
 * @param in the stream containing the entry data
 * @return a reference to the builder
 * @throws IOException if there is a problem writing the entry data
 */
public ZipBuilder addEntry(final String name, final String comment, final InputStream in) throws IOException {
    final ZipEntry entry = new ZipEntry(name);
    if (isNotBlank(comment)) {
        entry.setComment(comment);
    }
    return (addEntry(entry, in));
}

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;/*w ww .j a  v a  2s.c  o  m*/
    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;
}