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.apache.wookie.w3c.util.WidgetPackageUtils.java

/**
 * uses apache commons compress to unpack all the zip entries into a target folder
 * partly adapted from the examples on the apache commons compress site, and an
 * example of generic Zip unpacking. Note this iterates over the ZipArchiveEntry enumeration rather
 * than use the more typical ZipInputStream parsing model, as according to the doco it will
 * more reliably read the entries correctly. More info here: http://commons.apache.org/compress/zip.html
 * @param zipfile the Zip File to unpack
 * @param targetFolder the folder into which to unpack the Zip file
 * @throws IOException//from   w ww .j  a  v  a  2  s  .  c om
 */
@SuppressWarnings("unchecked")
public static void unpackZip(ZipFile zipfile, File targetFolder) throws IOException {
    targetFolder.mkdirs();
    BufferedOutputStream out = null;
    InputStream in = null;
    ZipArchiveEntry zipEntry;

    Enumeration entries = zipfile.getEntries();
    try {
        while (entries.hasMoreElements()) {
            zipEntry = (ZipArchiveEntry) entries.nextElement();
            // Don't add directories - use mkdirs instead
            if (!zipEntry.isDirectory()) {
                File outFile = new File(targetFolder, zipEntry.getName());

                // Ensure that the parent Folder exists
                if (!outFile.getParentFile().exists()) {
                    outFile.getParentFile().mkdirs();
                }
                // Read the entry
                in = new BufferedInputStream(zipfile.getInputStream(zipEntry));
                out = new BufferedOutputStream(new FileOutputStream(outFile));
                IOUtils.copy(in, out);
                // Restore time stamp
                outFile.setLastModified(zipEntry.getTime());

                // Close File
                out.close();
                // Close Stream
                in.close();
            }
        }

    }
    // We'll catch this exception to close the file otherwise it remains locked
    catch (IOException ex) {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.flush();
            out.close();
        }
        // And throw it again
        throw ex;
    }
}

From source file:org.beangle.commons.archiver.ZipUtils.java

public static List<String> unzip(final File zipFile, final String destination, String encoding) {
    List<String> fileNames = CollectUtils.newArrayList();
    String dest = destination;//from ww w  .  j a v  a2 s  . c o  m
    if (!destination.endsWith(File.separator)) {
        dest = destination + File.separator;
    }
    ZipFile file;
    try {
        file = null;
        if (null == encoding)
            file = new ZipFile(zipFile);
        else
            file = new ZipFile(zipFile, encoding);
        @SuppressWarnings("unchecked")
        Enumeration<ZipArchiveEntry> en = file.getEntries();
        ZipArchiveEntry ze = null;
        while (en.hasMoreElements()) {
            ze = en.nextElement();
            File f = new File(dest, ze.getName());
            if (ze.isDirectory()) {
                f.mkdirs();
                continue;
            } else {
                f.getParentFile().mkdirs();
                InputStream is = file.getInputStream(ze);
                OutputStream os = new FileOutputStream(f);
                IOUtils.copy(is, os);
                is.close();
                os.close();
                fileNames.add(f.getAbsolutePath());
            }
        }
        file.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return fileNames;
}

From source file:org.beangle.commons.archiver.ZipUtils.java

public static boolean isZipFile(File zipFile) {
    try {//w  ww  .  jav a 2 s . co m
        ZipFile zf = new ZipFile(zipFile);
        boolean isZip = zf.getEntries().hasMoreElements();
        zf.close();
        return isZip;
    } catch (IOException e) {
        return false;
    }
}

From source file:org.beangle.ems.util.ZipUtils.java

/**
 * <p>//  w  w w  .  j a va  2  s .c  o m
 * unzip.
 * </p>
 * 
 * @param zipFile a {@link java.io.File} object.
 * @param destination a {@link java.lang.String} object.
 * @param encoding a {@link java.lang.String} object.
 * @return a {@link java.util.List} object.
 */
public static List<String> unzip(final File zipFile, final String destination, String encoding) {
    List<String> fileNames = CollectUtils.newArrayList();
    String dest = destination;
    if (!destination.endsWith(File.separator)) {
        dest = destination + File.separator;
    }
    ZipFile file;
    try {
        file = null;
        if (null == encoding)
            file = new ZipFile(zipFile);
        else
            file = new ZipFile(zipFile, encoding);
        Enumeration<ZipArchiveEntry> en = file.getEntries();
        ZipArchiveEntry ze = null;
        while (en.hasMoreElements()) {
            ze = en.nextElement();
            File f = new File(dest, ze.getName());
            if (ze.isDirectory()) {
                f.mkdirs();
                continue;
            } else {
                f.getParentFile().mkdirs();
                InputStream is = file.getInputStream(ze);
                OutputStream os = new FileOutputStream(f);
                IOs.copy(is, os);
                is.close();
                os.close();
                fileNames.add(f.getAbsolutePath());
            }
        }
        file.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return fileNames;
}

From source file:org.codehaus.plexus.archiver.jar.JarArchiver.java

/**
 * Grab lists of all root-level files and all directories
 * contained in the given archive./*from  w ww.ja  v a  2  s  .  c  o  m*/
 *
 * @param file  .
 * @param files .
 * @param dirs  .
 * @throws java.io.IOException .
 */
protected static void grabFilesAndDirs(String file, List<String> dirs, List<String> files) throws IOException {
    File zipFile = new File(file);
    if (!zipFile.exists()) {
        Logger logger = new ConsoleLogger(Logger.LEVEL_INFO, "console");
        logger.error("JarArchive skipping non-existing file: " + zipFile.getAbsolutePath());
    } else if (zipFile.isDirectory()) {
        Logger logger = new ConsoleLogger(Logger.LEVEL_INFO, "console");
        logger.info("JarArchiver skipping indexJar " + zipFile + " because it is not a jar");
    } else {
        org.apache.commons.compress.archivers.zip.ZipFile zf = null;
        try {
            zf = new org.apache.commons.compress.archivers.zip.ZipFile(file, "utf-8");
            Enumeration<ZipArchiveEntry> entries = zf.getEntries();
            HashSet<String> dirSet = new HashSet<String>();
            while (entries.hasMoreElements()) {
                ZipArchiveEntry ze = entries.nextElement();
                String name = ze.getName();
                // avoid index for manifest-only jars.
                if (!name.equals(META_INF_NAME) && !name.equals(META_INF_NAME + '/') && !name.equals(INDEX_NAME)
                        && !name.equals(MANIFEST_NAME)) {
                    if (ze.isDirectory()) {
                        dirSet.add(name);
                    } else if (!name.contains("/")) {
                        files.add(name);
                    } else {
                        // a file, not in the root
                        // since the jar may be one without directory
                        // entries, add the parent dir of this file as
                        // well.
                        dirSet.add(name.substring(0, name.lastIndexOf("/") + 1));
                    }
                }
            }
            dirs.addAll(dirSet);
        } finally {
            if (zf != null) {
                zf.close();
            }
        }
    }
}

From source file:org.codehaus.plexus.archiver.zip.AbstractZipArchiveContentLister.java

protected List<ArchiveContentEntry> execute() throws ArchiverException {
    ArrayList<ArchiveContentEntry> archiveContentList = new ArrayList<ArchiveContentEntry>();

    getLogger().debug("listing: " + getSourceFile());
    org.apache.commons.compress.archivers.zip.ZipFile zf = null;
    try {/*from   w ww. j  a  v  a2  s.  c  o  m*/
        zf = new org.apache.commons.compress.archivers.zip.ZipFile(getSourceFile(), encoding);
        final Enumeration e = zf.getEntries();
        while (e.hasMoreElements()) {
            final ZipArchiveEntry ze = (ZipArchiveEntry) e.nextElement();
            final ZipEntryFileInfo fileInfo = new ZipEntryFileInfo(zf, ze);
            if (isSelected(ze.getName(), fileInfo)) {
                ArchiveContentEntry ae = fileInfo.asArchiveContentEntry();
                archiveContentList.add(ae);
            }
        }
        getLogger().debug("listing complete");
    } catch (final IOException ioe) {
        throw new ArchiverException("Error while listing " + getSourceFile().getAbsolutePath(), ioe);
    } finally {
        IOUtils.closeQuietly(zf);
    }
    return archiveContentList;
}

From source file:org.codehaus.plexus.archiver.zip.AbstractZipUnArchiver.java

protected void execute() throws ArchiverException {
    getLogger().debug("Expanding: " + getSourceFile() + " into " + getDestDirectory());
    org.apache.commons.compress.archivers.zip.ZipFile zf = null;
    try {/*from w w w  .  j av a 2  s  .c o  m*/
        zf = new org.apache.commons.compress.archivers.zip.ZipFile(getSourceFile(), encoding);
        final Enumeration e = zf.getEntries();
        while (e.hasMoreElements()) {
            final ZipArchiveEntry ze = (ZipArchiveEntry) e.nextElement();
            final ZipEntryFileInfo fileInfo = new ZipEntryFileInfo(zf, ze);
            if (isSelected(ze.getName(), fileInfo)) {
                InputStream in = zf.getInputStream(ze);
                extractFileIfIncluded(getSourceFile(), getDestDirectory(), in, ze.getName(),
                        new Date(ze.getTime()), ze.isDirectory(),
                        ze.getUnixMode() != 0 ? ze.getUnixMode() : null, resolveSymlink(zf, ze));
                IOUtil.close(in);
            }

        }

        getLogger().debug("expand complete");
    } catch (final IOException ioe) {
        throw new ArchiverException("Error while expanding " + getSourceFile().getAbsolutePath(), ioe);
    } finally {
        IOUtils.closeQuietly(zf);
    }
}

From source file:org.codehaus.plexus.archiver.zip.AbstractZipUnArchiver.java

protected void execute(final String path, final File outputDirectory) throws ArchiverException {
    org.apache.commons.compress.archivers.zip.ZipFile zipFile = null;

    try {//from   w  w  w  .j  a v a 2 s . c  o m
        zipFile = new org.apache.commons.compress.archivers.zip.ZipFile(getSourceFile(), encoding);

        final Enumeration e = zipFile.getEntries();

        while (e.hasMoreElements()) {
            final ZipArchiveEntry ze = (ZipArchiveEntry) e.nextElement();
            final ZipEntryFileInfo fileInfo = new ZipEntryFileInfo(zipFile, ze);
            if (!isSelected(ze.getName(), fileInfo)) {
                continue;
            }

            if (ze.getName().startsWith(path)) {
                final InputStream inputStream = zipFile.getInputStream(ze);
                extractFileIfIncluded(getSourceFile(), outputDirectory, inputStream, ze.getName(),
                        new Date(ze.getTime()), ze.isDirectory(),
                        ze.getUnixMode() != 0 ? ze.getUnixMode() : null, resolveSymlink(zipFile, ze));
                IOUtil.close(inputStream);
            }
        }
    } catch (final IOException ioe) {
        throw new ArchiverException("Error while expanding " + getSourceFile().getAbsolutePath(), ioe);
    } finally {
        IOUtils.closeQuietly(zipFile);
    }
}

From source file:org.codehaus.plexus.archiver.zip.ZipArchiverTest.java

private void createArchive(ZipArchiver archiver) throws ArchiverException, IOException {
    archiver.createArchive();/*from   w  w w.java 2  s  .c o m*/

    ZipFile zf = new ZipFile(archiver.getDestFile());

    Enumeration e = zf.getEntries();

    while (e.hasMoreElements()) {
        ZipArchiveEntry ze = (ZipArchiveEntry) e.nextElement();
        if (ze.isDirectory()) {
            if (ze.getName().startsWith("worldwritable")) {
                fileModeAssert(0777, UnixStat.PERM_MASK & ze.getUnixMode());
            } else if (ze.getName().startsWith("groupwritable")) {
                fileModeAssert(0070, UnixStat.PERM_MASK & ze.getUnixMode());
            } else {
                fileModeAssert(0500, UnixStat.PERM_MASK & ze.getUnixMode());
            }
        } else {
            if (ze.getName().equals("one.txt")) {
                fileModeAssert(0640, UnixStat.PERM_MASK & ze.getUnixMode());
            } else if (ze.getName().equals("two.txt")) {
                fileModeAssert(0664, UnixStat.PERM_MASK & ze.getUnixMode());
            } else if (ze.isUnixSymlink()) {
                //         assertEquals( ze.getName(), 0500, UnixStat.PERM_MASK & ze.getUnixMode() );
            } else {
                fileModeAssert(0400, UnixStat.PERM_MASK & ze.getUnixMode());
            }
        }

    }
}

From source file:org.epics.archiverappliance.etl.ConsolidateETLJobsForOnePVTest.java

@SuppressWarnings("deprecation")
private void Consolidate() throws AlreadyRegisteredException, IOException, InterruptedException {
    PVTypeInfo typeInfo = new PVTypeInfo(pvName, ArchDBRTypes.DBR_SCALAR_DOUBLE, true, 1);
    String[] dataStores = new String[] { storageplugin1.getURLRepresentation(),
            storageplugin2.getURLRepresentation(), storageplugin3.getURLRepresentation() };
    typeInfo.setDataStores(dataStores);//from ww  w. ja va 2  s . c o m
    configService.updateTypeInfoForPV(pvName, typeInfo);
    configService.registerPVToAppliance(pvName, configService.getMyApplianceInfo());
    configService.getETLLookup().manualControlForUnitTests();
    //generate datas of 10 days PB file 2012_01_01.pb  to 2012_01_10.pb
    int dayCount = 10;
    for (int day = 0; day < dayCount; day++) {
        logger.debug("Generating data for day " + 1);
        int startofdayinseconds = day * 24 * 60 * 60;
        int runsperday = 12;
        int eventsperrun = 24 * 60 * 60 / runsperday;
        for (int currentrun = 0; currentrun < runsperday; currentrun++) {
            try (BasicContext context = new BasicContext()) {
                logger.debug("Generating data for run " + currentrun);

                YearSecondTimestamp yts = new YearSecondTimestamp(currentYear, (day + 1) * 24 * 60 * 60, 0);
                Timestamp etlTime = TimeUtils.convertFromYearSecondTimestamp(yts);
                logger.debug("Running ETL as if it were " + TimeUtils.convertToHumanReadableString(etlTime));
                ETLExecutor.runETLs(configService, etlTime);
                ArrayListEventStream testData = new ArrayListEventStream(eventsperrun,
                        new RemotableEventStreamDesc(type, pvName, currentYear));
                for (int secondsinrun = 0; secondsinrun < eventsperrun; secondsinrun++) {
                    testData.add(
                            new SimulationEvent(startofdayinseconds + currentrun * eventsperrun + secondsinrun,
                                    currentYear, type, new ScalarValue<Double>((double) secondsinrun)));
                }
                storageplugin1.appendData(context, pvName, testData);
            }
            // Sleep for a couple of seconds so that the modification times are different.
            Thread.sleep(2 * 1000);
        }
    } // end for 

    File shortTermFIle = new File(shortTermFolderName);
    File mediumTermFIle = new File(mediumTermFolderName);
    //File longTermFIle=new File(longTermFolderName);

    String[] filesShortTerm = shortTermFIle.list();
    String[] filesMediumTerm = mediumTermFIle.list();
    assertTrue("there should be PB files int short term storage but there is no ", filesShortTerm.length != 0);
    assertTrue("there should be PB files int medium term storage but there is no ",
            filesMediumTerm.length != 0);
    //ArchUnitTestConsolidateETLJobsForOnePVTest:_pb.zip
    File zipFileOflongTermFile = new File(longTermFolderName + "/" + pvName + ":_pb.zip");
    assertTrue(longTermFolderName + "/" + pvName + ":_pb.zip shoule exist but it doesn't",
            zipFileOflongTermFile.exists());
    ZipFile lastZipFile1 = new ZipFile(zipFileOflongTermFile);
    Enumeration<ZipArchiveEntry> enumeration1 = lastZipFile1.getEntries();
    int ss = 0;
    while (enumeration1.hasMoreElements()) {
        enumeration1.nextElement();
        ss++;
    }
    assertTrue(
            "the zip file of " + longTermFolderName + "/" + pvName
                    + ":_pb.zip should contain pb files less than " + dayCount + ",but the number is " + ss,
            ss < dayCount);
    // consolidate
    String storageName = "LTS";
    Timestamp oneYearLaterTimeStamp = TimeUtils
            .convertFromEpochSeconds(TimeUtils.getCurrentEpochSeconds() + 365 * 24 * 60 * 60, 0);
    // The ConfigServiceForTests automatically adds a ETL Job for each PV. For consolidate, we need to have "paused" the PV; we fake this by deleting the jobs.
    configService.getETLLookup().deleteETLJobs(pvName);
    ETLExecutor.runPvETLsBeforeOneStorage(configService, oneYearLaterTimeStamp, pvName, storageName);
    // make sure there are no pb files in short term storage , medium term storage and all files in long term storage
    Thread.sleep(4000);
    String[] filesShortTerm2 = shortTermFIle.list();
    String[] filesMediumTerm2 = mediumTermFIle.list();
    assertTrue("there should be no files int short term storage but there are still " + filesShortTerm2.length
            + "PB files", filesShortTerm2.length == 0);
    assertTrue("there should be no files int medium term storage but there are still " + filesMediumTerm2.length
            + "PB files", filesMediumTerm2.length == 0);
    //ArchUnitTestConsolidateETLJobsForOnePVTest:_pb.zip
    File zipFileOflongTermFile2 = new File(longTermFolderName + "/" + pvName + ":_pb.zip");
    assertTrue(longTermFolderName + "/" + pvName + ":_pb.zip shoule exist but it doesn't",
            zipFileOflongTermFile2.exists());

    ZipFile lastZipFile = new ZipFile(zipFileOflongTermFile2);
    Enumeration<ZipArchiveEntry> enumeration = lastZipFile.getEntries();
    ZipEntry zipEntry = null;
    HashMap<String, String> fileNameMap = new HashMap<String, String>();
    while (enumeration.hasMoreElements()) {
        zipEntry = (ZipEntry) enumeration.nextElement();

        String fileNameTemp = zipEntry.getName();
        logger.info("fileName1=" + fileNameTemp);

        int indexPB = fileNameTemp.indexOf(".pb");
        int indexDate = indexPB - 5;
        String dateFileName = fileNameTemp.substring(indexDate, indexPB);
        fileNameMap.put(dateFileName, dateFileName);
        //System.out.println("fileName="+dateFileName);
        logger.info("fileName=" + dateFileName);
    }

    assertTrue("The number of files should be " + dayCount + ", acutuallly, it is " + fileNameMap.size(),
            fileNameMap.size() == dayCount);
    Date beinningDate = new Date();
    beinningDate.setYear(currentYear - 1);
    beinningDate.setMonth(11);
    beinningDate.setDate(31);
    logger.info("currentYear=" + currentYear);
    logger.info("beinningDate=" + beinningDate);
    Calendar calendarBeingining = Calendar.getInstance();
    calendarBeingining.setTime(beinningDate);
    SimpleDateFormat df = new SimpleDateFormat("MM_dd");
    for (int m = 0; m < dayCount; m++) {
        calendarBeingining.add(Calendar.DAY_OF_MONTH, 1);
        String fileNameTemp1 = df.format(calendarBeingining.getTime());
        logger.info("fileNameTemp1=" + fileNameTemp1);
        assertTrue("the file  whose name is like " + pvName + ":" + currentYear + "_" + fileNameTemp1
                + ".pb should exist,but it doesn't", fileNameMap.get(fileNameTemp1) != null);
    }

}