Example usage for java.util.zip ZipInputStream read

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

Introduction

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

Prototype

public int read(byte[] b, int off, int len) throws IOException 

Source Link

Document

Reads from the current ZIP entry into an array of bytes.

Usage

From source file:org.springframework.roo.addon.roobot.eclipse.client.AddOnRooBotEclipseOperationsImpl.java

private boolean populateBundleCache(boolean startupTime) {
    boolean success = false;
    InputStream is = null;/* w ww.  ja v  a  2  s .com*/
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        String url = props.getProperty("roobot.url", ROOBOT_XML_URL);
        if (url == null) {
            log.warning("Bundle properties could not be loaded");
            return false;
        }
        if (url.startsWith("http://")) {
            // Handle it as HTTP
            URL httpUrl = new URL(url);
            String failureMessage = urlInputStreamService.getUrlCannotBeOpenedMessage(httpUrl);
            if (failureMessage != null) {
                if (!startupTime) {
                    // This wasn't just an eager startup time attempt, so let's display the error reason
                    // (for startup time, we just fail quietly)
                    log.warning(failureMessage);
                }
                return false;
            }
            // It appears we can acquire the URL, so let's do it
            is = urlInputStreamService.openConnection(httpUrl);
        } else {
            // Fallback to normal protocol handler (likely in local development testing etc
            is = new URL(url).openStream();
        }
        if (is == null) {
            log.warning("Could not connect to Roo Addon bundle repository index");
            return false;
        }

        ZipInputStream zip = new ZipInputStream(is);
        zip.getNextEntry();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[8192];
        int length = -1;
        while (zip.available() > 0) {
            length = zip.read(buffer, 0, 8192);
            if (length > 0) {
                baos.write(buffer, 0, length);
            }
        }

        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        Document roobotXml = db.parse(bais);

        if (roobotXml != null) {
            bundleCache.clear();
            for (Element bundleElement : XmlUtils.findElements("/roobot/bundles/bundle",
                    roobotXml.getDocumentElement())) {
                String bsn = bundleElement.getAttribute("bsn");
                List<Comment> comments = new LinkedList<Comment>();
                for (Element commentElement : XmlUtils.findElements("comments/comment", bundleElement)) {
                    comments.add(new Comment(Rating.fromInt(new Integer(commentElement.getAttribute("rating"))),
                            commentElement.getAttribute("comment"),
                            dateFormat.parse(commentElement.getAttribute("date"))));
                }
                Bundle bundle = new Bundle(bundleElement.getAttribute("bsn"),
                        new Float(bundleElement.getAttribute("uaa-ranking")).floatValue(), comments);

                for (Element versionElement : XmlUtils.findElements("versions/version", bundleElement)) {
                    if (bsn != null && bsn.length() > 0 && versionElement != null) {
                        String signedBy = "";
                        String pgpKey = versionElement.getAttribute("pgp-key-id");
                        if (pgpKey != null && pgpKey.length() > 0) {
                            Element pgpSigned = XmlUtils.findFirstElement(
                                    "/roobot/pgp-keys/pgp-key[@id='" + pgpKey + "']/pgp-key-description",
                                    roobotXml.getDocumentElement());
                            if (pgpSigned != null) {
                                signedBy = pgpSigned.getAttribute("text");
                            }
                        }

                        Map<String, String> commands = new HashMap<String, String>();
                        for (Element shell : XmlUtils.findElements("shell-commands/shell-command",
                                versionElement)) {
                            commands.put(shell.getAttribute("command"), shell.getAttribute("help"));
                        }

                        StringBuilder versionBuilder = new StringBuilder();
                        versionBuilder.append(versionElement.getAttribute("major")).append(".")
                                .append(versionElement.getAttribute("minor"));
                        String versionMicro = versionElement.getAttribute("micro");
                        if (versionMicro != null && versionMicro.length() > 0) {
                            versionBuilder.append(".").append(versionMicro);
                        }
                        String versionQualifier = versionElement.getAttribute("qualifier");
                        if (versionQualifier != null && versionQualifier.length() > 0) {
                            versionBuilder.append(".").append(versionQualifier);
                        }

                        String rooVersion = versionElement.getAttribute("roo-version");
                        if (rooVersion.equals("*") || rooVersion.length() == 0) {
                            rooVersion = getVersionForCompatibility();
                        } else {
                            String[] split = rooVersion.split("\\.");
                            if (split.length > 2) {
                                //only interested in major.minor
                                rooVersion = split[0] + "." + split[1];
                            }
                        }

                        BundleVersion version = new BundleVersion(versionElement.getAttribute("url"),
                                versionElement.getAttribute("obr-url"), versionBuilder.toString(),
                                versionElement.getAttribute("name"),
                                new Long(versionElement.getAttribute("size")).longValue(),
                                versionElement.getAttribute("description"), pgpKey, signedBy, rooVersion,
                                commands);
                        // For security reasons we ONLY accept httppgp:// add-on versions
                        if (!version.getUri().startsWith("httppgp://")) {
                            continue;
                        }
                        bundle.addVersion(version);
                    }
                    bundleCache.put(bsn, bundle);
                }
            }
            success = true;
        }
        zip.close();
        baos.close();
        bais.close();
    } catch (Throwable ignore) {
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException ignored) {
        }
    }
    if (success && startupTime) {
        //printAddonStats();
    }
    return success;
}

From source file:io.sledge.core.impl.extractor.SledgeApplicationPackageExtractor.java

@Override
public DeploymentConfiguration getDeploymentConfiguration(InputStream appPackageInputStream) {
    DeploymentConfiguration deploymentConfig = null;
    ZipInputStream zipStream = new ZipInputStream(new BufferedInputStream(appPackageInputStream),
            Charset.forName("UTF-8"));

    try {/*from ww  w.  ja v a  2 s  .  c o  m*/
        byte[] buffer = new byte[2048];
        ZipEntry zipEntry = null;

        while ((zipEntry = zipStream.getNextEntry()) != null) {

            if (zipEntry.isDirectory()) {
                zipStream.closeEntry();
                continue;
            }

            if (zipEntry.getName().startsWith(SLEDGEFILE_XML)) {
                ByteArrayOutputStream output = new ByteArrayOutputStream();

                int length;
                while ((length = zipStream.read(buffer, 0, buffer.length)) >= 0) {
                    output.write(buffer, 0, length);
                }

                DeploymentConfigurationReader deploymentConfigReader = new DeploymentConfigurationReaderXml();
                deploymentConfig = deploymentConfigReader
                        .parseDeploymentConfiguration(new ByteArrayInputStream(output.toByteArray()));

                zipStream.closeEntry();

                // Stop here, the file is read
                break;
            }
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        try {
            zipStream.close();
            appPackageInputStream.reset();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    return deploymentConfig;
}

From source file:com.marklogic.contentpump.CompressedDelimitedTextReader.java

private boolean nextKeyValueInZip() throws IOException, InterruptedException {
    ByteArrayOutputStream baos;//from w  ww . j  ava  2  s.c om
    ZipInputStream zis = (ZipInputStream) zipIn;
    while (true) {
        currZipEntry = zis.getNextEntry();
        if (currZipEntry == null) {
            break;
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("ZipEntry: " + currZipEntry.getName());
        }
        if (currZipEntry.getSize() == 0) {
            continue;
        }
        subId = currZipEntry.getName();
        long size = currZipEntry.getSize();
        if (size == -1) {
            baos = new ByteArrayOutputStream();
        } else {
            baos = new ByteArrayOutputStream((int) size);
        }
        int nb;
        while ((nb = zis.read(buf, 0, buf.length)) != -1) {
            baos.write(buf, 0, nb);
        }
        if (encoding == null) {
            instream = new InputStreamReader(new ByteArrayInputStream(baos.toByteArray()));
        } else {
            instream = new InputStreamReader(new ByteArrayInputStream(baos.toByteArray()), encoding);
        }
        baos.close();
        parser = new CSVParser(instream, CSVParserFormatter.getFormat(delimiter, encapsulator, true, true));
        parserIterator = parser.iterator();
        // clear metadata
        fields = null;
        if (super.nextKeyValue()) {
            // current delim txt has next
            return true;
        }
        // continue read next zip entry if any
    }
    // end of zip
    if (iterator != null && iterator.hasNext()) {
        close();
        initStream(iterator.next());
        return nextKeyValueInZip();
    } else {
        hasNext = false;
        return false;
    }
}

From source file:org.dhatim.ect.formats.unedifact.UnEdifactSpecificationReader.java

private void readDefinitionEntries(ZipInputStream folderZip, ZipDirectoryEntry... entries) throws IOException {

    ZipEntry fileEntry = folderZip.getNextEntry();
    while (fileEntry != null) {
        String fName = new File(fileEntry.getName().toLowerCase()).getName().replaceFirst("tr", "ed");
        for (ZipDirectoryEntry entry : entries) {
            if (fName.startsWith(entry.getDirectory())) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();

                byte[] bytes = new byte[BUFFER];
                int size;
                while ((size = folderZip.read(bytes, 0, bytes.length)) != -1) {
                    baos.write(bytes, 0, size);
                }/*from   w w w .  j a va  2 s  . co m*/

                ZipInputStream zipInputStream = new ZipInputStream(
                        new ByteArrayInputStream(baos.toByteArray()));
                readZipEntry(entry.getEntries(), zipInputStream, entry.getFile());
                zipInputStream.close();
            }
        }
        folderZip.closeEntry();
        fileEntry = folderZip.getNextEntry();
    }
}

From source file:com.oprisnik.semdroid.Semdroid.java

protected void extract(InputStream source, File targetDir) {
    if (!targetDir.exists()) {
        targetDir.mkdirs();//from w w  w.j  ava 2 s .c  om
    }
    if (BuildConfig.DEBUG) {
        Log.d(TAG, "Extracting to " + targetDir);
    }

    try {
        ZipInputStream zip = new ZipInputStream(source);
        ZipEntry entry = null;

        while ((entry = zip.getNextEntry()) != null) {
            if (entry.isDirectory()) {
                File dir = new File(targetDir, entry.getName());
                if (!dir.exists()) {
                    dir.mkdirs();
                }
            } else {
                File newFile = new File(targetDir, entry.getName());
                FileOutputStream fout = new FileOutputStream(newFile);
                if (BuildConfig.DEBUG) {
                    Log.d(TAG, "Extracting " + entry.getName() + " to " + newFile);
                }

                byte[] data = new byte[BUFFER];
                int count;
                while ((count = zip.read(data, 0, BUFFER)) != -1) {
                    fout.write(data, 0, count);
                }
                zip.closeEntry();
                fout.close();
            }

        }
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    } finally {
        IOUtils.closeQuietly(source);
    }
}

From source file:org.n52.wps.server.feed.AlgorithmFeed.java

private void unzipFeed(InputStream is) throws IOException {
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
    ZipEntry entry;// w  w w .  jav a2 s.  c  o m

    while ((entry = zis.getNextEntry()) != null) {
        String fileName = entry.getName();
        File newFile = new File(localPath + File.separator + fileName);
        if (!entry.isDirectory()) {
            LOGGER.info("Unzipping: " + newFile.getAbsolutePath());

            //create all non existing folders
            new File(newFile.getParent()).mkdirs();
            FileOutputStream fos = new FileOutputStream(newFile);

            int size;
            byte[] buffer = new byte[2048];
            BufferedOutputStream bos = new BufferedOutputStream(fos, buffer.length);
            while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
                bos.write(buffer, 0, size);
            }

            bos.flush();
            bos.close();
        }
    }
    zis.close();
    is.close();

    LOGGER.info("All contents unzipped. Folder was: " + localPath);
}

From source file:org.dhatim.ect.formats.unedifact.UnEdifactSpecificationReader.java

private boolean readZipEntry(Map<String, byte[]> files, ZipInputStream folderZip, String entry)
        throws IOException {

    boolean result = false;

    ZipEntry fileEntry = folderZip.getNextEntry();
    while (fileEntry != null) {
        String fileName = fileEntry.getName();
        String fName = new File(fileName.toLowerCase()).getName().replaceFirst("tr", "ed");
        if (fName.startsWith(entry) || entry.equals("*")) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            byte[] bytes = new byte[2048];
            int size;
            while ((size = folderZip.read(bytes, 0, bytes.length)) != -1) {
                translatePseudoGraph(bytes);
                baos.write(bytes, 0, size);
            }/*from w w w .j av a2 s. c  om*/

            File file = new File(fileName);
            String messageName = file.getName().toUpperCase();

            result = true;
            messages.add(messageName);
            if (entry.equals("*")) {
                Matcher match = entryFileName.matcher(messageName);
                if (match.matches()) {
                    String entryName = match.group(1);
                    files.put(entryName, baos.toByteArray());
                    versions.add((match.group(2) + match.group(3)).toLowerCase());
                }
            } else {
                files.put(entry, baos.toByteArray());
                break;
            }
        }
        folderZip.closeEntry();
        fileEntry = folderZip.getNextEntry();
    }

    return result;
}

From source file:com.glaf.core.util.ZipUtils.java

public static void unzip(java.io.InputStream inputStream, String path, List<String> excludes) throws Exception {
    File file = new File(path);
    FileUtils.mkdirsWithExistsCheck(file);
    ZipInputStream zipInputStream = null;
    FileOutputStream fileoutputstream = null;
    BufferedOutputStream bufferedoutputstream = null;
    try {//  w w w.  j a v a2  s. c  om
        zipInputStream = new ZipInputStream(inputStream);
        java.util.zip.ZipEntry zipEntry;
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            boolean isDirectory = zipEntry.isDirectory();
            byte abyte0[] = new byte[BUFFER];
            String s1 = zipEntry.getName();
            String ext = FileUtils.getFileExt(s1);
            if (excludes.contains(ext) || excludes.contains(ext.toLowerCase())) {
                continue;
            }

            s1 = convertEncoding(s1);

            String s2 = path + sp + s1;
            s2 = FileUtils.getJavaFileSystemPath(s2);

            if (s2.indexOf('/') != -1 || isDirectory) {
                String s4 = s2.substring(0, s2.lastIndexOf('/'));
                File file2 = new File(s4);
                FileUtils.mkdirsWithExistsCheck(file2);
            }
            if (isDirectory) {
                continue;
            }
            fileoutputstream = new FileOutputStream(s2);
            bufferedoutputstream = new BufferedOutputStream(fileoutputstream, BUFFER);
            int i = 0;
            while ((i = zipInputStream.read(abyte0, 0, BUFFER)) != -1) {
                bufferedoutputstream.write(abyte0, 0, i);
            }
            bufferedoutputstream.flush();
            IOUtils.closeStream(fileoutputstream);
            IOUtils.closeStream(bufferedoutputstream);
        }

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(zipInputStream);
        IOUtils.closeStream(fileoutputstream);
        IOUtils.closeStream(bufferedoutputstream);
    }
}

From source file:com.glaf.core.util.ZipUtils.java

public static void unzip(File zipFile, String dir) throws Exception {
    File file = new File(dir);
    FileUtils.mkdirsWithExistsCheck(file);
    FileInputStream fileInputStream = null;
    ZipInputStream zipInputStream = null;
    FileOutputStream fileoutputstream = null;
    BufferedOutputStream bufferedoutputstream = null;
    try {//from w  ww .j  av a2 s. co  m
        fileInputStream = new FileInputStream(zipFile);
        zipInputStream = new ZipInputStream(fileInputStream);
        fileInputStream = new FileInputStream(zipFile);
        zipInputStream = new ZipInputStream(fileInputStream);
        java.util.zip.ZipEntry zipEntry;
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            boolean isDirectory = zipEntry.isDirectory();
            byte abyte0[] = new byte[BUFFER];
            String s1 = zipEntry.getName();
            s1 = convertEncoding(s1);

            String s2 = dir + "/" + s1;
            s2 = FileUtils.getJavaFileSystemPath(s2);

            if (s2.indexOf('/') != -1 || isDirectory) {
                String s4 = s2.substring(0, s2.lastIndexOf('/'));
                File file2 = new File(s4);
                FileUtils.mkdirsWithExistsCheck(file2);
            }

            if (isDirectory) {
                continue;
            }

            fileoutputstream = new FileOutputStream(s2);
            bufferedoutputstream = new BufferedOutputStream(fileoutputstream, BUFFER);
            int i = 0;
            while ((i = zipInputStream.read(abyte0, 0, BUFFER)) != -1) {
                bufferedoutputstream.write(abyte0, 0, i);
            }
            bufferedoutputstream.flush();
            IOUtils.closeStream(fileoutputstream);
            IOUtils.closeStream(bufferedoutputstream);
        }

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(fileInputStream);
        IOUtils.closeStream(zipInputStream);
        IOUtils.closeStream(fileoutputstream);
        IOUtils.closeStream(bufferedoutputstream);
    }
}

From source file:org.arquillian.warp.ftest.installation.ContainerInstaller.java

private void unzip(InputStream inputStream, File destination, boolean overwrite) {
    try {/* ww w  .  j a va  2 s. c o m*/
        byte[] buf = new byte[1024];
        ZipInputStream zipinputstream = null;
        ZipEntry zipentry;
        zipinputstream = new ZipInputStream(inputStream);

        zipentry = zipinputstream.getNextEntry();
        while (zipentry != null) {
            int n;
            FileOutputStream fileoutputstream;
            File newFile = new File(destination, zipentry.getName());
            if (zipentry.isDirectory()) {
                newFile.mkdirs();
                zipentry = zipinputstream.getNextEntry();
                continue;
            }

            if (newFile.exists() && overwrite) {
                log.info("Overwriting " + newFile);
                newFile.delete();
            }

            fileoutputstream = new FileOutputStream(newFile);

            while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
                fileoutputstream.write(buf, 0, n);
            }

            fileoutputstream.close();
            zipinputstream.closeEntry();
            zipentry = zipinputstream.getNextEntry();

        }

        zipinputstream.close();
    } catch (Exception e) {
        throw new IllegalStateException("Can't unzip input stream", e);
    }
}