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.ichi2.libanki.Media.java

/**
 * Extract zip data; return the number of files extracted. Unlike the python version, this method consumes a
 * ZipFile stored on disk instead of a String buffer. Holding the entire downloaded data in memory is not feasible
 * since some devices can have very limited heap space.
 *
 * This method closes the file before it returns.
 *//*w  ww. j  a v a 2 s.  c o m*/
public int addFilesFromZip(ZipFile z) throws IOException {
    try {
        List<Object[]> media = new ArrayList<Object[]>();
        // get meta info first
        JSONObject meta = new JSONObject(Utils.convertStreamToString(z.getInputStream(z.getEntry("_meta"))));
        // then loop through all files
        int cnt = 0;
        for (ZipEntry i : Collections.list(z.entries())) {
            if (i.getName().equals("_meta")) {
                // ignore previously-retrieved meta
                continue;
            } else {
                String name = meta.getString(i.getName());
                // normalize name for platform
                name = HtmlUtil.nfcNormalized(name);
                // save file
                String destPath = dir().concat(File.separator).concat(name);
                Utils.writeToFile(z.getInputStream(i), destPath);
                String csum = Utils.fileChecksum(destPath);
                // update db
                media.add(new Object[] { name, csum, _mtime(destPath), 0 });
                cnt += 1;
            }
        }
        if (media.size() > 0) {
            mDb.executeMany("insert or replace into media values (?,?,?,?)", media);
        }
        return cnt;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } finally {
        z.close();
    }
}

From source file:org.docx4j.openpackaging.io3.stores.ZipPartStore.java

public ZipPartStore(File f) throws Docx4JException {
    log.info("Filepath = " + f.getPath());

    ZipFile zf = null;
    try {//  ww w .j a v  a 2  s.co  m
        if (!f.exists()) {
            log.info("Couldn't find " + f.getPath());
        }
        zf = new ZipFile(f);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        throw new Docx4JException("Couldn't get ZipFile", ioe);
    }

    partByteArrays = new HashMap<String, ByteArray>();
    Enumeration entries = zf.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) entries.nextElement();
        //log.info( "\n\n" + entry.getName() + "\n" );
        InputStream in = null;
        try {
            byte[] bytes = getBytesFromInputStream(zf.getInputStream(entry));
            partByteArrays.put(entry.getName(), new ByteArray(bytes));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // At this point, we've finished with the zip file
    try {
        zf.close();
    } catch (IOException exc) {
        exc.printStackTrace();
    }
}

From source file:org.hyperic.hq.product.ClientPluginDeployer.java

public List unpackJar(String jar) throws IOException {

    ArrayList jars = new ArrayList();

    ZipFile zipfile = new ZipFile(jar);
    for (Enumeration e = zipfile.entries(); e.hasMoreElements();) {
        ZipEntry entry = (ZipEntry) e.nextElement();
        String name = entry.getName();

        if (entry.isDirectory()) {
            continue;
        }//from w ww . jav a  2 s .c o m

        int ix = name.indexOf('/');
        if (ix == -1) {
            continue;
        }

        String prefix = name.substring(0, ix);
        name = name.substring(ix + 1);

        File file = getFile(prefix, name);
        if (file == null) {
            continue;
        }

        if (name.endsWith(".jar")) {
            jars.add(file.toString());
        }

        if (upToDate(entry, file)) {
            continue;
        }

        InputStream is = zipfile.getInputStream(entry);
        try {
            write(is, file);
        } catch (IOException ioe) {
            zipfile.close();
            throw ioe;
        } finally {
            is.close();
        }
    }

    zipfile.close();

    return jars;
}

From source file:com.brienwheeler.apps.tomcat.TomcatBean.java

private void extractWarFile() {
    if (webAppBase != null && webAppBase.length() > 0) {
        ProtectionDomain protectionDomain = this.getClass().getProtectionDomain();
        URL location = protectionDomain.getCodeSource().getLocation();
        log.info("detected run JAR at " + location);

        if (!location.toExternalForm().startsWith("file:") || !location.toExternalForm().endsWith(".jar"))
            throw new IllegalArgumentException("invalid code location: " + location);

        try {//from   w w  w.  ja  v  a2  s .  c o  m
            ZipFile zipFile = new ZipFile(new File(location.toURI()));

            Enumeration<? extends ZipEntry> entryEnum = zipFile.entries();
            ZipEntry warEntry = null;
            while (entryEnum.hasMoreElements()) {
                ZipEntry entry = entryEnum.nextElement();
                String entryName = entry.getName();
                if (entryName.startsWith(webAppBase) && entryName.endsWith(".war")) {
                    warEntry = entry;
                    break;
                }
            }

            if (warEntry == null)
                throw new RuntimeException("can't find JAR entry for " + webAppBase + "*.war");

            log.info("extracting WAR file " + warEntry.getName());

            // extract web app WAR to current directory
            InputStream inputStream = zipFile.getInputStream(warEntry);
            OutputStream outputStream = new FileOutputStream(new File(warEntry.getName()));
            byte buf[] = new byte[1024];
            int nread;
            while ((nread = inputStream.read(buf, 0, 1024)) > 0) {
                outputStream.write(buf, 0, nread);
            }
            outputStream.close();
            inputStream.close();
            zipFile.close();

            String launchContextRoot = contextRoot != null ? contextRoot : webAppBase;
            if (!launchContextRoot.startsWith("/"))
                launchContextRoot = "/" + launchContextRoot;

            log.info("launching WAR file " + warEntry.getName() + " at context root " + launchContextRoot);

            // add web app to Tomcat
            Context context = tomcat.addWebapp(launchContextRoot, warEntry.getName());
            if (context instanceof StandardContext)
                ((StandardContext) context).setUnpackWAR(false);
        } catch (Exception e) {
            throw new RuntimeException("error extracting WAR file", e);
        }
    }
}

From source file:com.aurel.track.lucene.util.openOffice.OOIndexer.java

private List unzip(String zip, String destination) {
    List destLs = new ArrayList();
    Enumeration entries;/*ww w  .j a  va 2 s .  c  o m*/
    ZipFile zipFile;
    File dest = new File(destination);
    dest.mkdir();
    if (dest.isDirectory()) {

        try {
            zipFile = new ZipFile(zip);

            entries = zipFile.entries();

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

                if (entry.isDirectory()) {

                    (new File(dest.getAbsolutePath() + File.separator + entry.getName())).mkdirs();
                    continue;
                }

                if (entry.getName().lastIndexOf("/") > 0) {
                    File f = new File(dest.getAbsolutePath() + File.separator
                            + entry.getName().substring(0, entry.getName().lastIndexOf("/")));
                    f.mkdirs();
                }
                copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream(
                        new FileOutputStream(dest.getAbsolutePath() + File.separator + entry.getName())));
                destLs.add(dest.getAbsolutePath() + File.separator + TMP_UNZIP_DIR + File.separator
                        + entry.getName());
            }

            zipFile.close();
        } catch (IOException e) {
            deleteDir(new File(destination));
            LOGGER.error(e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    } else {
        LOGGER.info("There is already a file by that name");
    }
    return destLs;
}

From source file:bammerbom.ultimatecore.bukkit.UltimateUpdater.java

/**
 * Part of Zip-File-Extractor, modified by Gravity for use with Updater.
 *
 * @param file the location of the file to extract.
 *///from  ww  w  . j a va 2s. co m
private void unzip(String file) {
    final File fSourceZip = new File(file);
    try {
        final String zipPath = file.substring(0, file.length() - 4);
        ZipFile zipFile = new ZipFile(fSourceZip);
        Enumeration<? extends ZipEntry> e = zipFile.entries();
        while (e.hasMoreElements()) {
            ZipEntry entry = e.nextElement();
            File destinationFilePath = new File(zipPath, entry.getName());
            destinationFilePath.getParentFile().mkdirs();
            if (!entry.isDirectory()) {
                final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
                int b;
                final byte[] buffer = new byte[UltimateUpdater.BYTE_SIZE];
                final FileOutputStream fos = new FileOutputStream(destinationFilePath);
                final BufferedOutputStream bos = new BufferedOutputStream(fos, UltimateUpdater.BYTE_SIZE);
                while ((b = bis.read(buffer, 0, UltimateUpdater.BYTE_SIZE)) != -1) {
                    bos.write(buffer, 0, b);
                }
                bos.flush();
                bos.close();
                bis.close();
                final String name = destinationFilePath.getName();
                if (name.endsWith(".jar") && this.pluginExists(name)) {
                    File output = new File(updateFolder, name);
                    destinationFilePath.renameTo(output);
                }
            }
        }
        zipFile.close();

        // Move any plugin data folders that were included to the right place, Bukkit won't do this for us.
        moveNewZipFiles(zipPath);

    } catch (final IOException e) {
    } finally {
        fSourceZip.delete();
    }
}

From source file:org.broad.igv.feature.genome.GenomeManager.java

/**
 * Creates a genome descriptor.// w w  w .  j  a v  a2s  .com
 */
public static GenomeDescriptor parseGenomeArchiveFile(File f) throws IOException {

    if (!f.exists()) {
        throw new FileNotFoundException("Genome file: " + f.getAbsolutePath() + " does not exist.");
    }

    GenomeDescriptor genomeDescriptor = null;
    Map<String, ZipEntry> zipEntries = new HashMap();
    ZipFile zipFile = new ZipFile(f);

    FileInputStream fileInputStream = null;
    try {
        fileInputStream = new FileInputStream(f);
        ZipInputStream zipInputStream = new ZipInputStream(fileInputStream);
        ZipEntry zipEntry = zipInputStream.getNextEntry();

        while (zipEntry != null) {
            String zipEntryName = zipEntry.getName();
            zipEntries.put(zipEntryName, zipEntry);

            if (zipEntryName.equalsIgnoreCase(Globals.GENOME_ARCHIVE_PROPERTY_FILE_NAME)) {
                InputStream inputStream = zipFile.getInputStream(zipEntry);
                Properties properties = new Properties();
                properties.load(inputStream);

                String cytobandZipEntryName = properties.getProperty(Globals.GENOME_ARCHIVE_CYTOBAND_FILE_KEY);
                String geneFileName = properties.getProperty(Globals.GENOME_ARCHIVE_GENE_FILE_KEY);
                String chrAliasFileName = properties.getProperty(Globals.GENOME_CHR_ALIAS_FILE_KEY);
                String sequenceLocation = properties
                        .getProperty(Globals.GENOME_ARCHIVE_SEQUENCE_FILE_LOCATION_KEY);

                if ((sequenceLocation != null) && !HttpUtils.isRemoteURL(sequenceLocation)) {
                    File sequenceFolder = null;
                    // Relative or absolute location? We use a few redundant methods to check,
                    //since we don't know what platform the file was created on or is running on
                    sequenceFolder = new File(sequenceLocation);
                    boolean isAbsolutePath = sequenceFolder.isAbsolute() || sequenceLocation.startsWith("/")
                            || sequenceLocation.startsWith("\\");
                    if (!isAbsolutePath) {
                        sequenceFolder = new File(f.getParent(), sequenceLocation);
                    }
                    sequenceLocation = sequenceFolder.getCanonicalPath();
                    sequenceLocation.replace('\\', '/');
                }

                boolean chrNamesAltered = parseBooleanPropertySafe(properties, "filenamesAltered");
                boolean fasta = parseBooleanPropertySafe(properties, "fasta");
                boolean fastaDirectory = parseBooleanPropertySafe(properties, "fastaDirectory");
                boolean chromosomesAreOrdered = parseBooleanPropertySafe(properties,
                        Globals.GENOME_ORDERED_KEY);
                boolean hasCustomSequenceLocation = parseBooleanPropertySafe(properties,
                        Globals.GENOME_ARCHIVE_CUSTOM_SEQUENCE_LOCATION_KEY);

                String fastaFileNameString = properties.getProperty("fastaFiles");
                String url = properties.getProperty(Globals.GENOME_URL_KEY);

                // The new descriptor
                genomeDescriptor = new GenomeZipDescriptor(
                        properties.getProperty(Globals.GENOME_ARCHIVE_NAME_KEY), chrNamesAltered,
                        properties.getProperty(Globals.GENOME_ARCHIVE_ID_KEY), cytobandZipEntryName,
                        geneFileName, chrAliasFileName,
                        properties.getProperty(Globals.GENOME_GENETRACK_NAME, "Gene"), sequenceLocation,
                        hasCustomSequenceLocation, zipFile, zipEntries, chromosomesAreOrdered, fasta,
                        fastaDirectory, fastaFileNameString);

                if (url != null) {
                    genomeDescriptor.setUrl(url);
                }

            }
            zipEntry = zipInputStream.getNextEntry();
        }
    } finally {
        try {
            if (fileInputStream != null) {
                fileInputStream.close();
            }
        } catch (IOException ex) {
            log.warn("Error closing imported genome zip stream!", ex);
        }
    }
    return genomeDescriptor;
}

From source file:org.apache.taverna.scufl2.ucfpackage.TestUCFPackage.java

@Test
public void workflowBundleMimeType() throws Exception {
    UCFPackage container = new UCFPackage();
    container.setPackageMediaType(UCFPackage.MIME_WORKFLOW_BUNDLE);
    assertEquals(UCFPackage.MIME_WORKFLOW_BUNDLE, container.getPackageMediaType());
    container.save(tmpFile);//from w w  w.j  av a2s. com
    ZipFile zipFile = new ZipFile(tmpFile);
    ZipEntry mimeEntry = zipFile.getEntry("mimetype");
    assertEquals("mimetype", mimeEntry.getName());
    assertEquals("Wrong mimetype", UCFPackage.MIME_WORKFLOW_BUNDLE,
            IOUtils.toString(zipFile.getInputStream(mimeEntry), "ASCII"));

}

From source file:org.jboss.tools.project.examples.ProjectExamplesActivator.java

public static boolean extractZipFile(File file, File destination, IProgressMonitor monitor) {
    ZipFile zipFile = null;
    destination.mkdirs();//from w w w .j  a v  a 2  s. c  o  m
    try {
        zipFile = new ZipFile(file);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            if (monitor.isCanceled()) {
                return false;
            }
            ZipEntry entry = (ZipEntry) entries.nextElement();
            if (entry.isDirectory()) {
                monitor.setTaskName("Extracting " + entry.getName());
                File dir = new File(destination, entry.getName());
                dir.mkdirs();
                continue;
            }
            monitor.setTaskName("Extracting " + entry.getName());
            File entryFile = new File(destination, entry.getName());
            entryFile.getParentFile().mkdirs();
            InputStream in = null;
            OutputStream out = null;
            try {
                in = zipFile.getInputStream(entry);
                out = new FileOutputStream(entryFile);
                copy(in, out);
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (Exception e) {
                        // ignore
                    }
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (Exception e) {
                        // ignore
                    }
                }
            }
        }
    } catch (IOException e) {
        ProjectExamplesActivator.log(e);
        return false;
    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
    return true;
}

From source file:org.guvnor.m2repo.backend.server.GuvnorM2Repository.java

private String loadGAVFromJarInternal(final File file) {
    InputStream is = null;/*from w ww . ja  v a 2 s .  c o m*/
    InputStreamReader isr = null;
    try {
        ZipFile zip = new ZipFile(file);

        for (Enumeration e = zip.entries(); e.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) e.nextElement();

            if (entry.getName().startsWith("META-INF/maven") && entry.getName().endsWith("pom.properties")) {
                is = zip.getInputStream(entry);
                isr = new InputStreamReader(is, "UTF-8");
                StringBuilder sb = new StringBuilder();
                for (int c = isr.read(); c != -1; c = isr.read()) {
                    sb.append((char) c);
                }
                return sb.toString();
            }
        }
    } catch (ZipException e) {
        log.error(e.getMessage());
    } catch (IOException e) {
        log.error(e.getMessage());
    } finally {
        if (isr != null) {
            try {
                isr.close();
            } catch (IOException e) {
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
    }

    return null;
}