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.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  ww w.ja  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:it.readbeyond.minstrel.unzipper.Unzipper.java

private String unzip(String inputZip, String destinationDirectory, String mode, JSONObject parameters)
        throws IOException, JSONException {

    // store the zip entries to decompress
    List<String> list = new ArrayList<String>();

    // store the zip entries actually decompressed
    List<String> decompressed = new ArrayList<String>();

    // open input zip file
    File sourceZipFile = new File(inputZip);
    ZipFile zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);

    // open destination directory, creating it if needed    
    File unzipDestinationDirectory = new File(destinationDirectory);
    unzipDestinationDirectory.mkdirs();//w w  w  .ja  v  a2s.com

    // extract all files
    if (mode.equals(ARGUMENT_MODE_ALL)) {
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            list.add(zipFileEntries.nextElement().getName());
        }
    }

    // extract all files except audio and video
    // (determined by file extension)
    if (mode.equals(ARGUMENT_MODE_ALL_NON_MEDIA)) {
        String[] excludeExtensions = JSONArrayToStringArray(
                parameters.optJSONArray(ARGUMENT_ARGS_EXCLUDE_EXTENSIONS));
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            String name = zipFileEntries.nextElement().getName();
            String lower = name.toLowerCase();
            if (!isFile(lower, excludeExtensions)) {
                list.add(name);
            }
        }
    }

    // extract all small files
    // maximum size is passed in args parameter
    // or, if not passed, defaults to const DEFAULT_MAXIMUM_SIZE_FILE
    if (mode.equals(ARGUMENT_MODE_ALL_SMALL)) {
        long maximum_size = parameters.optLong(ARGUMENT_ARGS_MAXIMUM_FILE_SIZE, DEFAULT_MAXIMUM_SIZE_FILE);
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            ZipEntry ze = zipFileEntries.nextElement();
            if (ze.getSize() <= maximum_size) {
                list.add(ze.getName());
            }
        }
    }

    // extract only the requested files
    if (mode.equals(ARGUMENT_MODE_SELECTED)) {
        String[] entries = JSONArrayToStringArray(parameters.optJSONArray(ARGUMENT_ARGS_ENTRIES));
        for (String entry : entries) {
            ZipEntry ze = zipFile.getEntry(entry);
            if (ze != null) {
                list.add(entry);
            }
        }
    }

    // extract all "structural" files
    if (mode.equals(ARGUMENT_MODE_ALL_STRUCTURE)) {
        String[] extensions = JSONArrayToStringArray(parameters.optJSONArray(ARGUMENT_ARGS_EXTENSIONS));
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            String name = zipFileEntries.nextElement().getName();
            String lower = name.toLowerCase();
            boolean extract = isFile(lower, extensions);
            if (extract) {
                list.add(name);
            }
        }
    }

    // NOTE list contains only valid zip entries
    // perform unzip
    for (String currentEntry : list) {
        ZipEntry entry = zipFile.getEntry(currentEntry);
        File destFile = new File(unzipDestinationDirectory, currentEntry);

        File destinationParent = destFile.getParentFile();
        destinationParent.mkdirs();

        if (!entry.isDirectory()) {
            BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry));
            int numberOfBytesRead;
            byte data[] = new byte[BUFFER_SIZE];
            FileOutputStream fos = new FileOutputStream(destFile);
            BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE);
            while ((numberOfBytesRead = is.read(data, 0, BUFFER_SIZE)) > -1) {
                dest.write(data, 0, numberOfBytesRead);
            }
            dest.flush();
            dest.close();
            is.close();
            fos.close();
            decompressed.add(currentEntry);
        }
    }

    zipFile.close();
    return stringify(decompressed);
}

From source file:org.kse.gui.crypto.DUpgradeCryptoStrength.java

private void processPolicyZipFile(File droppedFile) {
    // Process the supplied drop file as a policy zip. If it is a valid policy zip store the policy jar contents
    try {/*from w ww  .java2  s  . c  om*/
        ZipFile zip = null;

        try {
            zip = new ZipFile(droppedFile);
        } catch (ZipException ex) {
            return;
        } finally {
            IOUtils.closeQuietly(zip);
        }

        Enumeration<? extends ZipEntry> zipEntries = zip.entries();

        while (zipEntries.hasMoreElements()) {
            ZipEntry zipEntry = zipEntries.nextElement();

            if (!zipEntry.isDirectory()) {
                if (zipEntry.getName().endsWith(LOCAL_POLICY.jar())) {
                    ByteArrayOutputStream localPolicyJarBaos = new ByteArrayOutputStream();
                    CopyUtil.copyClose(zip.getInputStream(zipEntry), localPolicyJarBaos);
                    localPolicyJarContents = localPolicyJarBaos.toByteArray();
                } else if (zipEntry.getName().endsWith(US_EXPORT_POLICY.jar())) {
                    ByteArrayOutputStream usExportPolicyJarBaos = new ByteArrayOutputStream();
                    CopyUtil.copyClose(zip.getInputStream(zipEntry), usExportPolicyJarBaos);
                    usExportPolicyJarContents = usExportPolicyJarBaos.toByteArray();
                }
            }
        }

        if (localPolicyJarContents != null && usExportPolicyJarContents != null) {
            jbDownloadPolicy.setEnabled(false);
            jbBrowsePolicy.setEnabled(false);
            policyZipDropTarget.policyZipAccepted();
            jbUpgrade.setEnabled(true);
        } else {
            JOptionPane.showMessageDialog(DUpgradeCryptoStrength.this,
                    res.getString("DUpgradeCryptoStrength.NotPolicyZip.message"),
                    res.getString("DUpgradeCryptoStrength.Title"), JOptionPane.WARNING_MESSAGE);
        }
    } catch (IOException ex) {
        DError.displayError(DUpgradeCryptoStrength.this, ex);
    }
}

From source file:com.google.appinventor.buildserver.util.AARLibrary.java

/**
 * Unpacks the Android Archive to a directory in the file system. The unpacking operation will
 * create a new directory named with the archive's package name to prevent collisions with
 * other Android Archives.//from  w  ww  .j  a v  a 2  s .c  o  m
 * @param path the path to where the archive will be unpacked.
 * @throws IOException if any error occurs attempting to read the archive or write new files to
 *                     the file system.
 */
public void unpackToDirectory(final File path) throws IOException {
    ZipFile zip = null;
    try {
        zip = new ZipFile(aarPath);
        packageName = extractPackageName(zip);
        basedir = new File(path, packageName);
        if (!basedir.mkdirs()) {
            throw new IOException("Unable to create directory for AAR package");
        }
        InputStream input = null;
        OutputStream output = null;
        Enumeration<? extends ZipEntry> i = zip.entries();
        while (i.hasMoreElements()) {
            ZipEntry entry = i.nextElement();
            File target = new File(basedir, entry.getName());
            if (entry.isDirectory() && !target.exists() && !target.mkdirs()) {
                throw new IOException("Unable to create directory " + path.getAbsolutePath());
            } else if (!entry.isDirectory()) {
                try {
                    output = new FileOutputStream(target);
                    input = zip.getInputStream(entry);
                    IOUtils.copy(input, output);
                } finally {
                    IOUtils.closeQuietly(input);
                    IOUtils.closeQuietly(output);
                }
                catalog(target);
            }
        }
        resdir = new File(basedir, "res");
        if (!resdir.exists()) {
            resdir = null;
        }
    } finally {
        IOUtils.closeQuietly(zip);
    }
}

From source file:nl.edia.sakai.tool.skinmanager.impl.SkinFileSystemServiceImpl.java

protected void installSkin(File skinDir, File file) throws SkinException, IOException {
    ZipFile myZipFile = null;
    try {/*from   w  w w . j a v a 2 s.  com*/
        myZipFile = new ZipFile(file);
        Enumeration<? extends ZipEntry> myEntries = myZipFile.entries();
        while (myEntries.hasMoreElements()) {
            ZipEntry myZipEntry = (ZipEntry) myEntries.nextElement();
            handleEntry(myZipEntry, myZipFile, skinDir);
        }
    } catch (ZipException z) {
        throw new SkinException("Error reading zip file", z);
    } finally {
        if (myZipFile != null) {
            try {
                myZipFile.close();
            } catch (IOException e) {
                // ignore
            }
        }

    }
}

From source file:org.jvnet.hudson.plugins.thinbackup.backup.BackupSet.java

/**
 * Unzips this backup set into a directory within the specified directory if it was initialized from a ZIP file. Does
 * NOT change <i>this</i>. deleteUnzipDir() may be called if the unzipped BackupSet is no longer needed. The directory
 * the BackupSet was unzipped to can be retrieved with getUnzipDir(). Before using the returned BackupSet, it should
 * be checked if it is valid./* w  ww  .  j a v  a 2s  .com*/
 * 
 * @param directory target directory
 * @return a new BackupSet referencing the unzipped directories, or the current BackupSet if it was either not created
 *         from a ZIP file or is invalid. In case of an error an invalid BackupSet is returned.
 * @throws IOException - if an I/O error occurs.
 */
public BackupSet unzipTo(final File directory) throws IOException {
    BackupSet result = null;

    if (inZipFile && isValid()) {
        if (!directory.exists()) {
            directory.mkdirs();
        }
        unzipDir = new File(directory, getBackupSetZipFileName().replace(HudsonBackup.ZIP_FILE_EXTENSION, ""));
        if (!unzipDir.exists()) {
            unzipDir.mkdirs();
        }

        final ZipFile zipFile = new ZipFile(backupSetzipFile);
        final byte data[] = new byte[DirectoriesZipper.BUFFER_SIZE];
        final Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
        while (zipEntries.hasMoreElements()) {
            final ZipEntry entry = zipEntries.nextElement();

            final String fullPathToEntry = entry.getName();
            final String pathToEntry = fullPathToEntry.substring(0,
                    fullPathToEntry.lastIndexOf(File.separator));
            final File entryDir = new File(unzipDir, pathToEntry);
            entryDir.mkdirs();
            final String entryName = fullPathToEntry.substring(fullPathToEntry.lastIndexOf(File.separator) + 1);

            final BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry));

            final FileOutputStream fos = new FileOutputStream(
                    new File(unzipDir + File.separator + pathToEntry, entryName));
            final BufferedOutputStream dest = new BufferedOutputStream(fos, DirectoriesZipper.BUFFER_SIZE);

            int count = 0;
            while ((count = is.read(data)) != -1) {
                dest.write(data, 0, count);
            }

            dest.flush();
            dest.close();
        }
        zipFile.close();

        final File[] backups = unzipDir.listFiles();
        if (backups.length > 0) {
            result = new BackupSet(backups[0]);
        } else {
            // in case of an error (i.e. nothing was unzipped) return an invalid BackupSet
            result = new BackupSet(unzipDir);
        }
    } else {
        result = this;
    }

    return result;
}

From source file:fr.gouv.finances.cp.xemelios.importers.batch.BatchRealImporter.java

private ImportContent files(final String extension, final String titreEtat) {
    ImportContent ic = new ImportContent();
    Vector<File> ret = new Vector<File>();
    ret.addAll(files);/*w w w  . j a v  a  2  s. c om*/
    // on regarde si l'un des fichiers a importer est un zip
    for (int i = 0; i < ret.size(); i++) {
        if (ret.get(i).getName().toLowerCase().endsWith(".zip")) {
            if (ret.get(i).exists()) {
                ZipFile zf = null;
                try {
                    zf = new ZipFile(ret.get(i));
                    for (Enumeration<? extends ZipEntry> enumer = zf.entries(); enumer.hasMoreElements();) {
                        ZipEntry ze = enumer.nextElement();
                        if (!ze.isDirectory()) {
                            String fileName = ze.getName();
                            String entryName = fileName.toLowerCase();
                            fileName = fileName.replace(File.pathSeparatorChar, '_')
                                    .replace(File.separatorChar, '_').replace(':', '|').replace('\'', '_')
                                    .replace('/', '_');
                            logger.debug(entryName);
                            if (PJRef.isPJ(ze)) {
                                PJRef pj = new PJRef(ze);
                                File tmpFile = pj.writeTmpFile(FileUtils.getTempDir(), zf);
                                ic.pjs.add(pj);
                                filesToDrop.add(tmpFile);
                            } else if ((entryName.endsWith(extension.toLowerCase())
                                    || entryName.endsWith(".xml")) && !fileName.startsWith("_")) {
                                // on decompresse le fichier dans le
                                // repertoire temporaire, comme ca il sera
                                // supprime en quittant
                                InputStream is = zf.getInputStream(ze);
                                BufferedInputStream bis = new BufferedInputStream(is);
                                File output = new File(FileUtils.getTempDir(), fileName);
                                BufferedOutputStream bos = new BufferedOutputStream(
                                        new FileOutputStream(output));
                                byte[] buffer = new byte[1024];
                                int read = bis.read(buffer);
                                while (read > 0) {
                                    bos.write(buffer, 0, read);
                                    read = bis.read(buffer);
                                }
                                bos.flush();
                                bos.close();
                                bis.close();
                                ic.filesToImport.add(output);
                                filesToDrop.add(output);
                            }
                        }
                    }
                    zf.close();
                } catch (ZipException zEx) {
                    System.out.println(
                            "Le fichier " + ret.get(i).getName() + " n'est pas une archive ZIP valide.");
                } catch (IOException ioEx) {
                    ioEx.printStackTrace();
                } finally {
                    if (zf != null) {
                        try {
                            zf.close();
                        } catch (Throwable t) {
                        }
                    }
                }
            }
        } else if (ret.get(i).getName().toLowerCase().endsWith(".gz")) {
            try {
                String fileName = ret.get(i).getName();
                fileName = fileName.substring(0, fileName.length() - 3);
                File output = new File(FileUtils.getTempDir(), fileName);
                GZIPInputStream gis = new GZIPInputStream(new FileInputStream(ret.get(i)));
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(output));
                byte[] buffer = new byte[1024];
                int read = gis.read(buffer);
                while (read > 0) {
                    bos.write(buffer, 0, read);
                    read = gis.read(buffer);
                }
                bos.flush();
                bos.close();
                gis.close();
                ic.filesToImport.add(output);
                filesToDrop.add(output);
            } catch (IOException ioEx) {
                // nothing to do
            }
        } else {
            ic.filesToImport.add(ret.get(i));
            // dans ce cas l, on ne le supprime pas
        }
    }
    return ic;
}

From source file:com.t3.persistence.PackedFile.java

/**
 * Get all of the path names for this packed file.
 *
 * @return All the path names. Changing this set does not affect the packed file. Changes to the
 * file made after this method is called are not reflected in the path and do not cause a
 * ConcurrentModificationException. Directories in the packed file are also included in the set.
 * @throws IOException Problem with the zip file.
 *///w w  w .j  av  a2s . com
public Set<String> getPaths() throws IOException {
    Set<String> paths = new HashSet<String>(addedFileSet);
    paths.add(CONTENT_FILE);
    paths.add(PROPERTY_FILE);
    if (file.exists()) {
        ZipFile zf = getZipFile();
        Enumeration<? extends ZipEntry> e = zf.entries();
        while (e.hasMoreElements()) {
            paths.add(e.nextElement().getName());
        }
    }
    paths.removeAll(removedFileSet);
    return paths;
}

From source file:org.jvnet.hudson.plugins.thinbackup.backup.BackupSet.java

private boolean initializeFromZipFile() {
    boolean success = true;

    ZipFile zipFile = null;
    try {//  w ww.  j av  a 2 s . c om
        Utils.waitUntilFileCanBeRead(backupSetzipFile);
        zipFile = new ZipFile(backupSetzipFile);
        final Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
        while (zipEntries.hasMoreElements() && success) {
            final ZipEntry entry = zipEntries.nextElement();
            String tmpName = entry.getName();
            tmpName = tmpName.substring(0, tmpName.indexOf(File.separator));
            if (tmpName.startsWith(BackupType.FULL.toString())) {
                if ((fullBackupName == null) || fullBackupName.equals(tmpName)) {
                    fullBackupName = tmpName;
                } else {
                    LOGGER.warning(String.format(
                            "Backup set '%s' contains multiple full backups and is therefore not valid.",
                            zipFile.getName()));
                    success = false;
                }
            } else if (tmpName.startsWith(BackupType.DIFF.toString()) && !diffBackupsNames.contains(tmpName)) {
                diffBackupsNames.add(tmpName);
            }
        }
    } catch (final IOException e) {
        LOGGER.log(Level.SEVERE,
                String.format("Cannot initialize BackupSet from ZIP file '%s'.", backupSetzipFile.getName()),
                e);
        success = false;
    } finally {
        try {
            if (zipFile != null) {
                zipFile.close();
            }
        } catch (final IOException e) {
            LOGGER.log(Level.SEVERE, String.format("Cannot close ZIP file '%s'.", backupSetzipFile.getName()),
                    e);
            success = false;
        }
    }

    return success;
}

From source file:de.tudarmstadt.ukp.clarin.webanno.project.page.ProjectPage.java

private void actionImportProject(List<FileUpload> exportedProjects, boolean aGenerateUsers) {
    Project importedProject = new Project();
    // import multiple projects!
    for (FileUpload exportedProject : exportedProjects) {
        InputStream tagInputStream;
        try {//  w  w  w  .j  a v a2s .  c o m
            tagInputStream = exportedProject.getInputStream();
            if (!ZipUtils.isZipStream(tagInputStream)) {
                error("Invalid ZIP file");
                return;
            }
            File zipFfile = exportedProject.writeToTempFile();
            if (!ImportUtil.isZipValidWebanno(zipFfile)) {
                error("Incompatible to webanno ZIP file");
            }
            ZipFile zip = new ZipFile(zipFfile);
            InputStream projectInputStream = null;
            for (Enumeration zipEnumerate = zip.entries(); zipEnumerate.hasMoreElements();) {
                ZipEntry entry = (ZipEntry) zipEnumerate.nextElement();
                if (entry.toString().replace("/", "").startsWith(ImportUtil.EXPORTED_PROJECT)
                        && entry.toString().replace("/", "").endsWith(".json")) {
                    projectInputStream = zip.getInputStream(entry);
                    break;
                }
            }

            // projectInputStream =
            // uploadedFile.getInputStream();
            String text = IOUtils.toString(projectInputStream, "UTF-8");
            de.tudarmstadt.ukp.clarin.webanno.model.export.Project importedProjectSetting = JSONUtil
                    .getJsonConverter().getObjectMapper()
                    .readValue(text, de.tudarmstadt.ukp.clarin.webanno.model.export.Project.class);

            importedProject = ImportUtil.createProject(importedProjectSetting, repository, userRepository);

            Map<de.tudarmstadt.ukp.clarin.webanno.model.export.AnnotationFeature, AnnotationFeature> featuresMap = ImportUtil
                    .createLayer(importedProject, importedProjectSetting, userRepository, annotationService);
            ImportUtil.createSourceDocument(importedProjectSetting, importedProject, repository, userRepository,
                    featuresMap);
            ImportUtil.createMiraTemplate(importedProjectSetting, automationService, featuresMap);
            ImportUtil.createCrowdJob(importedProjectSetting, repository, importedProject);

            ImportUtil.createAnnotationDocument(importedProjectSetting, importedProject, repository);
            ImportUtil.createProjectPermission(importedProjectSetting, importedProject, repository,
                    aGenerateUsers, userRepository);
            /*
             * for (TagSet tagset : importedProjectSetting.getTagSets()) {
             * ImportUtil.createTagset(importedProject, tagset, projectRepository,
             * annotationService); }
             */
            // add source document content
            ImportUtil.createSourceDocumentContent(zip, importedProject, repository);
            // add annotation document content
            ImportUtil.createAnnotationDocumentContent(zip, importedProject, repository);
            // create curation document content
            ImportUtil.createCurationDocumentContent(zip, importedProject, repository);
            // create project log
            ImportUtil.createProjectLog(zip, importedProject, repository);
            // create project guideline
            ImportUtil.createProjectGuideline(zip, importedProject, repository);
            // cretae project META-INF
            ImportUtil.createProjectMetaInf(zip, importedProject, repository);
        } catch (IOException e) {
            error("Error Importing Project " + ExceptionUtils.getRootCauseMessage(e));
        }
    }
    projectDetailForm.setModelObject(importedProject);
    SelectionModel selectedProjectModel = new SelectionModel();
    selectedProjectModel.project = importedProject;
    projectSelectionForm.setModelObject(selectedProjectModel);
    projectDetailForm.setVisible(true);
    RequestCycle.get().setResponsePage(getPage());
}