Example usage for org.apache.commons.compress.archivers.zip ZipFile getEntries

List of usage examples for org.apache.commons.compress.archivers.zip ZipFile getEntries

Introduction

In this page you can find the example usage for org.apache.commons.compress.archivers.zip ZipFile getEntries.

Prototype

public Enumeration getEntries() 

Source Link

Document

Returns all entries.

Usage

From source file:org.openjump.core.ui.plugin.file.open.OpenFileWizardState.java

public void setupFileLoaders(File[] files, FileLayerLoader fileLayerLoader) {
    Set<File> fileSet = new TreeSet<File>(Arrays.asList(files));
    multiLoaderFiles.clear();/*from w w  w  .  ja  va2  s.  com*/
    // explicit loader chosen
    if (fileLayerLoader != null) {
        fileLoaderMap.clear();
        for (File file : fileSet) {
            setFileLoader(file.toURI(), fileLayerLoader);
        }
    } else {
        // Remove old entries in fileloadermap
        fileLoaderMap.clear();
        //      for (Iterator<Entry<URI, FileLayerLoader>> iterator = fileLoaderMap.entrySet()
        //        .iterator(); iterator.hasNext();) {
        //        Entry<URI, FileLayerLoader> entry = iterator.next();
        //        URI fileUri = entry.getKey();
        //        File file;

        //        if (fileUri.getScheme().equals("zip")) {
        //          file = UriUtil.getZipFile(fileUri);
        //        } else {
        //          file = new File(fileUri);
        //        }
        //        
        //        if (!fileSet.contains(file)) {
        //          FileLayerLoader loader = entry.getValue();
        //          fileLoaderFiles.get(loader);
        //          Set<URI> loaderFiles = fileLoaderFiles.get(loader);
        //          if (loaderFiles != null) {
        //            loaderFiles.remove(fileUri);
        //          }
        //          iterator.remove();
        //        }
        //      }

        // manually add compressed files here
        for (File file : files) {
            // zip files
            if (CompressedFile.isZip(file.getName())) {
                try {
                    ZipFile zipFile = new ZipFile(file);
                    URI fileUri = file.toURI();
                    Enumeration entries = zipFile.getEntries();
                    while (entries.hasMoreElements()) {
                        ZipArchiveEntry entry = (ZipArchiveEntry) entries.nextElement();
                        if (!entry.isDirectory()) {
                            URI entryUri = UriUtil.createZipUri(file, entry.getName());
                            String entryExt = UriUtil.getFileExtension(entryUri);
                            //System.out.println(entryUri+"<->"+entryExt);
                            addFile(entryExt, entryUri);
                        }
                    }
                } catch (Exception e) {
                    errorHandler.handleThrowable(e);
                }
            }
            // tar[.gz,.bz...] (un)compressed archive files
            else if (CompressedFile.isTar(file.getName())) {
                try {
                    InputStream is = CompressedFile.openFile(file.getAbsolutePath(), null);
                    TarArchiveEntry entry;
                    TarArchiveInputStream tis = new TarArchiveInputStream(is);
                    while ((entry = tis.getNextTarEntry()) != null) {
                        if (!entry.isDirectory()) {
                            URI entryUri = UriUtil.createZipUri(file, entry.getName());

                            String entryExt = UriUtil.getFileExtension(entryUri);
                            addFile(entryExt, entryUri);
                        }
                    }
                    tis.close();
                } catch (Exception e) {
                    errorHandler.handleThrowable(e);
                }
            }
            // 7zip compressed files
            else if (CompressedFile.isSevenZ(file.getName())) {
                try {
                    //System.out.println(file.getName());
                    SevenZFile sevenZFile = new SevenZFile(file);
                    SevenZArchiveEntry entry;
                    while ((entry = sevenZFile.getNextEntry()) != null) {
                        if (!entry.isDirectory()) {
                            URI entryUri = UriUtil.createZipUri(file, entry.getName());

                            String entryExt = UriUtil.getFileExtension(entryUri);
                            addFile(entryExt, entryUri);
                        }
                    }
                    sevenZFile.close();
                } catch (IOException e) {
                    errorHandler.handleThrowable(e);
                }
            }
            // compressed files
            else if (CompressedFile.hasCompressedFileExtension(file.getName())) {
                String[] parts = file.getName().split("\\.");
                if (parts.length > 2)
                    addFile(parts[parts.length - 2], file.toURI());
            }
            // anything else is a plain data file
            else {
                URI fileUri = file.toURI();
                addFile(FileUtil.getExtension(file), fileUri);
            }
        }
    }
}

From source file:org.opentestsystem.authoring.testitembank.service.impl.ApipZipInputFileExtractorService.java

private HashMap<String, ZipArchiveEntry> getMappedZipFileEntries(final ZipFile zippedFile) {
    final HashMap<String, ZipArchiveEntry> mappedEntries = new HashMap<String, ZipArchiveEntry>();
    final Enumeration<ZipArchiveEntry> entries = zippedFile.getEntries();
    while (entries.hasMoreElements()) {
        final ZipArchiveEntry e = entries.nextElement();
        mappedEntries.put(e.getName(), e);
    }// w ww.  j  a v  a 2s .  com
    return mappedEntries;
}

From source file:org.overlord.commons.dev.server.util.ArchiveUtils.java

/**
 * Unpacks the given archive file into the output directory.
 * @param archiveFile an archive file/*from  w  w  w  .  j a  va  2s . com*/
 * @param toDir where to unpack the archive to
 * @throws IOException
 */
public static void unpackToWorkDir(File archiveFile, File toDir) throws IOException {
    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(archiveFile);
        Enumeration<ZipArchiveEntry> zipEntries = zipFile.getEntries();
        while (zipEntries.hasMoreElements()) {
            ZipArchiveEntry entry = zipEntries.nextElement();
            String entryName = entry.getName();
            File outFile = new File(toDir, entryName);
            if (!outFile.getParentFile().exists()) {
                if (!outFile.getParentFile().mkdirs()) {
                    throw new IOException(
                            "Failed to create parent directory: " + outFile.getParentFile().getCanonicalPath()); //$NON-NLS-1$
                }
            }

            if (entry.isDirectory()) {
                if (!outFile.exists() && !outFile.mkdir()) {
                    throw new IOException("Failed to create directory: " + outFile.getCanonicalPath()); //$NON-NLS-1$
                } else if (outFile.exists() && !outFile.isDirectory()) {
                    throw new IOException("Failed to create directory (already exists but is a file): " //$NON-NLS-1$
                            + outFile.getCanonicalPath());
                }
            } else {
                InputStream zipStream = null;
                OutputStream outFileStream = null;

                zipStream = zipFile.getInputStream(entry);
                outFileStream = new FileOutputStream(outFile);
                try {
                    IOUtils.copy(zipStream, outFileStream);
                } finally {
                    IOUtils.closeQuietly(zipStream);
                    IOUtils.closeQuietly(outFileStream);
                }
            }
        }
    } finally {
        ZipFile.closeQuietly(zipFile);
    }
}

From source file:org.silverpeas.core.util.ZipUtilTest.java

/**
* Test of compressPathToZip method, of class ZipManager.
*
* @throws Exception/*from www  .j  a v a2s.  c o  m*/
*/
@Test
public void testCompressPathToZip(MavenTestEnv mavenTestEnv) throws Exception {
    File path = new File(mavenTestEnv.getResourceTestDirFile(), "ZipSample");
    File outfile = new File(tempDir, "testCompressPathToZip.zip");
    ZipUtil.compressPathToZip(path, outfile);
    ZipFile zipFile = new ZipFile(outfile, CharEncoding.UTF_8);
    try {
        Enumeration<? extends ZipEntry> entries = zipFile.getEntries();
        assertThat(zipFile.getEncoding(), is(CharEncoding.UTF_8));
        int nbEntries = 0;
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            nbEntries++;
        }
        assertThat(nbEntries, is(5));
        assertThat(zipFile.getEntry("ZipSample/simple.txt"), is(notNullValue()));
        assertThat(zipFile.getEntry("ZipSample/level1/simple.txt"), is(notNullValue()));
        assertThat(zipFile.getEntry("ZipSample/level1/level2b/simple.txt"), is(notNullValue()));
        assertThat(zipFile.getEntry("ZipSample/level1/level2a/simple.txt"), is(notNullValue()));

        ZipEntry accentuatedEntry = zipFile.getEntry("ZipSample/level1/level2a/s\u00efmplifi\u00e9.txt");
        if (accentuatedEntry == null) {
            accentuatedEntry = zipFile.getEntry("ZipSample/level1/level2a/"
                    + new String("smplifi.txt".getBytes("UTF-8"), Charset.defaultCharset()));
        }
        assertThat(accentuatedEntry, is(notNullValue()));
        assertThat(zipFile.getEntry("ZipSample/level1/level2c/"), is(nullValue()));
    } finally {
        zipFile.close();
    }
}

From source file:org.slc.sli.ingestion.landingzone.validation.ZipFileValidator.java

@Override
public boolean isValid(File zipFile, AbstractMessageReport report, ReportStats reportStats, Source source,
        Map<String, Object> parameters) {
    boolean isValid = false;

    // we know more of our source
    LOG.info("Validating zipFile: {}", zipFile.getAbsolutePath());

    ZipFile zf = null;
    try {/*from   w  w w. j av  a 2s  .c o  m*/
        zf = new ZipFile(zipFile);

        Enumeration<ZipArchiveEntry> zes = zf.getEntries();

        while (zes.hasMoreElements()) {
            ZipArchiveEntry ze = zes.nextElement();

            LOG.debug("  ZipArchiveEntry:  name: {}, size {}", ze.getName(), ze.getSize());

            if (isDirectory(ze)) {
                report.error(reportStats, new FileSource(zipFile.getName()), BaseMessageCode.BASE_0010,
                        zipFile.getName());
                return false;
            }

            if (ze.getName().endsWith(".ctl")) {
                isValid = true;
            }
        }

        // no manifest (.ctl file) found in the zip file
        if (!isValid) {
            report.error(reportStats, new FileSource(zipFile.getName()), BaseMessageCode.BASE_0009,
                    zipFile.getName());
        }
    } catch (UnsupportedZipFeatureException ex) {
        report.error(ex, reportStats, new FileSource(zipFile.getName()), BaseMessageCode.BASE_0022,
                zipFile.getName());

        isValid = false;
    } catch (FileNotFoundException ex) {
        report.error(ex, reportStats, new FileSource(zipFile.getName()), BaseMessageCode.BASE_0020,
                zipFile.getName());

        isValid = false;
    } catch (IOException ex) {
        LOG.warn("Caught IO exception processing " + zipFile.getAbsolutePath());

        report.error(ex, reportStats, new FileSource(zipFile.getName()), BaseMessageCode.BASE_0021,
                zipFile.getName());

        isValid = false;
    } finally {
        ZipFile.closeQuietly(zf);
    }

    return isValid;
}

From source file:org.slc.sli.ingestion.landingzone.ZipFileUtil.java

/**
 * Extracts content of the ZIP file to the target folder.
 *
 * @param zipFile   ZIP archive//from  www  .  j a v  a2 s  . co m
 * @param targetDir Directory to extract files to
 * @param mkdirs    Allow creating missing directories on the file paths
 * @throws IOException           IO Exception
 * @throws FileNotFoundException
 */
public static void extract(File zipFile, File targetDir, boolean mkdirs) throws IOException {
    ZipFile zf = null;

    try {
        zf = new ZipFile(zipFile);

        Enumeration<ZipArchiveEntry> zes = zf.getEntries();

        while (zes.hasMoreElements()) {
            ZipArchiveEntry entry = zes.nextElement();

            if (!entry.isDirectory()) {
                File targetFile = new File(targetDir, entry.getName());

                if (mkdirs) {
                    targetFile.getParentFile().mkdirs();
                }

                InputStream is = null;
                try {
                    is = zf.getInputStream(entry);
                    copyInputStreamToFile(is, targetFile);
                } finally {
                    IOUtils.closeQuietly(is);
                }
            }
        }
    } finally {
        ZipFile.closeQuietly(zf);
    }
}

From source file:org.slc.sli.ingestion.landingzone.ZipFileUtil.java

/**
 * Get the entries in the ZIP file.//from   ww w  .ja  va 2s.  c om
 *
 * @param zipFileName  ZIP file name
 * @return the entries in the ZIP file
 */
public static Set<String> getZipFileEntries(String zipFileName) throws IOException {
    Enumeration<ZipArchiveEntry> zipFileEntries = null;
    Set<String> filesInZip = new HashSet<String>();

    ZipFile zf = null;

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

    try {
        zf = new ZipFile(zipFileName);

        zipFileEntries = zf.getEntries();
        while (zipFileEntries.hasMoreElements()) {
            filesInZip.add(zipFileEntries.nextElement().getName());
        }

    } finally {
        if (zf != null) {
            ZipFile.closeQuietly(zf);
        }
    }

    return filesInZip;
}

From source file:org.slc.sli.ingestion.landingzone.ZipFileUtil.java

/**
 * Retrieves a name of the first .ctl file found in the zip archive.
 *
 * @param zipFile ZIP file to scan/*  www .  j  av  a  2s  . c o  m*/
 * @return A filename representing the control file.
 * @throws IOException IO Exception
 */
public static String getControlFileName(File zipFile) throws IOException {
    ZipFile zf = null;

    try {
        zf = new ZipFile(zipFile);

        Enumeration<ZipArchiveEntry> zes = zf.getEntries();

        while (zes.hasMoreElements()) {
            ZipArchiveEntry entry = zes.nextElement();

            if (!entry.isDirectory() && entry.getName().endsWith(".ctl")) {
                return entry.getName();
            }
        }
    } finally {
        ZipFile.closeQuietly(zf);
    }

    return null;
}

From source file:org.springframework.ide.eclipse.boot.wizard.content.ZipFileCodeSet.java

@Override
public <T> T each(Processor<T> processor) throws Exception {
    T result = null;//from   www.j av a  2 s  .  c om
    ZipFile zip = new ZipFile(zipDownload.getFile());
    try {
        Enumeration<ZipArchiveEntry> iter = zip.getEntries();
        while (iter.hasMoreElements() && result == null) {
            ZipArchiveEntry el = iter.nextElement();
            Path zipPath = new Path(el.getName());
            if (root.isPrefixOf(zipPath)) {
                String key = zipPath.removeFirstSegments(root.segmentCount()).toString();
                if ("".equals(key)) {
                    //path maches exactly, this means we hit the root of the
                    // code set. Do not store it because the root of a codeset
                    // is not actually an element of the codeset!
                } else {
                    CodeSetEntry cse = csEntry(zip, el);
                    result = processor.doit(cse);
                    if (result != null) {
                        //Bail out early when result found
                        return result;
                    }
                }
            }
        }
        return result;
    } finally {
        try {
            zip.close();
        } catch (IOException e) {
        }
    }
}

From source file:org.xwiki.contrib.maven.PackageExtensionsMojo.java

private Collection<String> getJarsIncludedInWar(Artifact web) throws IOException, MojoExecutionException {
    if (web == null) {
        return Collections.emptyList();
    }/*from  w w w. jav  a  2  s.  c  om*/

    getLog().info(String.format("Excluding Base WAR [%s:%s].", web.getGroupId(), web.getArtifactId()));

    Collection<String> jars = new ArrayList<>();

    // TODO: replace this by a a method which look to the POM of the WAR
    // Open the war and list all the jars
    ZipFile zipFile = new ZipFile(web.getFile());
    Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
    while (entries.hasMoreElements()) {
        String entryName = entries.nextElement().getName();
        if (entryName.startsWith(JAR_DIRECTORY) && entryName.endsWith(".jar")) {
            jars.add(entryName.substring(JAR_DIRECTORY.length()));
        }
    }
    zipFile.close();

    return jars;
}