Example usage for java.util.zip ZipFile entries

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

Introduction

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

Prototype

public Enumeration<? extends ZipEntry> entries() 

Source Link

Document

Returns an enumeration of the ZIP file entries.

Usage

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);
    }//from w w w  .  j  a va2s. co 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:org.esa.s1tbx.sentinel1.gpf.EAPPhaseCorrectionOp.java

private void readAuxCalFile() throws Exception {

    try {/*from  w  w  w.ja  va2s. c o  m*/
        final DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
        final DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();

        final Document doc;
        if (auxCalFile.getName().toLowerCase().endsWith(".zip")) {
            final ZipFile productZip = new ZipFile(auxCalFile, ZipFile.OPEN_READ);
            final Enumeration<? extends ZipEntry> entries = productZip.entries();
            final ZipEntry folderEntry = entries.nextElement();
            final ZipEntry zipEntry = productZip.getEntry(folderEntry.getName() + "data/s1a-aux-cal.xml");

            InputStream is = productZip.getInputStream(zipEntry);
            doc = documentBuilder.parse(is);
        } else {
            doc = documentBuilder.parse(auxCalFile);
        }

        if (doc == null) {
            System.out.println("EAPPhaseCorrection: failed to create Document for AUX_CAL file");
            return;
        }

        doc.getDocumentElement().normalize();

        final org.w3c.dom.Node calibrationParamsListNode = doc.getElementsByTagName("auxiliaryCalibration")
                .item(0).getChildNodes().item(1);

        org.w3c.dom.Node childNode = calibrationParamsListNode.getFirstChild();
        while (childNode != null) {
            if (childNode.getNodeName().equals("calibrationParams")) {
                final String swath = getNodeTextContent(childNode, "swath");
                if (swath != null && swath.contains(acquisitionMode)) {
                    final String pol = getNodeTextContent(childNode, "polarisation");
                    readOneEAPVector(childNode, swath, pol.toUpperCase());
                }
            }
            childNode = childNode.getNextSibling();
        }

    } catch (IOException e) {
        System.out.println("EAPPhaseCorrection: IOException " + e.getMessage());
    } catch (ParserConfigurationException e) {
        System.out.println("EAPPhaseCorrection: ParserConfigurationException " + e.getMessage());
    } catch (SAXException e) {
        System.out.println("EAPPhaseCorrection: SAXException " + e.getMessage());
    } catch (Exception e) {
        System.out.println("EAPPhaseCorrection: Exception " + e.getMessage());
    }
}

From source file:org.jumpmind.metl.core.runtime.component.UnZip.java

@Override
public void handle(Message inputMessage, ISendMessageCallback callback, boolean unitOfWorkBoundaryReached) {
    if (inputMessage instanceof TextMessage) {
        List<String> files = ((TextMessage) inputMessage).getPayload();
        ArrayList<String> filePaths = new ArrayList<String>();
        for (String fileName : files) {
            log(LogLevel.INFO, "Preparing to extract file : %s", fileName);
            FileInfo sourceZipFile = sourceDir.listFile(fileName);
            if (mustExist && sourceZipFile == null) {
                throw new IoException(String.format("Could not find file to extract: %s", fileName));
            }//from  ww w.j  a v  a 2  s  . com
            if (sourceZipFile != null) {
                File unzipDir = new File(LogUtils.getLogDir(), "unzip");
                unzipDir.mkdirs();

                File localZipFile = copyZipLocally(fileName, unzipDir);
                ZipFile zipFile = getNewZipFile(localZipFile);
                InputStream in = null;
                OutputStream out = null;
                try {
                    String targetDirNameResolved = resolveParamsAndHeaders(targetRelativePath, inputMessage);
                    if (targetSubDir) {
                        targetDirNameResolved = targetDirNameResolved + "/"
                                + FilenameUtils.removeExtension(new FileInfo(fileName, false, 0, 0).getName());
                    }
                    for (Enumeration<? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements();) {
                        ZipEntry entry = e.nextElement();
                        if (!entry.isDirectory() && (extractEmptyFiles || entry.getSize() > 0)) {
                            String relativePathToEntry = targetDirNameResolved + "/" + entry.getName();
                            if (overwrite || targetDir.listFile(relativePathToEntry) == null) {
                                info("Unzipping %s", entry.getName());
                                out = targetDir.getOutputStream(relativePathToEntry, false);
                                in = zipFile.getInputStream(entry);
                                IOUtils.copy(in, out);
                                filePaths.add(relativePathToEntry);
                            } else if (!overwrite) {
                                info("Not unzipping %s.  It already exists and the override property is not enabled",
                                        entry.getName());
                            }
                        }
                    }
                } catch (IOException e) {
                    throw new IoException(e);
                } finally {
                    IOUtils.closeQuietly(in);
                    IOUtils.closeQuietly(out);
                    IOUtils.closeQuietly(zipFile);
                    FileUtils.deleteQuietly(localZipFile);
                }
                if (deleteOnComplete) {
                    sourceDir.delete(fileName);
                }

                log(LogLevel.INFO, "Extracted %s", fileName);
                getComponentStatistics().incrementNumberEntitiesProcessed(threadNumber);
            }
        }
        if (filePaths.size() > 0) {
            callback.sendTextMessage(null, filePaths);
        }
    }
}

From source file:com.live.aac_jenius.globalgroupmute.utilities.Updater.java

/**
 * Part of Zip-File-Extractor, modified by Gravity for use with Updater.
 *
 * @param file the location of the file to extract.
 *//*ww  w  . j  av a 2s. c  o  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());
            this.fileIOOrError(destinationFilePath.getParentFile(),
                    destinationFilePath.getParentFile().mkdirs(), true);
            if (!entry.isDirectory()) {
                final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
                int b;
                final byte[] buffer = new byte[Updater.BYTE_SIZE];
                final FileOutputStream fos = new FileOutputStream(destinationFilePath);
                final BufferedOutputStream bos = new BufferedOutputStream(fos, Updater.BYTE_SIZE);
                while ((b = bis.read(buffer, 0, Updater.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);
                    this.fileIOOrError(output, destinationFilePath.renameTo(output), true);
                }
            }
        }
        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 ex) {
        this.sender.sendMessage(
                this.prefix + "The auto-updater tried to unzip a new update file, but was unsuccessful.");
        this.result = Updater.UpdateResult.FAIL_DOWNLOAD;
        this.plugin.getLogger().log(Level.SEVERE, null, ex);
    } finally {
        this.fileIOOrError(fSourceZip, fSourceZip.delete(), false);
    }
}

From source file:org.apache.taverna.commandline.TavernaCommandLineTest.java

private void assertZipFilesEqual(File file1, File file2) {
    ZipFile zipFile1 = null;
    ZipFile zipFile2 = null;//  ww w.  j ava 2 s.c om
    try {
        zipFile1 = new ZipFile(file1);
        zipFile2 = new ZipFile(file2);
    } catch (Exception e) {
        assertTrue(String.format("%s and %s are not both zip files"), zipFile1 == null);
    }
    if (zipFile1 != null && zipFile2 != null) {
        Enumeration<? extends ZipEntry> entries1 = zipFile1.entries();
        Enumeration<? extends ZipEntry> entries2 = zipFile2.entries();
        while (entries1.hasMoreElements()) {
            assertTrue(entries2.hasMoreElements());
            ZipEntry zipEntry1 = entries1.nextElement();
            ZipEntry zipEntry2 = entries2.nextElement();
            assertEquals(String.format("%s and %s are not both directories", zipEntry1, zipEntry2),
                    zipEntry1.isDirectory(), zipEntry2.isDirectory());
            assertEquals(String.format("%s and %s have different names", zipEntry1, zipEntry2),
                    zipEntry1.getName(), zipEntry2.getName());
            assertEquals(String.format("%s and %s have different sizes", zipEntry1, zipEntry2),
                    zipEntry1.getSize(), zipEntry2.getSize());
            try {
                byte[] byteArray1 = IOUtils.toByteArray(zipFile1.getInputStream(zipEntry1));
                byte[] byteArray2 = IOUtils.toByteArray(zipFile2.getInputStream(zipEntry2));
                assertArrayEquals(String.format("%s != %s", zipEntry1, zipEntry2), byteArray1, byteArray2);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        assertFalse(entries2.hasMoreElements());
    }
}

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 {/*w w  w  .  j  av a2s .  c  o  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.apache.slider.common.tools.CoreFileSystem.java

/**
 * Verify that a file exists in the zip file given by path
 * @param path path to zip file/*from  w  w  w . j  a  v  a 2  s .  c om*/
 * @param file file expected to be in zip
 * @throws FileNotFoundException file not found or is not a zip file
 * @throws IOException  trouble with FS
 */
public void verifyFileExistsInZip(Path path, String file) throws IOException {
    fileSystem.copyToLocalFile(path, new Path("/tmp"));
    File dst = new File((new Path("/tmp", path.getName())).toString());
    Enumeration<? extends ZipEntry> entries;
    ZipFile zipFile = new ZipFile(dst);
    boolean found = false;

    try {
        entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            String nm = entry.getName();
            if (nm.endsWith(file)) {
                found = true;
                break;
            }
        }
    } finally {
        zipFile.close();
    }
    dst.delete();
    if (!found)
        throw new FileNotFoundException("file: " + file + " not found in " + path);
    log.info("Verification of " + path + " passed");
}

From source file:brut.androlib.Androlib.java

private void copyExistingFiles(ZipFile inputFile, ZipOutputStream outputFile) throws IOException {
    // First, copy the contents from the existing outFile:
    Enumeration<? extends ZipEntry> entries = inputFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = new ZipEntry(entries.nextElement());

        // We can't reuse the compressed size because it depends on compression sizes.
        entry.setCompressedSize(-1);//from ww  w  . j a va2 s . c o m
        outputFile.putNextEntry(entry);

        // No need to create directory entries in the final apk
        if (!entry.isDirectory()) {
            BrutIO.copy(inputFile, outputFile, entry);
        }

        outputFile.closeEntry();
    }
}

From source file:com.drevelopment.couponcodes.bukkit.updater.Updater.java

/**
 * Part of Zip-File-Extractor, modified by Gravity for use with Updater.
 *
 * @param file the location of the file to extract.
 *//*from w ww  . j  a  v a  2 s. 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());
            this.fileIOOrError(destinationFilePath.getParentFile(),
                    destinationFilePath.getParentFile().mkdirs(), true);
            if (!entry.isDirectory()) {
                final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
                int b;
                final byte[] buffer = new byte[Updater.BYTE_SIZE];
                final FileOutputStream fos = new FileOutputStream(destinationFilePath);
                final BufferedOutputStream bos = new BufferedOutputStream(fos, Updater.BYTE_SIZE);
                while ((b = bis.read(buffer, 0, Updater.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(this.updateFolder, name);
                    this.fileIOOrError(output, destinationFilePath.renameTo(output), true);
                }
            }
        }
        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) {
        this.plugin.getLogger().log(Level.SEVERE,
                "The auto-updater tried to unzip a new update file, but was unsuccessful.", e);
        this.result = Updater.UpdateResult.FAIL_DOWNLOAD;
    } finally {
        this.fileIOOrError(fSourceZip, fSourceZip.delete(), false);
    }
}

From source file:com.jayway.maven.plugins.android.phase09package.ApkMojo.java

private void computeDuplicateFiles(File jar) throws IOException {
    ZipFile file = new ZipFile(jar);
    Enumeration<? extends ZipEntry> list = file.entries();
    while (list.hasMoreElements()) {
        ZipEntry ze = list.nextElement();
        if (!(ze.getName().contains("META-INF/") || ze.isDirectory())) { // Exclude META-INF and Directories
            List<File> l = jars.get(ze.getName());
            if (l == null) {
                l = new ArrayList<File>();
                jars.put(ze.getName(), l);
            }//ww  w.ja  va  2  s  . c  o m
            l.add(jar);
        }
    }
}