Example usage for java.util.zip ZipInputStream getNextEntry

List of usage examples for java.util.zip ZipInputStream getNextEntry

Introduction

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

Prototype

public ZipEntry getNextEntry() throws IOException 

Source Link

Document

Reads the next ZIP file entry and positions the stream at the beginning of the entry data.

Usage

From source file:com.github.jknack.amd4j.ClosureMinifier.java

/**
 * Build the default list of google closure external variable files.
 * Taken from: com.google.javascript.jscomp.CommandLineRunner
 *
 * @return a mutable list of source files.
 * @throws IOException On error when working with externs.zip
 *//*from   w w  w . j  a va2s.  c  o  m*/
protected List<SourceFile> getDefaultExterns() throws IOException {
    ZipInputStream zip = null;
    try {
        InputStream input = CommandLineRunner.class.getResourceAsStream("/externs.zip");
        notNull(input, "The externs.zip file was not found within the closure classpath");

        zip = new ZipInputStream(input);
        Map<String, SourceFile> externsMap = Maps.newHashMap();
        ZipEntry entry = zip.getNextEntry();
        while (entry != null) {
            BufferedInputStream entryStream = new BufferedInputStream(ByteStreams.limit(zip, entry.getSize()));
            externsMap.put(entry.getName(), SourceFile.fromInputStream(
                    // Give the files an odd prefix, so that they do not conflict
                    // with the user's files.
                    "externs.zip//" + entry.getName(), entryStream));
            entry = zip.getNextEntry();
        }

        Preconditions.checkState(externsMap.keySet().equals(Sets.newHashSet(DEFAULT_EXTERNS_NAMES)),
                "Externs zip must match our hard-coded list of externs.");

        // Order matters, so the resources must be added to the result list
        // in the expected order.
        List<SourceFile> externs = Lists.newArrayList();
        for (String key : DEFAULT_EXTERNS_NAMES) {
            externs.add(externsMap.get(key));
        }

        return externs;
    } finally {
        IOUtils.closeQuietly(zip);
    }
}

From source file:org.saiku.plugin.resources.PentahoRepositoryResource2.java

@POST
@Path("/zipupload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadArchiveZip(@FormDataParam("file") InputStream uploadedInputStream,
        @FormDataParam("file") FormDataContentDisposition fileDetail,
        @FormDataParam("directory") String directory) {
    String zipFile = fileDetail.getFileName();
    String output = "";
    try {/*w  w w  .  j  av a2s .c  o m*/
        if (StringUtils.isBlank(zipFile))
            throw new Exception("You must specify a zip file to upload");

        output = "Uploding file: " + zipFile + " ...\r\n";
        ZipInputStream zis = new ZipInputStream(uploadedInputStream);
        ZipEntry ze = zis.getNextEntry();
        byte[] doc = null;
        boolean isFile = false;
        if (ze == null) {
            doc = IOUtils.toByteArray(uploadedInputStream);
            isFile = true;
        }
        while (ze != null || doc != null) {
            String fileName = null;
            if (!isFile) {
                fileName = ze.getName();
                doc = IOUtils.toByteArray(zis);
            } else {
                fileName = zipFile;
            }

            output += "Saving " + fileName + "... ";
            String fullPath = (StringUtils.isNotBlank(directory)) ? directory + "/" + fileName : fileName;

            String content = new String(doc);
            Response r = saveResource(fullPath, content);
            doc = null;

            if (Status.OK.getStatusCode() != r.getStatus()) {
                output += " ERROR: " + r.getEntity().toString() + "\r\n";
            } else {
                output += " OK\r\n";
            }
            if (!isFile)
                ze = zis.getNextEntry();
        }

        if (!isFile) {
            zis.closeEntry();
            zis.close();
        }
        uploadedInputStream.close();

        output += " SUCCESSFUL!\r\n";
        return Response.ok(output).build();

    } catch (Exception e) {
        log.error("Cannot unzip resources " + zipFile, e);
        String error = ExceptionUtils.getRootCauseMessage(e);
        return Response.serverError().entity(output + "\r\n" + error).build();
    }
}

From source file:de.static_interface.sinklibrary.Updater.java

/**
 * Part of Zip-File-Extractor, modified by Gravity for use with Bukkit
 *///from   w  w  w . jav a 2 s  .  c o  m
private void unzip(File zipFile) {
    byte[] buffer = new byte[1024];

    try {
        File outputFolder = zipFile.getParentFile();
        if (!outputFolder.exists()) {
            outputFolder.mkdir();
        }

        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {

            String fileName = ze.getName();
            File newFile = new File(outputFolder + File.separator + fileName);
            if (!newFile.exists() && newFile.getName().toLowerCase().endsWith(".jar")) {
                ze = zis.getNextEntry();
                continue;
            }

            FileOutputStream fos = new FileOutputStream(newFile);

            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }

            fos.close();
            ze = zis.getNextEntry();
        }

        zis.closeEntry();
        zis.close();

        zipFile.delete();

    } catch (IOException ex) {
        SinkLibrary.getInstance().getLogger()
                .warning("The auto-updater tried to unzip a new update file, but was unsuccessful.");
        result = Updater.UpdateResult.FAIL_DOWNLOAD;
        ex.printStackTrace();
    }
}

From source file:com.github.sampov2.OneJarMojo.java

private InputStream getFileBytes(ZipInputStream is, String name) throws IOException {
    ZipEntry entry = null;/*  w w w . ja v  a  2s .  c o m*/
    while ((entry = is.getNextEntry()) != null) {
        if (entry.getName().equals(name)) {
            byte[] data = IOUtils.toByteArray(is);
            return new ByteArrayInputStream(data);
        }
    }
    return null;
}

From source file:io.fabric8.tooling.archetype.generator.ArchetypeHelper.java

/**
 * Searches ZIP archive and returns properties found in "META-INF/maven/archetype-metadata.xml" entry
 *
 * @return//  w  w  w  . j  a  v  a  2 s . c om
 * @throws IOException
 */
public Map<String, String> parseProperties() throws IOException {
    Map<String, String> replaceProperties = new HashMap<String, String>();
    ZipInputStream zip = null;
    try {
        zip = new ZipInputStream(archetypeIn);
        boolean ok = true;
        while (ok) {
            ZipEntry entry = zip.getNextEntry();
            if (entry == null) {
                ok = false;
            } else {
                if (!entry.isDirectory()) {
                    String fullName = entry.getName();
                    if (fullName != null && fullName.equals("META-INF/maven/archetype-metadata.xml")) {
                        parseReplaceProperties(zip, replaceProperties);
                    }
                }
                zip.closeEntry();
            }
        }
    } catch (Exception e) {
        throw new IOException(e.getMessage(), e);
    } finally {
        if (zip != null) {
            zip.close();
        }
    }
    return replaceProperties;
}

From source file:aurelienribon.gdxsetupui.ProjectSetup.java

/**
 * Selected libraries are inflated from their zip files, and put in the
 * libs folders of the projects./*w w w .  j ava2s.c  om*/
 * @throws IOException
 */
public void inflateLibraries() throws IOException {
    File commonPrjLibsDir = new File(tmpDst, "/prj-common/libs");
    File desktopPrjLibsDir = new File(tmpDst, "/prj-desktop/libs");
    File androidPrjLibsDir = new File(tmpDst, "/prj-android/libs");
    File htmlPrjLibsDir = new File(tmpDst, "/prj-html/war/WEB-INF/lib");
    File iosPrjLibsDir = new File(tmpDst, "/prj-ios/libs");
    File dataDir = new File(tmpDst, "/prj-android/assets");

    for (String library : cfg.libraries) {
        InputStream is = new FileInputStream(cfg.librariesZipPaths.get(library));
        ZipInputStream zis = new ZipInputStream(is);
        ZipEntry entry;

        LibraryDef def = libs.getDef(library);

        while ((entry = zis.getNextEntry()) != null) {
            if (entry.isDirectory())
                continue;
            String entryName = entry.getName();

            for (String elemName : def.libsCommon)
                if (entryName.endsWith(elemName))
                    copyEntry(zis, elemName, commonPrjLibsDir);
            for (String elemName : def.libsDesktop)
                if (entryName.endsWith(elemName))
                    copyEntry(zis, elemName, desktopPrjLibsDir);
            for (String elemName : def.libsAndroid)
                if (entryName.endsWith(elemName))
                    copyEntry(zis, elemName, androidPrjLibsDir);
            for (String elemName : def.libsHtml)
                if (entryName.endsWith(elemName))
                    copyEntry(zis, elemName, htmlPrjLibsDir);
            for (String elemName : def.libsIos)
                if (entryName.endsWith(elemName))
                    copyEntry(zis, elemName, iosPrjLibsDir);
            for (String elemName : def.data)
                if (entryName.endsWith(elemName))
                    copyEntry(zis, elemName, dataDir);
        }

        zis.close();
    }
}

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

/**
 * ?//from   ww  w .  jav a 2 s .c om
 * 
 * @param event
 */
public void propertyZipUpload(FileUploadEvent event) {
    String fileName = event.getFile().getFileName();
    LOGGER.info("Deal uploaded file: {}", fileName);
    ZipInputStream zipInputStream = null;
    try {
        zipInputStream = new ZipInputStream(event.getFile().getInputstream());
        ZipEntry nextEntry = null;
        while ((nextEntry = zipInputStream.getNextEntry()) != null) {
            String entryName = nextEntry.getName();
            savePropertyGroup(entryName, Files.getNameWithoutExtension(entryName), zipInputStream);
        }
    } catch (IOException e) {
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, "Upload File error.", fileName));
        LOGGER.error("Upload File Exception.", e);
    } finally {
        if (zipInputStream != null) {
            try {
                zipInputStream.close();
            } catch (IOException e) {
                // DO NOTHING
            }
        }
    }
}

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

/**
 * ?(Old)//from  w ww.j  a  va  2  s  .co  m
 * 
 * @param event
 */
@Deprecated
public void propertyZipUploadOld(FileUploadEvent event) {
    String fileName = event.getFile().getFileName();
    LOGGER.info("Deal uploaded file: {}", fileName);
    ZipInputStream zipInputStream = null;
    try {
        zipInputStream = new ZipInputStream(event.getFile().getInputstream());
        ZipEntry nextEntry = null;
        while ((nextEntry = zipInputStream.getNextEntry()) != null) {
            String entryName = nextEntry.getName();
            savePropertyGroupOld(entryName, Files.getNameWithoutExtension(entryName), zipInputStream);
        }
    } catch (IOException e) {
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, "Upload File error.", fileName));
        LOGGER.error("Upload File Exception.", e);
    } finally {
        if (zipInputStream != null) {
            try {
                zipInputStream.close();
            } catch (IOException e) {
                // DO NOTHING
            }
        }
    }
}

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  v a 2  s . c  o  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:ch.puzzle.itc.mobiliar.business.shakedown.control.ShakedownTestRunner.java

private String analyzeResult(STS sts) throws ShakedownTestException {
    String testResultPath = ConfigurationService.getProperty(ConfigKey.TEST_RESULT_PATH);
    try {//  w w w  . ja va  2s .c  om
        StringBuilder sb = new StringBuilder();
        ZipInputStream zis = null;
        try {
            zis = new ZipInputStream(
                    new FileInputStream(testResultPath + File.separator + sts.getTestId() + ".zip"));
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                if (entry.getName().equals("/result.xml")) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(zis));
                    String s;
                    while ((s = reader.readLine()) != null) {
                        sb.append(s);
                    }
                }
            }
        } finally {
            if (zis != null) {
                zis.close();
            }
        }
        return sb.toString();
    } catch (FileNotFoundException e) {
        throw new ShakedownTestException("Was not able to analyze the result - no result file found!", e);
    } catch (IOException e) {
        throw new ShakedownTestException("Was not able to analyze the result", e);
    }

}