Example usage for java.util.zip ZipFile getEntry

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

Introduction

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

Prototype

public ZipEntry getEntry(String name) 

Source Link

Document

Returns the zip file entry for the specified name, or null if not found.

Usage

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

@Test
public void removeResource() throws Exception {
    UCFPackage container = new UCFPackage();
    container.setPackageMediaType(UCFPackage.MIME_WORKFLOW_BUNDLE);

    container.addResource("Soup for everyone", "soup.txt", "text/plain");

    container.addResource("Sub-folder entry 1", "sub/1.txt", "text/plain");
    container.addResource("Sub-folder entry 2", "sub/2.txt", "text/plain");
    container.addResource("Sub-folder entry 2", "sub/3/woho.txt", "text/plain");

    assertTrue(container.listAllResources().keySet().contains("soup.txt"));
    container.removeResource("soup.txt");
    assertFalse(container.listAllResources().keySet().contains("soup.txt"));

    try {/*from  w  w  w . ja va 2s  .co  m*/
        container.getResourceAsString("soup.txt");
        fail("Could still retrieve soup.txt");
    } catch (Exception ex) {
        // OK
    }

    container.save(tmpFile);
    // reload
    UCFPackage container2 = new UCFPackage(tmpFile);

    assertTrue(container2.listAllResources().keySet().contains("sub/"));
    container2.removeResource("sub"); // should not work
    assertTrue(container2.listAllResources().keySet().contains("sub/"));
    assertTrue(container2.listAllResources().keySet().contains("sub/1.txt"));

    container2.removeResource("sub/");
    assertFalse(container2.listAllResources().keySet().contains("sub/"));
    assertFalse(container2.listAllResources().keySet().contains("sub/1.txt"));

    container2.save(tmpFile);

    ZipFile zipFile = new ZipFile(tmpFile);
    assertNull("soup.txt still in zip file", zipFile.getEntry("soup.txt"));
    assertNull("sub/1.txt still in zip file", zipFile.getEntry("sub/1.txt"));
    assertNull("sub/2.txt still in zip file", zipFile.getEntry("sub/2.txt"));
    assertNull("sub/3.txt still in zip file", zipFile.getEntry("sub/3.txt"));
    assertNull("sub/ still in zip file", zipFile.getEntry("sub/"));
    zipFile.close();

    UCFPackage loaded = new UCFPackage(tmpFile);
    assertFalse(loaded.listAllResources().keySet().contains("soup.txt"));
    assertFalse(loaded.listAllResources().keySet().contains("sub/"));
    assertFalse(loaded.listAllResources().keySet().contains("sub/1.txt"));

    try {
        loaded.getResourceAsString("sub/1.txt");
        fail("Could still retrieve soup.txt");
    } catch (Exception ex) {
        // OK
    }
    loaded.save(tmpFile);
}

From source file:org.zeroturnaround.zip.ZipsTest.java

public void testPreservingTimestamps() throws IOException {
    File src = new File(MainExamplesTest.DEMO_ZIP);

    File dest = File.createTempFile("temp", ".zip");
    final ZipFile zf = new ZipFile(src);
    try {/*from   www .ja v a 2  s . c  o  m*/
        Zips.get(src).addEntries(new ZipEntrySource[0]).preserveTimestamps().destination(dest).process();
        Zips.get(dest).iterate(new ZipEntryCallback() {
            public void process(InputStream in, ZipEntry zipEntry) throws IOException {
                String name = zipEntry.getName();
                assertEquals("Timestapms differ at entry " + name, zf.getEntry(name).getTime(),
                        zipEntry.getTime());
            }
        });
    } finally {
        ZipUtil.closeQuietly(zf);
        FileUtils.deleteQuietly(dest);
    }
}

From source file:org.zeroturnaround.zip.ZipsTest.java

public void testPreservingTimestampsSetter() throws IOException {
    File src = new File(MainExamplesTest.DEMO_ZIP);

    File dest = File.createTempFile("temp", ".zip");
    final ZipFile zf = new ZipFile(src);
    try {// w  w  w .j av a2 s .  com
        Zips.get(src).addEntries(new ZipEntrySource[0]).setPreserveTimestamps(true).destination(dest).process();
        Zips.get(dest).iterate(new ZipEntryCallback() {
            public void process(InputStream in, ZipEntry zipEntry) throws IOException {
                String name = zipEntry.getName();
                assertEquals("Timestapms differ at entry " + name, zf.getEntry(name).getTime(),
                        zipEntry.getTime());
            }
        });
    } finally {
        ZipUtil.closeQuietly(zf);
        FileUtils.deleteQuietly(dest);
    }
}

From source file:com.hichinaschool.flashcards.libanki.Media.java

/**
 * Extract zip data.//from w w w . j a  va 2  s .  c o m
 * 
 * @param zipData An input stream that represents a zipped file.
 * @return True if finished.
 */
public boolean syncAdd(File zipData) {
    boolean finished = false;
    ZipFile z = null;
    ArrayList<Object[]> media = new ArrayList<Object[]>();
    long sizecnt = 0;
    JSONObject meta = null;
    int nextUsn = 0;
    try {
        z = new ZipFile(zipData, ZipFile.OPEN_READ);
        // get meta info first
        ZipEntry metaEntry = z.getEntry("_meta");
        // if (metaEntry.getSize() >= 100000) {
        // Log.e(AnkiDroidApp.TAG, "Size for _meta entry found too big (" + z.getEntry("_meta").getSize() + ")");
        // return false;
        // }
        meta = new JSONObject(Utils.convertStreamToString(z.getInputStream(metaEntry)));
        ZipEntry usnEntry = z.getEntry("_usn");
        String usnstr = Utils.convertStreamToString(z.getInputStream(usnEntry));
        nextUsn = Integer.parseInt(usnstr);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } catch (ZipException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    // Then loop through all files
    for (ZipEntry zentry : Collections.list(z.entries())) {
        // Check for zip bombs
        sizecnt += zentry.getSize();
        if (sizecnt > 100 * 1024 * 1024) {
            Log.e(AnkiDroidApp.TAG, "Media zip file exceeds 100MB uncompressed, aborting unzipping");
            return false;
        }
        if (zentry.getName().compareTo("_meta") == 0 || zentry.getName().compareTo("_usn") == 0) {
            // Ignore previously retrieved meta
            continue;
        } else if (zentry.getName().compareTo("_finished") == 0) {
            finished = true;
        } else {
            String name = meta.optString(zentry.getName());
            if (illegal(name)) {
                continue;
            }
            String path = getDir().concat(File.separator).concat(name);
            try {
                Utils.writeToFile(z.getInputStream(zentry), path);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            String csum = Utils.fileChecksum(path);
            // append db
            media.add(new Object[] { name, csum, _mtime(name) });
            mMediaDb.execute("delete from log where fname = ?", new String[] { name });
        }
    }

    // update media db and note new starting usn
    if (!media.isEmpty()) {
        mMediaDb.executeMany("insert or replace into media values (?,?,?)", media);
    }
    setUsn(nextUsn); // commits
    // if we have finished adding, we need to record the new folder mtime
    // so that we don't trigger a needless scan
    if (finished) {
        syncMod();
    }
    return finished;
}

From source file:com.gelakinetic.selfr.CameraActivity.java

/**
 * Helper function to return the build date of this APK
 *
 * @return A build date for this APK, or null if it could not be determined
 *//*from ww  w  .j a  va  2s .  c  o  m*/
private String getBuildDate() {
    try {
        ApplicationInfo ai = getPackageManager().getApplicationInfo(getPackageName(), 0);
        ZipFile zf = new ZipFile(ai.sourceDir);
        ZipEntry ze = zf.getEntry("classes.dex");
        long time = ze.getTime();
        String s = SimpleDateFormat.getInstance().format(new java.util.Date(time));
        zf.close();
        return s;
    } catch (Exception e) {
        return null;
    }
}

From source file:org.apache.maven.archetype.common.DefaultArchetypeArtifactManager.java

public Model getArchetypePom(File jar) throws XmlPullParserException, UnknownArchetype, IOException {
    ZipFile zipFile = null;
    try {//from   www  .  j av  a 2  s. c  om
        String pomFileName = null;
        zipFile = getArchetypeZipFile(jar);

        Enumeration<? extends ZipEntry> enumeration = zipFile.entries();
        while (enumeration.hasMoreElements()) {
            ZipEntry el = (ZipEntry) enumeration.nextElement();

            String entry = el.getName();
            if (entry.startsWith("META-INF") && entry.endsWith("pom.xml")) {
                pomFileName = entry;
            }
        }

        if (pomFileName == null) {
            return null;
        }

        ZipEntry pom = zipFile.getEntry(pomFileName);

        if (pom == null) {
            return null;
        }
        return pomManager.readPom(zipFile.getInputStream(pom));
    } finally {
        closeZipFile(zipFile);
    }
}

From source file:org.ambraproject.article.service.XslIngestArchiveProcessor.java

/**
 * Helper method to extract XML from the zip file
 *
 * @param zipFile  - the zip file containing the file to extract
 * @param fileName - the file to extract
 * @return - the parsed xml file/*w w  w .j  a va  2 s  .  c  om*/
 * @throws java.io.IOException      - if there's a problem reading from the zip file
 * @throws org.xml.sax.SAXException - if there's a problem parsing the xml
 */
private Document extractXml(ZipFile zipFile, String fileName) throws IOException, SAXException {
    InputStream inputStream = null;
    try {
        inputStream = zipFile.getInputStream(zipFile.getEntry(fileName));
        return documentBuilder.parse(inputStream);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                log.warn("Error closing zip input stream during ingest processing", e);
            }
        }
    }
}

From source file:org.apache.maven.doxia.siterenderer.DefaultSiteRenderer.java

/** {@inheritDoc} */
public SiteRenderingContext createContextForSkin(Artifact skin, Map<String, ?> attributes,
        DecorationModel decoration, String defaultWindowTitle, Locale locale)
        throws IOException, RendererException {
    SiteRenderingContext context = createSiteRenderingContext(attributes, decoration, defaultWindowTitle,
            locale);/*from   w ww .j  a  v a 2  s  . c o m*/

    context.setSkin(skin);

    ZipFile zipFile = getZipFile(skin.getFile());
    InputStream in = null;

    try {
        if (zipFile.getEntry(SKIN_TEMPLATE_LOCATION) != null) {
            context.setTemplateName(SKIN_TEMPLATE_LOCATION);
            context.setTemplateClassLoader(new URLClassLoader(new URL[] { skin.getFile().toURI().toURL() }));
        } else {
            context.setTemplateName(DEFAULT_TEMPLATE);
            context.setTemplateClassLoader(getClass().getClassLoader());
            context.setUsingDefaultTemplate(true);
        }

        ZipEntry skinDescriptorEntry = zipFile.getEntry(SkinModel.SKIN_DESCRIPTOR_LOCATION);
        if (skinDescriptorEntry != null) {
            in = zipFile.getInputStream(skinDescriptorEntry);

            SkinModel skinModel = new SkinXpp3Reader().read(in);
            context.setSkinModel(skinModel);

            String toolsPrerequisite = skinModel.getPrerequisites() == null ? null
                    : skinModel.getPrerequisites().getDoxiaSitetools();

            Package p = DefaultSiteRenderer.class.getPackage();
            String current = (p == null) ? null : p.getImplementationVersion();

            if (StringUtils.isNotBlank(toolsPrerequisite) && (current != null)
                    && !matchVersion(current, toolsPrerequisite)) {
                throw new RendererException("Cannot use skin: has " + toolsPrerequisite
                        + " Doxia Sitetools prerequisite, but current is " + current);
            }
        }
    } catch (XmlPullParserException e) {
        throw new RendererException("Failed to parse " + SkinModel.SKIN_DESCRIPTOR_LOCATION
                + " skin descriptor from " + skin.getId() + " skin", e);
    } finally {
        IOUtil.close(in);
        closeZipFile(zipFile);
    }

    return context;
}

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.
 *///from w w  w  . j a  v a2s.  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.zeroturnaround.zip.ZipsTest.java

public void testOverwritingTimestamps() throws IOException {
    File src = new File(MainExamplesTest.DEMO_ZIP);

    File dest = File.createTempFile("temp", ".zip");
    final ZipFile zf = new ZipFile(src);
    try {//from  www.j a v  a  2 s.  c om
        Zips.get(src).addEntries(new ZipEntrySource[0]).destination(dest).process();
        Zips.get(dest).iterate(new ZipEntryCallback() {
            public void process(InputStream in, ZipEntry zipEntry) throws IOException {
                String name = zipEntry.getName();
                // original timestamp is believed to be earlier than test execution time.
                assertTrue("Timestapms were carried over for entry " + name,
                        zf.getEntry(name).getTime() < zipEntry.getTime());
            }
        });
    } finally {
        ZipUtil.closeQuietly(zf);
        FileUtils.deleteQuietly(dest);
    }
}