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.sead.repositories.reference.RefRepository.java

protected static void createMap(File map, String path, String bagNameRoot) {
    ZipFile zf = null;
    try {//from   w  w w.j a v a  2  s .c o  m
        log.info("Caching oremap: " + map.getPath());
        // Note: This step can be VERY slow when something is being
        // published on the same disk - minutes for a large file
        // If you don't see the "Zipfile opened" message in the log,
        // look at disk I/O...
        File result = new File(path, bagNameRoot + ".zip");
        zf = new ZipFile(result);
        log.debug("Zipfile opened");
        ZipEntry archiveEntry1 = zf.getEntry(bagNameRoot + "/oremap.jsonld.txt");
        InputStream source = zf.getInputStream(archiveEntry1);
        OutputStream sink = new FileOutputStream(map);
        IOUtils.copy(source, sink);
        IOUtils.closeQuietly(source);
        IOUtils.closeQuietly(sink);
        log.debug("ORE Map written: " + result.getCanonicalPath());
    } catch (Exception e) {
        log.error("Cannot read zipfile to create cached oremap: " + map.getPath(), e);
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(zf);
    }
}

From source file:abfab3d.io.input.STSReader.java

/**
 * Load a STS file into a grid.//from   w  w w.  j  av a  2  s .  co m
 *
 * @param file The zip file
 * @return
 * @throws java.io.IOException
 */
public TriangleMesh[] loadMeshes(String file) throws IOException {
    ZipFile zip = null;
    TriangleMesh[] ret_val = null;

    try {
        zip = new ZipFile(file);

        ZipEntry entry = zip.getEntry("manifest.xml");
        if (entry == null) {
            throw new IOException("Cannot find manifest.xml in top level");
        }

        InputStream is = zip.getInputStream(entry);
        mf = parseManifest(is);

        if (mf == null) {
            throw new IOException("Could not parse manifest file");
        }

        List<STSPart> plist = mf.getParts();
        int len = plist.size();

        ret_val = new TriangleMesh[len];
        for (int i = 0; i < len; i++) {
            STSPart part = plist.get(i);
            ZipEntry ze = zip.getEntry(part.getFile());
            MeshReader reader = new MeshReader(zip.getInputStream(ze), "",
                    FilenameUtils.getExtension(part.getFile()));
            IndexedTriangleSetBuilder its = new IndexedTriangleSetBuilder();
            reader.getTriangles(its);

            // TODO: in this case we could return a less heavy triangle mesh struct?
            WingedEdgeTriangleMesh mesh = new WingedEdgeTriangleMesh(its.getVertices(), its.getFaces());
            ret_val[i] = mesh;
        }

        return ret_val;
    } finally {
        if (zip != null)
            zip.close();
    }
}

From source file:net.sf.sripathi.ws.mock.util.FileUtil.java

public static void createFilesAndFolder(String root, ZipFile zip) {

    @SuppressWarnings("unchecked")
    Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip.entries();
    Set<String> files = new TreeSet<String>();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();

        if (entry.getName().toLowerCase().endsWith(".wsdl") || entry.getName().toLowerCase().endsWith(".xsd"))
            files.add(entry.getName());/*from   ww w. j  a  va 2 s  . c om*/
    }

    File rootFolder = new File(root);
    if (!rootFolder.exists()) {
        throw new MockException("Unable to create file - " + root);
    }

    for (String fileStr : files) {

        String folder = root;

        String[] split = fileStr.split("/");

        if (split.length > 1) {

            for (int i = 0; i < split.length - 1; i++) {

                folder = folder + "/" + split[i];
                File f = new File(folder);
                if (!f.exists()) {
                    f.mkdir();
                }
            }
        }

        File file = new File(folder + "/" + split[split.length - 1]);
        FileOutputStream fos = null;
        InputStream zipStream = null;
        try {
            fos = new FileOutputStream(file);
            zipStream = zip.getInputStream(zip.getEntry(fileStr));
            fos.write(IOUtils.toByteArray(zipStream));
        } catch (Exception e) {
            throw new MockException("Unable to create file - " + fileStr);
        } finally {
            try {
                fos.close();
            } catch (Exception e) {
            }
            try {
                zipStream.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:org.nebulaframework.deployment.classloading.GridArchiveClassLoader.java

/**
 * Internal method which does the search for class inside
 * the {@code GridArchive}. First attempts locate the file directly in 
 * the {@code .nar} file. If this fails, it then looks in the 
 * {@code .jar} libraries available in the {@code .nar}
 * file, and attempts to locate the class inside each of the {@code .jar}
 * file./*from  w w w.j  a  v a2 s. co m*/
 * 
 * @param fileName expected filename of Class file to be loaded
 * 
 * @return the {@code byte[]} for the class file
 * 
 * @throws IOException if IO errors occur during operation
 * @throws ClassNotFoundException if unable to locate the class
 */
protected byte[] findInArchive(String fileName) throws IOException, ClassNotFoundException {

    ZipFile archive = new ZipFile(archiveFile);

    ZipEntry entry = archive.getEntry(fileName);

    if (entry == null) { // Unable to find file in archive
        try {
            // Attempt to look in libraries
            Enumeration<? extends ZipEntry> enumeration = archive.entries();
            while (enumeration.hasMoreElements()) {
                ZipEntry zipEntry = enumeration.nextElement();
                if (zipEntry.getName().contains(GridArchive.NEBULA_INF)
                        && zipEntry.getName().endsWith(".jar")) {

                    // Look in Jar File
                    byte[] bytes = findInJarStream(archive.getInputStream(zipEntry), fileName);

                    // If Found
                    if (bytes != null) {
                        log.debug("[GridArchiveClassLoader] found class in JAR Library " + fileName);
                        return bytes;
                    }
                }
            }
        } catch (Exception e) {
            log.warn("[[GridArchiveClassLoader] Exception " + "while attempting class loading", e);
        }

        // Cannot Find Class
        throw new ClassNotFoundException("No such file as " + fileName);

    } else { // Entry not null, Found Class
        log.debug("[GridArchiveClassLoader] found class at " + fileName);

        // Get byte[] and return
        return IOSupport.readBytes(archive.getInputStream(entry));
    }
}

From source file:org.openflexo.toolbox.ZipUtils.java

public static final void unzip(File zip, File outputDir, IProgress progress) throws ZipException, IOException {
    Enumeration<? extends ZipEntry> entries;
    outputDir = outputDir.getCanonicalFile();
    if (!outputDir.exists()) {
        boolean b = outputDir.mkdirs();
        if (!b) {
            throw new IllegalArgumentException("Could not create dir " + outputDir.getAbsolutePath());
        }/*from   w  ww. ja v a 2  s  . co  m*/
    }
    if (!outputDir.isDirectory()) {
        throw new IllegalArgumentException(
                outputDir.getAbsolutePath() + "is not a directory or is not writeable!");
    }
    ZipFile zipFile;
    zipFile = new ZipFile(zip);
    entries = zipFile.entries();
    if (progress != null) {
        progress.resetSecondaryProgress(zipFile.size());
    }
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        if (progress != null) {
            progress.setSecondaryProgress(
                    FlexoLocalization.localizedForKey("unzipping") + " " + entry.getName());
        }
        if (entry.getName().startsWith("__MACOSX")) {
            continue;
        }
        if (entry.isDirectory()) {
            // Assume directories are stored parents first then
            // children.
            // This is not robust, just for demonstration purposes.
            new File(outputDir, entry.getName().replace('\\', '/')).mkdirs();
            continue;
        }
        File outputFile = new File(outputDir, entry.getName().replace('\\', '/'));
        if (outputFile.getName().startsWith("._")) {
            // This block is made to drop MacOS crap added to zip files
            if (zipFile.getEntry(
                    entry.getName().substring(0, entry.getName().length() - outputFile.getName().length())
                            + outputFile.getName().substring(2)) != null) {
                continue;
            }
            if (new File(outputFile.getParentFile(), outputFile.getName().substring(2)).exists()) {
                continue;
            }
        }
        FileUtils.createNewFile(outputFile);
        InputStream zipStream = null;
        FileOutputStream fos = null;
        try {
            zipStream = zipFile.getInputStream(entry);
            if (zipStream == null) {
                System.err.println("Could not find input stream for entry: " + entry.getName());
                continue;
            }
            fos = new FileOutputStream(outputFile);
            copyInputStream(zipStream, new BufferedOutputStream(fos));
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("Could not extract: " + outputFile.getAbsolutePath()
                    + " maybe some files contains invalid characters.");
        } finally {
            IOUtils.closeQuietly(zipStream);
            IOUtils.closeQuietly(fos);
        }
    }
    Collection<File> listFiles = org.apache.commons.io.FileUtils.listFiles(outputDir, null, true);
    for (File file : listFiles) {
        if (file.isFile() && file.getName().startsWith("._")) {
            File f = new File(file.getParentFile(), file.getName().substring(2));
            if (f.exists()) {
                file.delete();
            }
        }
    }
    zipFile.close();
}

From source file:mobac.mapsources.loader.MapPackManager.java

public int getMapPackRevision(File mapPackFile) throws ZipException, IOException {
    ZipFile zip = new ZipFile(mapPackFile);
    try {/*from  w w  w  .j a  v a  2s.com*/
        ZipEntry entry = zip.getEntry("META-INF/MANIFEST.MF");
        if (entry == null)
            throw new ZipException("Unable to find MANIFEST.MF");
        Manifest mf = new Manifest(zip.getInputStream(entry));
        Attributes a = mf.getMainAttributes();
        String mpv = a.getValue("MapPackRevision").trim();
        return Utilities.parseSVNRevision(mpv);
    } catch (NumberFormatException e) {
        return -1;
    } finally {
        zip.close();
    }
}

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 {//from w w w.  ja va  2 s.  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:it.readbeyond.minstrel.librarian.FormatHandlerEPUB.java

public Publication parseFile(File file) {
    Publication p = super.parseFile(file);
    Format format = new Format(EPUB_FORMAT);
    pathThumbnailSourceRelativeToOPF = null;
    coverManifestItemID = null;/*from  w  ww . ja  v a  2 s  .  c  o  m*/

    String OPFPath = this.getOPFPath(file);
    if (OPFPath != null) {
        try {
            ZipFile zipFile = new ZipFile(file, ZipFile.OPEN_READ);
            ZipEntry OPFEntry = zipFile.getEntry(OPFPath);
            if (OPFEntry != null) {

                InputStream is;

                // first pass: parse metadata
                is = zipFile.getInputStream(OPFEntry);
                parser = Xml.newPullParser();
                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
                parser.setInput(is, null);
                parser.nextTag();
                this.parsePackage(format, 1);
                is.close();

                // second pass: parse manifest
                is = zipFile.getInputStream(OPFEntry);
                parser = Xml.newPullParser();
                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
                parser.setInput(is, null);
                parser.nextTag();
                this.parsePackage(format, 2);
                is.close();

                // item is valid
                p.isValid(true);

                // set the cover path, relative to the EPUB container (aka ZIP) root
                if (pathThumbnailSourceRelativeToOPF != null) {
                    // concatenate OPFPath parent directory and pathThumbnailSourceRelativeToOPF
                    File tmp = new File(new File(OPFPath).getParent(), pathThumbnailSourceRelativeToOPF);
                    // remove leading "/"
                    format.addMetadatum("internalPathCover", tmp.getAbsolutePath().substring(1));
                }

            }
            zipFile.close();
        } catch (Exception e) {
            // invalidate item, so it will not be added to library
            p.isValid(false);
        }
    }

    p.addFormat(format);

    // extract cover
    super.extractCover(file, format, p.getID());

    return p;
}

From source file:at.alladin.rmbt.android.about.RMBTAboutFragment.java

/**
 * /*from ww w  .  j  av a2s . c  o  m*/
 * @param context
 * @return
 */
private String getAppInfo(final Context context) {
    PackageInfo pInfo;
    try {

        String date = "";
        try {
            final ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(),
                    0);
            final ZipFile zf = new ZipFile(ai.sourceDir);
            final ZipEntry ze = zf.getEntry("classes.dex");
            zf.close();
            final long time = ze.getTime();
            date = DateFormat.getDateTimeInstance().format(new java.util.Date(time));

        } catch (final Exception e) {// not much we can do
        }

        pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        clientVersion = pInfo.versionName + " (" + pInfo.versionCode + ")\n("
                + RevisionHelper.getVerboseRevision() + ")\n(" + date + ")";
        clientName = context.getResources().getString(R.string.app_name);
    } catch (final Exception e) {
        // e1.printStackTrace();
        Log.e(DEBUG_TAG, "version of the application cannot be found", e);
    }

    return clientVersion;
}

From source file:org.digidoc4j.ContainerBuilderTest.java

@Test
public void signAndSaveContainerToFile() throws Exception {
    Container container = TestDataBuilder.createContainerWithFile(testFolder);
    TestDataBuilder.signContainer(container);
    assertEquals(1, container.getSignatures().size());
    String filePath = testFolder.newFile("test-container.bdoc").getPath();
    File file = container.saveAsFile(filePath);
    assertTrue(FileUtils.sizeOf(file) > 0);
    ZipFile zip = new ZipFile(filePath);
    assertNotNull(zip.getEntry("META-INF/signatures0.xml"));
}