Example usage for java.util.zip ZipFile getInputStream

List of usage examples for java.util.zip ZipFile getInputStream

Introduction

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

Prototype

public InputStream getInputStream(ZipEntry entry) throws IOException 

Source Link

Document

Returns an input stream for reading the contents of the specified zip file entry.

Usage

From source file:com.shazam.fork.suite.TestClassScanner.java

private void dumpDexFilesFromApk(File apkFile, File outputFolder) throws IOException {
    ZipFile zip = null;
    InputStream classesDexInputStream = null;
    FileOutputStream fileOutputStream = null;
    try {// w w w  .  ja va 2s.  co  m
        zip = new ZipFile(apkFile);

        int index = 1;
        String currentDex;
        while (true) {
            currentDex = CLASSES_PREFIX + (index > 1 ? index : "") + DEX_EXTENSION;
            ZipEntry classesDex = zip.getEntry(currentDex);
            if (classesDex != null) {
                File dexFileDestination = new File(outputFolder, currentDex);
                classesDexInputStream = zip.getInputStream(classesDex);
                fileOutputStream = new FileOutputStream(dexFileDestination);
                copyLarge(classesDexInputStream, fileOutputStream);
                index++;
            } else {
                break;
            }
        }
    } finally {
        closeQuietly(classesDexInputStream);
        closeQuietly(fileOutputStream);
        closeQuietly(zip);
    }
}

From source file:org.apache.tika.parser.odf.OpenDocumentParser.java

private void handleZipFile(ZipFile zipFile, Metadata metadata, ParseContext context,
        EndDocumentShieldingContentHandler handler) throws IOException, TikaException, SAXException {
    // If we can, process the metadata first, then the
    //  rest of the file afterwards (TIKA-1353)
    // Only possible to guarantee that when opened from a file not a stream

    ZipEntry entry = zipFile.getEntry(META_NAME);
    if (entry != null) {
        handleZipEntry(entry, zipFile.getInputStream(entry), metadata, context, handler);
    }/*  w ww .j  a  v a 2 s.c o  m*/

    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        entry = entries.nextElement();
        if (!META_NAME.equals(entry.getName())) {
            handleZipEntry(entry, zipFile.getInputStream(entry), metadata, context, handler);
        }
    }
}

From source file:com.enioka.jqm.tools.LibraryResolverFS.java

private void loadCache(Node node, JobDef jd, EntityManager em) throws JqmPayloadException {
    jqmlogger.debug("Resolving classpath for job definition " + jd.getApplicationName());

    File jarFile = new File(FilenameUtils.concat(new File(node.getRepo()).getAbsolutePath(), jd.getJarPath()));
    File jarDir = jarFile.getParentFile();
    File libDir = new File(FilenameUtils.concat(jarDir.getAbsolutePath(), "lib"));
    File libDirExtracted = new File(FilenameUtils.concat(jarDir.getAbsolutePath(), "libFromJar"));
    File pomFile = new File(FilenameUtils.concat(jarDir.getAbsolutePath(), "pom.xml"));

    if (!jarFile.canRead()) {
        jqmlogger.warn("Cannot read file at " + jarFile.getAbsolutePath()
                + ". Job instance will crash. Check job definition or permissions on file.");
        throw new JqmPayloadException("File " + jarFile.getAbsolutePath() + " cannot be read");
    }/*from w  w  w  .j a  va 2 s. c o  m*/

    // POM file should be deleted if it comes from the jar file. Otherwise, it would stay into place and modifications to the internal
    // pom would be ignored.
    boolean pomFromJar = false;

    // 1st: if no pom, no lib dir => find a pom inside the JAR. (& copy it, we will read later)
    if (!pomFile.exists() && !libDir.exists()) {
        jqmlogger.trace("No pom inside jar directory. Checking for a pom inside the jar file");
        InputStream is = null;
        FileOutputStream os = null;
        ZipFile zf = null;

        try {
            zf = new ZipFile(jarFile);
            Enumeration<? extends ZipEntry> zes = zf.entries();
            while (zes.hasMoreElements()) {
                ZipEntry ze = zes.nextElement();
                if (ze.getName().endsWith("pom.xml")) {

                    is = zf.getInputStream(ze);
                    os = new FileOutputStream(pomFile);
                    IOUtils.copy(is, os);
                    pomFromJar = true;
                    break;
                }
            }
        } catch (Exception e) {
            throw new JqmPayloadException("Could not handle pom inside jar", e);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
            Helpers.closeQuietly(zf);
        }
    }

    // 2nd: no pom, no pom inside jar, no lib dir => find a lib dir inside the jar
    if (!pomFile.exists() && !libDir.exists()) {
        jqmlogger.trace("Checking for a lib directory inside jar");
        InputStream is = null;
        FileOutputStream os = null;
        ZipFile zf = null;
        FileUtils.deleteQuietly(libDirExtracted);

        try {
            zf = new ZipFile(jarFile);
            Enumeration<? extends ZipEntry> zes = zf.entries();
            while (zes.hasMoreElements()) {
                ZipEntry ze = zes.nextElement();
                if (ze.getName().startsWith("lib/") && ze.getName().endsWith(".jar")) {
                    if (!libDirExtracted.isDirectory() && !libDirExtracted.mkdir()) {
                        throw new JqmPayloadException("Could not extract libraries from jar");
                    }

                    is = zf.getInputStream(ze);
                    os = new FileOutputStream(FilenameUtils.concat(libDirExtracted.getAbsolutePath(),
                            FilenameUtils.getName(ze.getName())));
                    IOUtils.copy(is, os);
                }
            }
        } catch (Exception e) {
            throw new JqmPayloadException("Could not handle internal lib directory", e);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
            Helpers.closeQuietly(zf);
        }

        // If libs were extracted, put in cache and return
        if (libDirExtracted.isDirectory()) {
            FileFilter fileFilter = new WildcardFileFilter("*.jar");
            File[] files = libDirExtracted.listFiles(fileFilter);
            URL[] libUrls = new URL[files.length];
            try {
                for (int i = 0; i < files.length; i++) {
                    libUrls[i] = files[i].toURI().toURL();
                }
            } catch (Exception e) {
                throw new JqmPayloadException("Could not handle internal lib directory", e);
            }

            // Put in cache
            putInCache(libUrls, jd.getApplicationName());
            return;
        }
    }

    // 3rd: if pom, use pom!
    if (pomFile.exists() && !libDir.exists()) {
        jqmlogger.trace("Reading a pom file");

        ConfigurableMavenResolverSystem resolver = LibraryResolverMaven.getMavenResolver(em);

        // Resolve
        File[] depFiles = null;
        try {
            depFiles = resolver.loadPomFromFile(pomFile).importRuntimeDependencies().resolve()
                    .withTransitivity().asFile();
        } catch (IllegalArgumentException e) {
            // Happens when no dependencies inside pom, which is a weird use of the feature...
            jqmlogger.trace("No dependencies inside pom.xml file - no libs will be used", e);
            depFiles = new File[0];
        }

        // Extract results
        URL[] tmp = LibraryResolverMaven.extractMavenResults(depFiles);

        // Put in cache
        putInCache(tmp, jd.getApplicationName());

        // Cleanup
        if (pomFromJar && !pomFile.delete()) {
            jqmlogger.warn("Could not delete the temp pom file extracted from the jar.");
        }
        return;
    }

    // 4: if lib, use lib... (lib has priority over pom)
    if (libDir.exists()) {
        jqmlogger.trace(
                "Using the lib directory " + libDir.getAbsolutePath() + " as the source for dependencies");
        FileFilter fileFilter = new WildcardFileFilter("*.jar");
        File[] files = libDir.listFiles(fileFilter);
        URL[] tmp = new URL[files.length];
        for (int i = 0; i < files.length; i++) {
            try {
                tmp[i] = files[i].toURI().toURL();
            } catch (MalformedURLException e) {
                throw new JqmPayloadException("incorrect file inside lib directory", e);
            }
        }

        // Put in cache
        putInCache(tmp, jd.getApplicationName());
        return;
    }

    throw new JqmPayloadException(
            "There is no lib dir or no pom.xml inside the directory containing the jar or inside the jar. The jar cannot be launched.");
}

From source file:com.sshtools.j2ssh.util.DynamicClassLoader.java

private byte[] loadClassFromZipfile(File file, String name, ClassCacheEntry cache) throws IOException {
    // Translate class name to file name
    String classFileName = name.replace('.', '/') + ".class";

    ZipFile zipfile = new ZipFile(file);

    try {/*  ww  w. j a va  2 s  . c  o  m*/
        ZipEntry entry = zipfile.getEntry(classFileName);

        if (entry != null) {
            cache.origin = file;

            return loadBytesFromStream(zipfile.getInputStream(entry), (int) entry.getSize());
        } else {
            // Not found
            return null;
        }
    } finally {
        zipfile.close();
    }
}

From source file:FeatureExtraction.FeatureExtractorOOXMLStructuralPaths.java

private void ExtractStructuralFeaturesInMemory(String filePath, Map<String, Integer> structuralPaths) {
    String path;//from   w w w .ja v  a  2 s  .com
    String directoryPath;
    String fileExtension;
    try {
        ZipFile zipFile = new ZipFile(filePath);

        for (Enumeration e = zipFile.entries(); e.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            path = entry.getName();
            directoryPath = FilenameUtils.getFullPath(path);
            fileExtension = FilenameUtils.getExtension(path);

            AddStructuralPath(directoryPath, structuralPaths);
            AddStructuralPath(path, structuralPaths);

            if (fileExtension.equals("rels") || fileExtension.equals("xml")) {
                AddXMLStructuralPaths(zipFile.getInputStream(entry), path, structuralPaths);
            }
        }
    } catch (IOException ex) {
        Console.PrintException(
                String.format("Error extracting OOXML structural features from file: %s", filePath), ex);
    }
}

From source file:gui.accessories.DownloadProgressWork.java

/**
 * Uncompress all the files contained in the compressed file and its folders in the same folder where the zip file is placed. Doesn't respects the
 * directory tree of the zip file. This method seems a clear candidate to ZipManager.
 *
 * @param file Zip file.//from  w  w w .j a  va  2 s  .  co m
 * @return Count of files uncopressed.
 * @throws ZipException Exception.
 */
private int doUncompressZip(File file) throws ZipException {
    int fileCount = 0;
    try {
        byte[] buf = new byte[1024];
        ZipFile zipFile = new ZipFile(file);

        Enumeration zipFileEntries = zipFile.entries();

        while (zipFileEntries.hasMoreElements()) {
            ZipEntry zipentry = (ZipEntry) zipFileEntries.nextElement();
            if (zipentry.isDirectory()) {
                continue;
            }
            File entryZipFile = new File(zipentry.getName());
            File outputFile = new File(file.getParentFile(), entryZipFile.getName());
            FileOutputStream fileoutputstream = new FileOutputStream(outputFile);
            InputStream is = zipFile.getInputStream(zipentry);
            int n;
            while ((n = is.read(buf, 0, 1024)) > -1) {
                fileoutputstream.write(buf, 0, n);
            }
            fileoutputstream.close();
            is.close();
            fileoutputstream.close();
            fileCount++;
        }
        zipFile.close();

    } catch (IOException ex) {
        throw new ZipException(ex.getMessage());
    }

    return fileCount;
}

From source file:com.genericworkflownodes.knime.nodes.io.outputfile.OutputFileNodeModel.java

/**
 * {@inheritDoc}//w  w w . j  a  va 2s .co m
 */
@Override
protected void loadInternals(final File internDir, final ExecutionMonitor exec)
        throws IOException, CanceledExecutionException {
    ZipFile zip = new ZipFile(new File(internDir, "loadeddata"));

    @SuppressWarnings("unchecked")
    Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip.entries();

    int BUFFSIZE = 2048;
    byte[] BUFFER = new byte[BUFFSIZE];

    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();

        if (entry.getName().equals("rawdata.bin")) {
            int size = (int) entry.getSize();
            byte[] data = new byte[size];
            InputStream in = zip.getInputStream(entry);
            int len;
            int totlen = 0;
            while ((len = in.read(BUFFER, 0, BUFFSIZE)) >= 0) {
                System.arraycopy(BUFFER, 0, data, totlen, len);
                totlen += len;
            }
            this.data = new String(data);
        }
    }
    zip.close();
}

From source file:com.josue.lottery.eap.service.core.LotoImporter.java

private void readZip(File file) {

    ZipFile zipFile = null;
    try {/*from   w w w.j  a  v a2  s .c o m*/
        logger.info("unzipping ************");

        zipFile = new ZipFile(file);

        File dataDir = new File(System.getProperty("jboss.server.data.dir"));
        File dest = new File(dataDir, "deziped.htm");

        Enumeration<? extends ZipEntry> entries = zipFile.entries();

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.getName().endsWith(".HTM")) {

                InputStream stream = zipFile.getInputStream(entry);
                OutputStream oStr = null;
                try {
                    oStr = new FileOutputStream(dest);
                    IOUtils.copy(stream, oStr);

                    parseHtml(dest);

                } catch (IOException e) {
                    throw new RuntimeException(e);
                } finally {
                    IOUtils.closeQuietly(oStr);
                }
            }

        }
    } catch (IOException ex) {
        logger.error(ex);
    } finally {
        try {
            zipFile.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:FeatureExtraction.FeatureExtractorOOXMLStructuralPathsInputStream.java

private void ExtractStructuralFeaturesInMemory(InputStream fileInputStream,
        Map<String, Integer> structuralPaths) {
    String path;//  w ww .  j  a v  a2s  .  com
    String directoryPath;
    String fileExtension;
    try {
        File file = new File(fileInputStream.hashCode() + "");
        try (FileOutputStream fos = new FileOutputStream(file)) {
            IOUtils.copy(fileInputStream, fos);
        }

        ZipFile zipFile = new ZipFile(file);

        for (Enumeration e = zipFile.entries(); e.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            path = entry.getName();
            directoryPath = FilenameUtils.getFullPath(path);
            fileExtension = FilenameUtils.getExtension(path);

            AddStructuralPath(directoryPath, structuralPaths);
            AddStructuralPath(path, structuralPaths);

            if (fileExtension.equals("rels") || fileExtension.equals("xml")) {
                AddXMLStructuralPaths(zipFile.getInputStream(entry), path, structuralPaths);
            }
        }
    } catch (IOException ex) {
        Console.PrintException(String.format("Error extracting OOXML structural features from file in memory"),
                ex);
    }
}

From source file:com.dtolabs.rundeck.ExpandRunServer.java

/**
 * Return inputstream for a resource from the enclosing jar file
 *
 * @param path resource path/*ww w  .j av a 2  s  .c  om*/
 *
 * @return InputStream for the resource
 *
 * @throws IOException if an error occurs
 */
private InputStream loadResourceInternal(final String path) throws IOException {
    final ZipFile jar = new ZipFile(thisJar);
    return jar.getInputStream(new ZipEntry(path));
}