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.commonjava.maven.galley.filearc.internal.ZipListing.java

@Override
public ListingResult call() {
    final File src = getArchiveFile(resource.getLocationUri());
    if (!src.canRead() || src.isDirectory()) {
        return null;
    }//from   w  w w.j a va  2  s .  c o  m

    final boolean isJar = isJar(resource.getLocationUri());

    final TreeSet<String> filenames = new TreeSet<String>();

    ZipFile zf = null;
    try {
        if (isJar) {
            zf = new JarFile(src);
        } else {
            zf = new ZipFile(src);
        }

        final String path = resource.getPath();
        final int pathLen = path.length();
        for (final ZipEntry entry : Collections.list(zf.entries())) {
            String name = entry.getName();
            if (name.startsWith(path)) {
                name = name.substring(pathLen);

                if (name.startsWith("/") && name.length() > 1) {
                    name = name.substring(1);

                    if (name.indexOf("/") < 0) {
                        filenames.add(name);
                    }
                }
            }
        }

    } catch (final IOException e) {
        error = new TransferException("Failed to get listing for: %s to: %s. Reason: %s", e, resource,
                e.getMessage());
    } finally {
        if (zf != null) {
            try {
                zf.close();
            } catch (final IOException e) {
            }
        }
    }

    if (!filenames.isEmpty()) {
        OutputStream stream = null;
        try {
            stream = target.openOutputStream(TransferOperation.DOWNLOAD);
            stream.write(join(filenames, "\n").getBytes("UTF-8"));

            return new ListingResult(resource, filenames.toArray(new String[filenames.size()]));
        } catch (final IOException e) {
            error = new TransferException("Failed to write listing to: %s. Reason: %s", e, target,
                    e.getMessage());
        } finally {
            closeQuietly(stream);
        }
    }

    return null;
}

From source file:org.jboss.windup.util.RecursiveZipMetaFactory.java

protected void recursivelyExtract(ZipMetadata parent, ZipFile zip, File outputDirectory) {
    String fileName = StringUtils.substringAfterLast(zip.getName(), File.separator);
    File subOutputDir = new File(outputDirectory.getAbsolutePath() + File.separator + fileName);
    ZipEntry entry;/*from  w  w w .j  a  va 2 s . co m*/

    Enumeration<?> e = zip.entries();
    while (e.hasMoreElements()) {
        entry = (ZipEntry) e.nextElement();
        // must be a candidate file.
        if (!entry.isDirectory()) {
            if (archiveEndInEntryOfInterest(entry.getName())) {
                try {
                    File extracted = unzipEntry(parent, entry, zip, subOutputDir);
                    ZipFile zf = new ZipFile(extracted);

                    // we should know it is a valid zip here..
                    ZipMetadata arch = generateArchive(parent, extracted);
                    LOG.info("Prepared ZipMetadata: " + arch.getRelativePath());
                    recursivelyExtract(arch, zf,
                            new File(StringUtils.substringBeforeLast(zf.getName(), File.separator)));
                } catch (FileNotFoundException e1) {
                    LOG.warn("Skipping invalid zip entry: " + entry);
                } catch (IOException e1) {
                    LOG.warn("Skipping invalid zip entry: " + entry);
                }
            }
        }
    }
    try {
        zip.close();
    } catch (IOException e1) {
        LOG.error("Exception closing zip.", e1);
    }
}

From source file:net.sourceforge.squirrel_sql.fw.util.IOUtilitiesImpl.java

/**
 * @see net.sourceforge.squirrel_sql.fw.util.IOUtilities# copyResourceFromJarFile(java.lang.String,
 *      java.lang.String, java.lang.String)
 *///from  w  ww  . j  a  v a 2  s .  co  m
@Override
public void copyResourceFromJarFile(String jarFilename, String resourceName, String destinationFile)
        throws ZipException, IOException {
    ZipFile appJar = new ZipFile(new File(jarFilename));
    Enumeration<? extends ZipEntry> entries = appJar.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        String entryName = entry.getName();
        if (entryName.endsWith(resourceName)) {
            InputStream is = null;
            try {
                FileWrapper destinationFileWrapper = fileWrapperFactory.create(destinationFile);
                is = appJar.getInputStream(entry);
                copyBytesToFile(is, destinationFileWrapper);
            } finally {
                closeInputStream(is);
            }
            break;
        }
    }

}

From source file:ch.jamiete.hilda.plugins.PluginManager.java

/**
 * Attempts to load plugin data from the {@code plugin.json} file.
 * @param file//from ww  w.j a va2  s  .c om
 * @return the plugin data or {@code null} if no data could be loaded
 * @throws IllegalArgumentException if any of the conditions of a plugin data file are not met
 */
private PluginData loadPluginData(final File file) {
    PluginData data = null;

    try {
        final ZipFile zipFile = new ZipFile(file);
        final Enumeration<? extends ZipEntry> entries = zipFile.entries();

        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();
            final InputStream stream = zipFile.getInputStream(entry);

            if (entry.getName().equals("plugin.json")) {
                data = new Gson().fromJson(IOUtils.toString(stream, Charset.defaultCharset()),
                        PluginData.class);

                Sanity.nullCheck(data.name, "A plugin must define its name.");
                Sanity.nullCheck(data.mainClass, "A plugin must define its main class.");
                Sanity.nullCheck(data.version, "A plugin must define its version.");
                Sanity.nullCheck(data.author, "A plugin must define its author.");

                data.pluginFile = file;

                if (data.dependencies == null) {
                    data.dependencies = new String[0];
                }
            }
        }

        zipFile.close();
    } catch (final Exception ex) {
        Hilda.getLogger().log(Level.SEVERE,
                "Encountered exception when trying to load plugin JSON for " + file.getName(), ex);
    }

    return data;
}

From source file:de.uni_potsdam.hpi.bpt.promnicat.importer.bpmai.BpmaiImporter.java

/**
 * Scans the given root directory for sgx-archives and extracts them into the dummy folder.
 * The extracted models can be parsed like any other process models from the BPM AI.
 * @param rootDir container of archives to extract
 * @param dummyFolder folder to extract the models to
 * @throws ZipException if archive extraction went wrong
 * @throws IOException if one of the given paths can not be read or written
 *//*ww  w. j  av  a 2s. c o  m*/
private void extractAvailableSgxArchives(File rootDir, File dummyFolder) throws ZipException, IOException {
    for (File file : rootDir.listFiles()) {
        if ((!file.isDirectory()) && (file.getName().endsWith(".sgx"))) {
            ZipFile zipFile = new ZipFile(file);
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            //iterate through files of an zip archive
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                String entryName = entry.getName();
                if (entryName.contains("/")) {
                    //ignore meta data files
                    if (entryName.endsWith("_meta.json")) {
                        continue;
                    }
                    //remove directory folder to fit into expected structure
                    String[] pathParts = entryName.split("/");
                    if (entryName.contains("directory_")) {
                        entryName = "";
                        for (int i = 0; i < pathParts.length; i++) {
                            if (!(pathParts[i].startsWith("directory_"))) {
                                entryName = entryName.concat(pathParts[i] + "/");
                            }
                        }
                        entryName = entryName.substring(0, entryName.length() - 1);
                    }
                    //rename process model files
                    String oldModelName = pathParts[pathParts.length - 1];
                    String[] nameParts = oldModelName.split("_");
                    if (nameParts.length > 2) {
                        String modelName = pathParts[pathParts.length - 2].split("_")[1] + "_rev" + nameParts[1]
                                + nameParts[2];
                        entryName = entryName.replace(oldModelName, modelName);
                    }
                    //create directories
                    (new File(dummyFolder.getPath() + File.separatorChar
                            + entryName.substring(0, entryName.lastIndexOf("/")))).mkdirs();
                }
                //extract process model
                copyInputStream(zipFile.getInputStream(entry),
                        dummyFolder.getPath() + File.separatorChar + entryName);
            }
            zipFile.close();
        }
    }
}

From source file:com.microsoft.tfs.client.common.ui.teambuild.commands.CreateUploadZipCommand.java

/**
 * Get the root directory in zip archive to build a fake directory path and
 * use ignore file to exclude zip entries. e.g. Given a zip C:\java.zip if
 * top level folder in Java.zip is Java5, it will return C:\Java.zip\Java5\
 *
 * This method is only used to build the right ignore pattern to exclude zip
 * entries/*from www  .  j a  va 2 s .  co  m*/
 *
 * @param zipPath
 * @return
 * @throws IOException
 */
private String getRootFolderInZip(final String zipPath) throws Exception {
    final ZipFile zipSrc = new ZipFile(zipPath);
    final Enumeration<? extends ZipEntry> entries = zipSrc.entries();

    int minBinDepth = Integer.MAX_VALUE;
    String binEntryName = null;
    final int zipDepth = LocalPath.getFolderDepth(zipPath);

    while (entries.hasMoreElements()) {
        final ZipEntry entry = entries.nextElement();
        final String parentEntryName = LocalPath.getParent(LocalPath.combine(zipPath, entry.getName()));
        final String name = LocalPath.getFileName(parentEntryName);

        if (name.equalsIgnoreCase("bin")) //$NON-NLS-1$
        {
            final int depth = LocalPath.getFolderDepth(parentEntryName);
            if (minBinDepth > depth) {
                minBinDepth = depth;
                binEntryName = parentEntryName;
            }
            if (minBinDepth == zipDepth + 1) {
                break;
            }
        }
    }

    if (binEntryName != null) {
        return LocalPath.getParent(binEntryName);
    } else {
        errorMsg = MessageFormat.format(
                Messages.getString("CreateUploadZipCommand.InvalidArchiveErrorMessageFormat"), //$NON-NLS-1$
                buildToolName);
        log.error("Invalid archive " + zipPath); //$NON-NLS-1$
        throw new Exception("The archive does not contain valid " + buildToolName); //$NON-NLS-1$
    }
}

From source file:com.googlecode.android_scripting.ZipExtractorTask.java

private long unzip() throws Exception {
    long extractedSize = 0l;
    Enumeration<? extends ZipEntry> entries;
    if (mInput.isFile() && mInput.getName().contains(".gz")) {
        InputStream stream = new FileInputStream(mInput);
        GZIPInputStream gzipStream = new GZIPInputStream(stream);
        InputSource is = new InputSource(gzipStream);
        InputStream input = new BufferedInputStream(is.getByteStream());
        File destination = new File(mOutput, "php");
        ByteArrayBuffer baf = new ByteArrayBuffer(255000);
        int current = 0;
        while ((current = input.read()) != -1) {
            baf.append((byte) current);
        }//from  w ww . jav a 2  s  .c  om

        FileOutputStream output = new FileOutputStream(destination);
        output.write(baf.toByteArray());
        output.close();
        Log.d("written!");
        return baf.toByteArray().length;
    }
    ZipFile zip = new ZipFile(mInput);
    long uncompressedSize = getOriginalSize(zip);

    publishProgress(0, (int) uncompressedSize);

    entries = zip.entries();

    try {
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.isDirectory()) {
                // Not all zip files actually include separate directory entries.
                // We'll just ignore them
                // and create them as necessary for each actual entry.
                continue;
            }
            File destination = new File(mOutput, entry.getName());
            if (!destination.getParentFile().exists()) {
                destination.getParentFile().mkdirs();
            }
            if (destination.exists() && mContext != null && !mReplaceAll) {
                Replace answer = showDialog(entry.getName());
                switch (answer) {
                case YES:
                    break;
                case NO:
                    continue;
                case YESTOALL:
                    mReplaceAll = true;
                    break;
                default:
                    return extractedSize;
                }
            }
            ProgressReportingOutputStream outStream = new ProgressReportingOutputStream(destination);
            extractedSize += IoUtils.copy(zip.getInputStream(entry), outStream);
            outStream.close();
        }
    } finally {
        try {
            zip.close();
        } catch (Exception e) {
            // swallow this exception, we are only interested in the original one
        }
    }
    Log.v("Extraction is complete.");
    return extractedSize;
}

From source file:de.tarent.maven.plugins.pkg.packager.IzPackPackager.java

/**
 * Puts the embedded izpack jar from the (resource) classpath into the work
 * directory and unpacks it there./*  w ww  .  ja v a  2s .  com*/
 * 
 * @param l
 * @param izPackEmbeddedFile
 * @param izPackEmbeddedHomeDir
 * @throws MojoExecutionException
 */
private void unpackIzPack(Log l, File izPackEmbeddedFile, File izPackEmbeddedHomeDir)
        throws MojoExecutionException {
    l.info("storing embedded IzPack installation in " + izPackEmbeddedFile);
    Utils.storeInputStream(IzPackPackager.class.getResourceAsStream(IZPACK_EMBEDDED_JAR), izPackEmbeddedFile,
            "IOException while unpacking embedded IzPack installation.");

    l.info("unzipping embedded IzPack installation to" + izPackEmbeddedHomeDir);
    int count = 0;
    ZipFile zip = null;
    try {
        zip = new ZipFile(izPackEmbeddedFile);
        Enumeration<? extends ZipEntry> e = zip.entries();

        while (e.hasMoreElements()) {
            count++;
            ZipEntry entry = (ZipEntry) e.nextElement();
            File unpacked = new File(izPackEmbeddedHomeDir, entry.getName());
            if (entry.isDirectory()) {
                unpacked.mkdirs(); // TODO: Check success.
            } else {
                Utils.createFile(unpacked, "Unable to create ZIP file entry ");
                Utils.storeInputStream(zip.getInputStream(entry), unpacked,
                        "IOException while unpacking ZIP file entry.");
            }
        }
    } catch (IOException ioe) {
        throw new MojoExecutionException("IOException while unpacking embedded IzPack installation.", ioe);
    } finally {
        if (zip != null) {
            try {
                zip.close();
            } catch (IOException e) {
                l.info(String.format("Error at closing zipfile %s caused by %s", izPackEmbeddedFile.getName(),
                        e.getMessage()));
            }
        }
    }
    l.info("unpacked " + count + " entries");
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.action.ArchiveExpander.java

private void expandZip(final File expandDir, final Archive archive, final QcContext context)
        throws IOException {

    ZipFile zipFile = null;
    BufferedOutputStream out = null;
    try {//from  ww w.  j  ava  2  s  .  co m
        zipFile = new ZipFile(archive.fullArchivePathAndName());
        // write each entry to the archive directory
        final Enumeration zipEnum = zipFile.entries();
        boolean foundArchiveDir = false;
        while (zipEnum.hasMoreElements()) {
            final ZipEntry entry = (ZipEntry) zipEnum.nextElement();
            if (!entry.isDirectory()) {
                String entryName = entry.getName();
                final File entryFile = new File(entryName);
                // extract out just the filename of the entry
                if (entryFile.getCanonicalPath().lastIndexOf(File.separator) != -1) {
                    entryName = entryFile.getCanonicalPath()
                            .substring(entryFile.getCanonicalPath().lastIndexOf(File.separator));
                }
                // the file to write is the archive dir plus just the filename
                final File archiveFile = new File(expandDir, entryName);
                InputStream in = zipFile.getInputStream(entry);
                FileOutputStream fout = new FileOutputStream(archiveFile);
                //noinspection IOResourceOpenedButNotSafelyClosed
                out = new BufferedOutputStream(fout);
                copyInputStream(in, out);
                in = null;
                out = null;
                fout.close();
                fout = null;

            } else {
                // if find a directory that isn't the archive name, add warning for weird archive structure
                if (!entry.getName().equals(archive.getArchiveName())
                        && !entry.getName().equals(archive.getArchiveName() + "/")) {
                    context.addWarning(new StringBuilder().append("Archive '")
                            .append("' has a non-standard directory '").append(entry.getName()).append("'.")
                            .append("Archive files should be contained inside a single directory with the archive name as its name.")
                            .toString());
                } else {
                    foundArchiveDir = true;
                }
            }
        }
        if (!foundArchiveDir) {
            context.addWarning(
                    "Archive files should be contained inside a single directory with the archive name as its name.");
        }
    } finally {
        IOUtils.closeQuietly(out);

        if (zipFile != null) {
            zipFile.close();
        }
    }
}

From source file:net.morematerials.manager.UpdateManager.java

private void updateSmp(File file) throws Exception {
    ZipFile smpFile = new ZipFile(file);
    Enumeration<? extends ZipEntry> entries = smpFile.entries();
    String smpName = file.getName().substring(0, file.getName().lastIndexOf("."));

    // First we need to know what files are in this .smp file, because the old format uses magic filename matching.
    ArrayList<String> containedFiles = new ArrayList<String>();
    HashMap<String, YamlConfiguration> materials = new HashMap<String, YamlConfiguration>();

    // Now we walk through the file once and store every file.
    ZipEntry entry;//from   w  w  w .  j a  v  a  2  s . co  m
    YamlConfiguration yaml;
    while (entries.hasMoreElements()) {
        entry = entries.nextElement();

        // Only if its a .yml file
        if (entry.getName().endsWith(".yml")) {
            // Load the .yml file
            yaml = new YamlConfiguration();
            yaml.load(smpFile.getInputStream(entry));

            // Texture is required for new package format.
            if (!yaml.contains("Texture")) {
                materials.put(entry.getName().substring(0, entry.getName().lastIndexOf(".")), yaml);
            } else {
                containedFiles.add(entry.getName());
            }
        } else {
            containedFiles.add(entry.getName());
        }
    }

    // If this map contains any entry, we need to convert something.
    if (materials.size() > 0) {
        this.plugin.getUtilsManager().log("Deprecated .smp found: " + file.getName() + ". Updating...");

        // We need a temporary directory to update the .smp in.
        this.tempDir.mkdir();

        // First extract all untouched assets:
        for (String filename : containedFiles) {
            InputStream in = smpFile.getInputStream(smpFile.getEntry(filename));
            OutputStream out = new FileOutputStream(new File(this.tempDir, filename));
            int read;
            byte[] bytes = new byte[1024];
            while ((read = in.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            out.flush();
            out.close();
            in.close();
        }

        // Now convert each .yml file in this archive.
        YamlConfiguration oldYaml;
        YamlConfiguration newYaml;
        for (String materialName : materials.keySet()) {
            oldYaml = materials.get(materialName);
            newYaml = new YamlConfiguration();

            // Required "Type" which is Block or Item. Old format didnt support Tools anyway.
            newYaml.set("Type", oldYaml.getString("Type"));
            // Title is now required and falls back to filename.
            newYaml.set("Title", oldYaml.getString("Title", materialName));

            // Now call the converter methods.
            if (newYaml.getString("Type").equals("Block")) {
                this.convertBlock(oldYaml, newYaml, materialName, containedFiles);
                this.convertBlockHandlers(oldYaml, newYaml);
            } else if (newYaml.getString("Type").equals("Item")) {
                this.convertItem(oldYaml, newYaml, materialName, containedFiles);
                this.convertItemHandlers(oldYaml, newYaml);
            }

            // Copy over recipes - nothing changed here!
            if (oldYaml.contains("Recipes")) {
                newYaml.set("Recipes", oldYaml.getList("Recipes"));
            }

            // Finally store the new .yml file.
            String yamlString = newYaml.saveToString();
            BufferedWriter out = new BufferedWriter(
                    new FileWriter(new File(this.tempDir, materialName + ".yml")));
            out.write(this.fixYamlProblems(yamlString));
            out.close();

            // Also update itemmap entry!
            for (Integer i = 0; i < this.itemMap.size(); i++) {
                String oldMaterial = this.itemMap.get(i).replaceAll("^[0-9]+:MoreMaterials.", "");
                if (oldMaterial.equals(newYaml.getString("Title"))) {
                    this.itemMap.set(i, this.itemMap.get(i).replaceAll("^([0-9]+:MoreMaterials.).+$",
                            "$1" + smpName + "." + materialName));
                    break;
                }
            }

            // And we need to tell SpoutPlugin that this material must be renamed!
            SpoutManager.getMaterialManager().renameMaterialKey(this.plugin, newYaml.getString("Title"),
                    smpName + "." + materialName);
        }

        // First remove old .smp file
        smpFile.close();
        file.delete();

        // Then repack the new .smp file
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file));
        for (File entryFile : this.tempDir.listFiles()) {
            FileInputStream in = new FileInputStream(entryFile);
            out.putNextEntry(new ZipEntry(entryFile.getName()));
            Integer len;
            byte[] buf = new byte[1024];
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            out.closeEntry();
            in.close();
        }
        out.close();

        // At last remove the temp directory.
        FileUtils.deleteDirectory(this.tempDir);
    } else {
        // At last, close the file handle.
        smpFile.close();
    }
}