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:com.fujitsu.dc.core.eventlog.ArchiveLogCollection.java

/**
 * ????./*from w w w  . j a  v  a2 s. com*/
 */
public void createFileInformation() {
    File archiveDir = new File(this.directoryPath);
    // ???????????????????
    if (!archiveDir.exists()) {
        return;
    }
    File[] fileList = archiveDir.listFiles();
    for (File file : fileList) {
        // ??
        long fileUpdated = file.lastModified();

        // ??????
        if (this.updated < fileUpdated) {
            this.updated = fileUpdated;
        }

        BasicFileAttributes attr = null;
        ZipFile zipFile = null;
        long fileCreated = 0L;
        long size = 0L;
        try {
            // ???
            attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
            fileCreated = attr.creationTime().toMillis();

            // ????API???????????????????
            zipFile = new ZipFile(file);
            Enumeration<? extends ZipEntry> emu = zipFile.entries();
            while (emu.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) emu.nextElement();
                if (null == entry) {
                    log.info("Zip file entry is null.");
                    throw DcCoreException.Event.ARCHIVE_FILE_CANNOT_OPEN;
                }
                size += entry.getSize();
            }
        } catch (ZipException e) {
            log.info("ZipException", e);
            throw DcCoreException.Event.ARCHIVE_FILE_CANNOT_OPEN;
        } catch (IOException e) {
            log.info("IOException", e);
            throw DcCoreException.Event.ARCHIVE_FILE_CANNOT_OPEN;
        } finally {
            IOUtils.closeQuietly(zipFile);
        }

        // ??????API???????????????(.zip)??????
        String fileName = file.getName();
        String fileNameWithoutZip = fileName.substring(0, fileName.length() - ".zip".length());
        String fileUrl = this.url + "/" + fileNameWithoutZip;
        ArchiveLogFile archiveFile = new ArchiveLogFile(fileCreated, fileUpdated, size, fileUrl);

        this.archivefileList.add(archiveFile);
        log.info(String.format("filename:%s created:%d updated:%d size:%d", file.getName(), fileCreated,
                fileUpdated, size));
    }
}

From source file:io.personium.core.eventlog.ArchiveLogCollection.java

/**
 * ????./*from   www .j av a 2s.c  o m*/
 */
public void createFileInformation() {
    File archiveDir = new File(this.directoryPath);
    // ???????????????????
    if (!archiveDir.exists()) {
        return;
    }
    File[] fileList = archiveDir.listFiles();
    for (File file : fileList) {
        // ??
        long fileUpdated = file.lastModified();

        // ??????
        if (this.updated < fileUpdated) {
            this.updated = fileUpdated;
        }

        BasicFileAttributes attr = null;
        ZipFile zipFile = null;
        long fileCreated = 0L;
        long size = 0L;
        try {
            // ???
            attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
            fileCreated = attr.creationTime().toMillis();

            // ????API???????????????????
            zipFile = new ZipFile(file);
            Enumeration<? extends ZipEntry> emu = zipFile.entries();
            while (emu.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) emu.nextElement();
                if (null == entry) {
                    log.info("Zip file entry is null.");
                    throw PersoniumCoreException.Event.ARCHIVE_FILE_CANNOT_OPEN;
                }
                size += entry.getSize();
            }
        } catch (ZipException e) {
            log.info("ZipException", e);
            throw PersoniumCoreException.Event.ARCHIVE_FILE_CANNOT_OPEN;
        } catch (IOException e) {
            log.info("IOException", e);
            throw PersoniumCoreException.Event.ARCHIVE_FILE_CANNOT_OPEN;
        } finally {
            IOUtils.closeQuietly(zipFile);
        }

        // ??????API???????????????(.zip)??????
        String fileName = file.getName();
        String fileNameWithoutZip = fileName.substring(0, fileName.length() - ".zip".length());
        String fileUrl = this.url + "/" + fileNameWithoutZip;
        ArchiveLogFile archiveFile = new ArchiveLogFile(fileCreated, fileUpdated, size, fileUrl);

        this.archivefileList.add(archiveFile);
        log.info(String.format("filename:%s created:%d updated:%d size:%d", file.getName(), fileCreated,
                fileUpdated, size));
    }
}

From source file:org.eclipse.orion.internal.server.servlets.xfer.ClientImport.java

/**
 * Unzips the transferred file. Returns <code>true</code> if the unzip was
 * successful, and <code>false</code> otherwise. In case of failure, this method
 * handles setting an appropriate response.
 *///from w w w . j  a  v  a 2s.  co  m
private boolean completeUnzip(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
    IPath destPath = new Path(getPath());
    boolean force = false;
    List<String> filesFailed = new ArrayList<String>();
    if (req.getParameter("force") != null) {
        force = req.getParameter("force").equals("true");
    }
    List<String> excludedFiles = new ArrayList<String>();
    if (req.getParameter(ProtocolConstants.PARAM_EXCLUDE) != null) {
        excludedFiles = Arrays.asList(req.getParameter(ProtocolConstants.PARAM_EXCLUDE).split(","));
    }
    try {
        ZipFile source = new ZipFile(new File(getStorageDirectory(), FILE_DATA));
        IFileStore destinationRoot = NewFileServlet.getFileStore(req, destPath);
        Enumeration<? extends ZipEntry> entries = source.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            IFileStore destination = destinationRoot.getChild(entry.getName());
            if (!destinationRoot.isParentOf(destination)
                    || hasExcludedParent(destination, destinationRoot, excludedFiles)) {
                //file should not be imported
                continue;
            }
            if (entry.isDirectory())
                destination.mkdir(EFS.NONE, null);
            else {
                if (!force && destination.fetchInfo().exists()) {
                    filesFailed.add(entry.getName());
                    continue;
                }
                destination.getParent().mkdir(EFS.NONE, null);
                // this filter will throw an IOException if a zip entry is larger than 100MB
                FilterInputStream maxBytesReadInputStream = new FilterInputStream(
                        source.getInputStream(entry)) {
                    private static final int maxBytes = 0x6400000; // 100MB
                    private int totalBytes;

                    private void addByteCount(int count) throws IOException {
                        totalBytes += count;
                        if (totalBytes > maxBytes) {
                            throw new IOException("Zip file entry too large");
                        }
                    }

                    @Override
                    public int read() throws IOException {
                        int c = super.read();
                        if (c != -1) {
                            addByteCount(1);
                        }
                        return c;
                    }

                    @Override
                    public int read(byte[] b, int off, int len) throws IOException {
                        int read = super.read(b, off, len);
                        if (read != -1) {
                            addByteCount(read);
                        }
                        return read;
                    }
                };
                boolean fileWritten = false;
                try {
                    IOUtilities.pipe(maxBytesReadInputStream, destination.openOutputStream(EFS.NONE, null),
                            false, true);
                    fileWritten = true;
                } finally {
                    if (!fileWritten) {
                        try {
                            destination.delete(EFS.NONE, null);
                        } catch (CoreException ce) {
                            // best effort
                        }
                    }
                }
            }
        }
        source.close();

        if (!filesFailed.isEmpty()) {
            String failedFilesList = "";
            for (String file : filesFailed) {
                if (failedFilesList.length() > 0) {
                    failedFilesList += ", ";
                }
                failedFilesList += file;
            }
            String msg = NLS.bind(
                    "Failed to transfer all files to {0}, the following files could not be overwritten {1}",
                    destPath.toString(), failedFilesList);
            JSONObject jsonData = new JSONObject();
            jsonData.put("ExistingFiles", filesFailed);
            statusHandler.handleRequest(req, resp,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, jsonData, null));
            return false;
        }

    } catch (ZipException e) {
        //zip exception implies client sent us invalid input
        String msg = NLS.bind("Failed to complete file transfer on {0}", destPath.toString());
        statusHandler.handleRequest(req, resp,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, e));
        return false;
    } catch (Exception e) {
        //other failures should be considered server errors
        String msg = NLS.bind("Failed to complete file transfer on {0}", destPath.toString());
        statusHandler.handleRequest(req, resp,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
        return false;
    }
    return true;
}

From source file:org.deventropy.shared.utils.DirectoryArchiverUtilTest.java

private void checkZipArchive(final File archiveFile, final File sourceDirectory, final String pathPrefix)
        throws IOException {

    ZipFile zipFile = null;
    try {/*from   ww w  .j  a  va2  s.  c  om*/
        zipFile = new ZipFile(archiveFile);
        final ArchiveEntries archiveEntries = createArchiveEntries(sourceDirectory, pathPrefix);

        final Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            final ZipEntry ze = entries.nextElement();
            if (ze.isDirectory()) {
                assertTrue("Directory in zip should be from us [" + ze.getName() + "]",
                        archiveEntries.dirs.contains(ze.getName()));
                archiveEntries.dirs.remove(ze.getName());
            } else {
                assertTrue("File in zip should be from us [" + ze.getName() + "]",
                        archiveEntries.files.containsKey(ze.getName()));
                final byte[] inflatedMd5 = getMd5Digest(zipFile.getInputStream(ze), true);
                assertArrayEquals("MD5 hash of files should equal [" + ze.getName() + "]",
                        archiveEntries.files.get(ze.getName()), inflatedMd5);
                archiveEntries.files.remove(ze.getName());
            }
        }

        // Check that all files and directories have been accounted for
        assertTrue("All directories should be in the zip", archiveEntries.dirs.isEmpty());
        assertTrue("All files should be in the zip", archiveEntries.files.isEmpty());
    } finally {
        if (null != zipFile) {
            zipFile.close();
        }
    }
}

From source file:net.firejack.platform.installation.processor.OFRInstallProcessor.java

private void installOFR(File ofr) throws IOException {
    ZipFile zipFile = null;
    try {// w w w.j  a v  a  2s . com
        zipFile = new ZipFile(ofr);

        String packageXmlUploadedFile = null;
        String resourceZipUploadedFile = null;
        String codeWarUploadedFile = null;
        Enumeration entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();

            if (PackageFileType.PACKAGE_XML.getOfrFileName().equals(entry.getName())) {
                packageXmlUploadedFile = SecurityHelper.generateRandomSequence(16)
                        + PackageFileType.PACKAGE_XML.getDotExtension();
                OPFEngine.FileStoreService.upload(OpenFlame.FILESTORE_BASE, packageXmlUploadedFile,
                        zipFile.getInputStream(entry), helper.getTemp());
            } else if (PackageFileType.RESOURCE_ZIP.getOfrFileName().equals(entry.getName())) {
                resourceZipUploadedFile = SecurityHelper.generateRandomSequence(16)
                        + PackageFileType.RESOURCE_ZIP.getDotExtension();
                OPFEngine.FileStoreService.upload(OpenFlame.FILESTORE_BASE, resourceZipUploadedFile,
                        zipFile.getInputStream(entry), helper.getTemp());
            } else if (PackageFileType.APP_WAR.getOfrFileName().equals(entry.getName())) {
                codeWarUploadedFile = SecurityHelper.generateRandomSequence(16)
                        + PackageFileType.APP_WAR.getDotExtension();
                OPFEngine.FileStoreService.upload(OpenFlame.FILESTORE_BASE, codeWarUploadedFile,
                        zipFile.getInputStream(entry), helper.getTemp());
            }
        }

        InputStream packageXml = OPFEngine.FileStoreService.download(OpenFlame.FILESTORE_BASE,
                packageXmlUploadedFile, helper.getTemp());
        InputStream resourceZip = OPFEngine.FileStoreService.download(OpenFlame.FILESTORE_BASE,
                resourceZipUploadedFile, helper.getTemp());
        StatusProviderTranslationResult statusResult = packageInstallationService.activatePackage(packageXml,
                resourceZip);
        IOUtils.closeQuietly(packageXml);
        IOUtils.closeQuietly(resourceZip);

        if (statusResult.getResult() && statusResult.getPackage() != null) {
            PackageModel packageRN = statusResult.getPackage();
            if (packageRN != null) {
                Integer oldVersion = packageRN.getVersion();
                packageRN = packageStore.updatePackageVersion(packageRN.getId(),
                        statusResult.getVersionNumber());

                if (statusResult.getOldPackageXml() != null) {
                    packageVersionHelper.archiveVersion(packageRN, oldVersion, statusResult.getOldPackageXml());
                }

                String packageXmlName = packageRN.getName() + PackageFileType.PACKAGE_XML.getDotExtension();
                packageXml = OPFEngine.FileStoreService.download(OpenFlame.FILESTORE_BASE,
                        packageXmlUploadedFile, helper.getTemp());
                OPFEngine.FileStoreService.upload(OpenFlame.FILESTORE_BASE, packageXmlName, packageXml,
                        helper.getVersion(), String.valueOf(packageRN.getId()),
                        String.valueOf(packageRN.getVersion()));
                IOUtils.closeQuietly(packageXml);

                if (resourceZipUploadedFile != null) {
                    String resourceZipName = packageRN.getName()
                            + PackageFileType.RESOURCE_ZIP.getDotExtension();
                    resourceZip = OPFEngine.FileStoreService.download(OpenFlame.FILESTORE_BASE,
                            resourceZipUploadedFile, helper.getTemp());
                    OPFEngine.FileStoreService.upload(OpenFlame.FILESTORE_BASE, resourceZipName, resourceZip,
                            helper.getVersion(), String.valueOf(packageRN.getId()),
                            String.valueOf(packageRN.getVersion()));
                    IOUtils.closeQuietly(resourceZip);
                }

                //                    File webapps = new File(Env.CATALINA_BASE.getValue(), "webapps");
                //                    if (codeWarUploadedFile != null && webapps.exists()) {
                //                        FileUtils.copyFile(codeWarUploadedFile, new File(webapps, packageRN.getName() + PackageFileType.APP_WAR.getDotExtension()));
                //                    }

                if (codeWarUploadedFile != null) {
                    String codeWarName = packageRN.getName() + PackageFileType.APP_WAR.getDotExtension();
                    InputStream warstream = OPFEngine.FileStoreService.download(OpenFlame.FILESTORE_BASE,
                            codeWarUploadedFile, helper.getTemp());
                    OPFEngine.FileStoreService.upload(OpenFlame.FILESTORE_BASE, codeWarName, warstream,
                            helper.getVersion(), String.valueOf(packageRN.getId()),
                            String.valueOf(packageRN.getVersion()));
                    IOUtils.closeQuietly(warstream);
                }

                String packageFilename = packageRN.getName() + PackageFileType.PACKAGE_OFR.getDotExtension();
                FileInputStream stream = new FileInputStream(ofr);
                OPFEngine.FileStoreService.upload(OpenFlame.FILESTORE_BASE, packageFilename, stream,
                        helper.getVersion(), String.valueOf(packageRN.getId()),
                        String.valueOf(packageRN.getVersion()));
                IOUtils.closeQuietly(stream);
            } else {
                throw new BusinessFunctionException("Package archive has not created.");
            }
        }
    } finally {
        if (zipFile != null)
            zipFile.close();
    }
}

From source file:com.cubeia.maven.plugin.firebase.FirebaseRunPlugin.java

private void explode(ZipFile file, File dir) throws IOException {
    for (Enumeration<? extends ZipEntry> en = file.entries(); en.hasMoreElements();) {
        ZipEntry entry = en.nextElement();
        File next = new File(dir, entry.getName());
        if (entry.isDirectory()) {
            next.mkdirs();//from   www .  j av a  2  s .  c o m
        } else {
            next.createNewFile();
            if (next.getParentFile() != null) {
                next.getParentFile().mkdirs();
            }
            InputStream in = file.getInputStream(entry);
            OutputStream out = new FileOutputStream(next);
            try {
                IOUtils.copy(in, out);
            } finally {
                IOUtils.closeQuietly(out);
                IOUtils.closeQuietly(in);
            }
        }
    }
}

From source file:bammerbom.ultimatecore.bukkit.UltimateUpdater.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 ava  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());
            destinationFilePath.getParentFile().mkdirs();
            if (!entry.isDirectory()) {
                final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
                int b;
                final byte[] buffer = new byte[UltimateUpdater.BYTE_SIZE];
                final FileOutputStream fos = new FileOutputStream(destinationFilePath);
                final BufferedOutputStream bos = new BufferedOutputStream(fos, UltimateUpdater.BYTE_SIZE);
                while ((b = bis.read(buffer, 0, UltimateUpdater.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);
                    destinationFilePath.renameTo(output);
                }
            }
        }
        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) {
    } finally {
        fSourceZip.delete();
    }
}

From source file:org.fuin.utils4j.Utils4J.java

/**
 * Unzips a file into a given directory. WARNING: Only relative path entries
 * are allowed inside the archive!/*from  ww  w .j a va2 s. c o  m*/
 * 
 * @param zipFile
 *            Source ZIP file - Cannot be <code>null</code> and must be a
 *            valid ZIP file.
 * @param destDir
 *            Destination directory - Cannot be <code>null</code> and must
 *            exist.
 * @param wrapper
 *            Callback interface to give the caller the chance to wrap the
 *            ZIP input stream into another one. This is useful for example
 *            to display a progress bar - Can be <code>null</code> if no
 *            wrapping is required.
 * @param cancelable
 *            Signals if the unzip should be canceled - Can be
 *            <code>null</code> if no cancel option is required.
 * 
 * @throws IOException
 *             Error unzipping the file.
 */
public static void unzip(final File zipFile, final File destDir, final UnzipInputStreamWrapper wrapper,
        final Cancelable cancelable) throws IOException {

    checkNotNull("zipFile", zipFile);
    checkValidFile(zipFile);
    checkNotNull("destDir", destDir);
    checkValidDir(destDir);

    final ZipFile zip = new ZipFile(zipFile);
    try {
        final Enumeration enu = zip.entries();
        while (enu.hasMoreElements() && ((cancelable == null) || !cancelable.isCanceled())) {
            final ZipEntry entry = (ZipEntry) enu.nextElement();
            final File file = new File(entry.getName());
            if (file.isAbsolute()) {
                throw new IllegalArgumentException(
                        "Only relative path entries are allowed! [" + entry.getName() + "]");
            }
            if (entry.isDirectory()) {
                final File dir = new File(destDir, entry.getName());
                createIfNecessary(dir);
            } else {
                final File outFile = new File(destDir, entry.getName());
                createIfNecessary(outFile.getParentFile());
                final InputStream in;
                if (wrapper == null) {
                    in = new BufferedInputStream(zip.getInputStream(entry));
                } else {
                    in = new BufferedInputStream(
                            wrapper.wrapInputStream(zip.getInputStream(entry), entry, outFile));
                }
                try {
                    final OutputStream out = new BufferedOutputStream(new FileOutputStream(outFile));
                    try {
                        final byte[] buf = new byte[4096];
                        int len;
                        while ((len = in.read(buf)) > 0) {
                            out.write(buf, 0, len);
                        }
                    } finally {
                        out.close();
                    }
                } finally {
                    in.close();
                }
            }
        }
    } finally {
        zip.close();
    }
}

From source file:org.entando.entando.plugins.jpcomponentinstaller.aps.system.services.installer.DefaultComponentInstaller.java

private void extractArchiveFile(File file, String destinationPath)
        throws ZipException, FileNotFoundException, IOException {
    ZipFile zipFile = new ZipFile(file);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    File entryDestination = null;
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        entryDestination = new File(destinationPath, entry.getName());
        entryDestination.getParentFile().mkdirs();
        if (entry.isDirectory()) {
            entryDestination.mkdirs();// www  . ja  va  2 s . com
        } else {
            InputStream in = zipFile.getInputStream(entry);
            OutputStream out = new FileOutputStream(entryDestination);
            IOUtils.copy(in, out);
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    }
}

From source file:com.funambol.framework.tools.FileArchiverTest.java

private void assertDestFileContent(File destFile, List<String> expContent) throws IOException {

    ZipFile archive = null;
    try {//from w w w  .j a  v a  2 s. c  o m
        archive = new ZipFile(destFile);
        Enumeration<? extends ZipEntry> entries = archive.entries();

        assertEquals(expContent.size(), archive.size());

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            assertTrue(expContent.contains(entry.getName()));
        }
    } finally {
        if (archive != null) {
            archive.close();
            archive = null;
        }
    }
}