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.denimgroup.threadfix.service.channel.SkipfishChannelImporter.java

private String findFolderName(ZipFile zipFile) {
    if (zipFile == null)
        return null;

    if (zipFile.entries() != null && zipFile.entries().hasMoreElements()) {
        String possibleMatch = zipFile.entries().nextElement().toString();
        if (possibleMatch.charAt(0) != '_' && possibleMatch.contains("/"))
            return possibleMatch.substring(0, possibleMatch.indexOf("/"));
    }/*from   ww  w  .  ja  va 2  s .c o m*/

    return null;
}

From source file:org.apache.maven.archetype.common.DefaultArchetypeArtifactManager.java

private ZipEntry searchEntry(ZipFile zipFile, String searchString) {
    getLogger().debug("Searching for " + searchString + " inside " + zipFile.getName());

    Enumeration<? extends ZipEntry> enu = zipFile.entries();
    while (enu.hasMoreElements()) {
        ZipEntry entryfound = (ZipEntry) enu.nextElement();
        getLogger().debug("  - " + entryfound.getName());

        if (searchString.equals(entryfound.getName())) {
            getLogger().debug("Entry found");
            return entryfound;
        }/*  w  w w. j a  va  2 s .c o m*/
    }
    return null;
}

From source file:com.rover12421.shaka.apktool.lib.AndrolibAj.java

private void copyExistingFiles(ZipFile inputFile, ZipOutputStream outputFile, Map<String, String> excludeFiles)
        throws IOException {
    // First, copy the contents from the existing outFile:
    Enumeration<? extends ZipEntry> entries = inputFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = new ZipEntry(entries.nextElement());
        if (excludeFiles.get(entry.getName()) != null) {
            //??.
            continue;
        }/*from www .j ava 2  s .  co m*/
        // We can't reuse the compressed size because it depends on compression sizes.
        entry.setCompressedSize(-1);
        outputFile.putNextEntry(entry);

        // No need to create directory entries in the final apk
        if (!entry.isDirectory()) {
            BrutIO.copy(inputFile, outputFile, entry);
        }

        outputFile.closeEntry();
    }
}

From source file:it.greenvulcano.util.zip.ZipHelper.java

/**
 * Performs the uncompression of a <code>zip</code> file, whose name and
 * parent directory are passed as arguments, on the local filesystem. The
 * content of the <code>zip</code> file will be uncompressed within a
 * specified target directory.<br>
 *
 * @param srcDirectory//w  w  w.j  av  a  2s . c o m
 *            the source parent directory of the file/s to be unzipped. Must
 *            be an absolute pathname.
 * @param zipFilename
 *            the name of the file to be unzipped. Cannot contain wildcards.
 * @param targetDirectory
 *            the target directory in which the content of the
 *            <code>zip</code> file will be unzipped. Must be an absolute
 *            pathname.
 * @throws IOException
 *             If any error occurs during file uncompression.
 * @throws IllegalArgumentException
 *             if the arguments are invalid.
 */
public void unzipFile(String srcDirectory, String zipFilename, String targetDirectory) throws IOException {

    File srcDir = new File(srcDirectory);

    if (!srcDir.isAbsolute()) {
        throw new IllegalArgumentException(
                "The pathname of the source parent directory is NOT absolute: " + srcDirectory);
    }

    if (!srcDir.exists()) {
        throw new IllegalArgumentException(
                "Source parent directory " + srcDirectory + " NOT found on local filesystem.");
    }

    if (!srcDir.isDirectory()) {
        throw new IllegalArgumentException("Source parent directory " + srcDirectory + " is NOT a directory.");
    }

    File srcZipFile = new File(srcDirectory, zipFilename);
    if (!srcZipFile.exists()) {
        throw new IllegalArgumentException(
                "File to be unzipped (" + srcZipFile.getAbsolutePath() + ") NOT found on local filesystem.");
    }

    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(srcZipFile);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry currEntry = entries.nextElement();
            if (currEntry.isDirectory()) {
                String targetSubdirPathname = currEntry.getName();
                File dir = new File(targetDirectory, targetSubdirPathname);
                FileUtils.forceMkdir(dir);
                dir.setLastModified(currEntry.getTime());
            } else {
                InputStream is = null;
                OutputStream os = null;
                File file = null;
                try {
                    is = zipFile.getInputStream(currEntry);
                    FileUtils.forceMkdir(new File(targetDirectory, currEntry.getName()).getParentFile());
                    file = new File(targetDirectory, currEntry.getName());
                    os = new FileOutputStream(file);
                    IOUtils.copy(is, os);
                } finally {
                    try {
                        if (is != null) {
                            is.close();
                        }

                        if (os != null) {
                            os.close();
                        }
                    } catch (IOException exc) {
                        // Do nothing
                    }

                    if (file != null) {
                        file.setLastModified(currEntry.getTime());
                    }
                }
            }
        }
    } finally {
        try {
            if (zipFile != null) {
                zipFile.close();
            }
        } catch (Exception exc) {
            // do nothing
        }
    }
}

From source file:org.apache.maven.archetype.common.DefaultArchetypeArtifactManager.java

public Model getArchetypePom(File jar) throws XmlPullParserException, UnknownArchetype, IOException {
    ZipFile zipFile = null;
    try {//from   w w  w  .  jav a  2 s  .c  o  m
        String pomFileName = null;
        zipFile = getArchetypeZipFile(jar);

        Enumeration<? extends ZipEntry> enumeration = zipFile.entries();
        while (enumeration.hasMoreElements()) {
            ZipEntry el = (ZipEntry) enumeration.nextElement();

            String entry = el.getName();
            if (entry.startsWith("META-INF") && entry.endsWith("pom.xml")) {
                pomFileName = entry;
            }
        }

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

        ZipEntry pom = zipFile.getEntry(pomFileName);

        if (pom == null) {
            return null;
        }
        return pomManager.readPom(zipFile.getInputStream(pom));
    } finally {
        closeZipFile(zipFile);
    }
}

From source file:net.minecraftforge.gradle.util.ZipFileTree.java

public void visit(FileVisitor visitor) {
    if (!zipFile.exists()) {
        DeprecationLogger.nagUserOfDeprecatedBehaviour(String.format(
                "The specified zip file %s does not exist and will be silently ignored", getDisplayName()));
        return;//from   www . ja  va  2s .co m
    }
    if (!zipFile.isFile()) {
        throw new InvalidUserDataException(
                String.format("Cannot expand %s as it is not a file.", getDisplayName()));
    }

    AtomicBoolean stopFlag = new AtomicBoolean();

    try {
        ZipFile zip = new ZipFile(zipFile);
        try {
            // The iteration order of zip.getEntries() is based on the hash of the zip entry. This isn't much use
            // to us. So, collect the entries in a map and iterate over them in alphabetical order.
            Map<String, ZipEntry> entriesByName = new TreeMap<String, ZipEntry>();
            Enumeration<? extends ZipEntry> entries = zip.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                entriesByName.put(entry.getName(), entry);
            }
            Iterator<ZipEntry> sortedEntries = entriesByName.values().iterator();
            while (!stopFlag.get() && sortedEntries.hasNext()) {
                ZipEntry entry = sortedEntries.next();
                if (entry.isDirectory()) {
                    visitor.visitDir(new DetailsImpl(entry, zip, stopFlag));
                } else {
                    visitor.visitFile(new DetailsImpl(entry, zip, stopFlag));
                }
            }
        } finally {
            zip.close();
        }
    } catch (Exception e) {
        throw new GradleException(String.format("Could not expand %s.", getDisplayName()), e);
    }
}

From source file:fr.paris.lutece.plugins.updater.service.UpdateService.java

/**
 * Extract a package// w  ww. j  a  v  a2 s.c  om
 * @param strZipFile The package zip file
 * @param strDirectory The target directory
 * @throws UpdaterDownloadException If an exception occurs during download
 */
private void extractPackage(String strZipFile, String strDirectory) throws UpdaterDownloadException {
    try {
        File file = new File(strZipFile);
        ZipFile zipFile = new ZipFile(file);

        // Each zipped file is indentified by a zip entry :
        Enumeration zipEntries = zipFile.entries();

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

            // Clean the name :
            String strEntryName = zipEntry.getName();

            // The unzipped file :
            File destFile = new File(strDirectory, strEntryName);

            // Create the parent directory structure if needed :
            destFile.getParentFile().mkdirs();

            if (!zipEntry.isDirectory()) {
                // InputStream from zipped data
                InputStream inZipStream = null;

                try {
                    AppLogService.debug("unzipping " + strEntryName + " to " + destFile.getName());
                    inZipStream = zipFile.getInputStream(zipEntry);

                    // OutputStream to the destination file
                    OutputStream outDestStream = new FileOutputStream(destFile);

                    // Helper method to copy data
                    copyStream(inZipStream, outDestStream);

                    inZipStream.close();
                    outDestStream.close();
                } catch (IOException e) {
                    AppLogService.error("Error extracting file : " + e.getMessage(), e);
                } finally {
                    try {
                        inZipStream.close();
                    } catch (IOException e) {
                        AppLogService.error("Error extracting file : " + e.getMessage(), e);
                    }
                }
            } else {
                AppLogService.debug("skipping directory " + strEntryName);
            }
        }
    } catch (ZipException e) {
        AppLogService.error("Error extracting file : " + e.getMessage(), e);
        throw new UpdaterDownloadException("Error extracting package ", e);
    } catch (IOException e) {
        AppLogService.error("Error extracting file : " + e.getMessage(), e);
    }
}

From source file:org.liberty.android.fantastischmemopro.downloader.DownloaderAnyMemo.java

private void downloadDatabase(final DownloadItem di) throws Exception {
    String filename = di.getExtras("filename");
    if (filename == null) {
        throw new Exception("Could not get filename");
    }/*from   w ww . j a  va2 s .co m*/

    String sdpath = Environment.getExternalStorageDirectory().getAbsolutePath()
            + getString(R.string.default_dir);
    File outFile = new File(sdpath + filename);
    mHandler.post(new Runnable() {
        public void run() {
            mProgressDialog = new ProgressDialog(DownloaderAnyMemo.this);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setMessage(getString(R.string.loading_downloading));
            mProgressDialog.show();

        }
    });
    try {
        OutputStream out;
        if (outFile.exists()) {
            throw new IOException("Database already exist!");
        }
        try {
            outFile.createNewFile();
            out = new FileOutputStream(outFile);

            URL myURL = new URL(di.getAddress());
            Log.v(TAG, "URL IS: " + myURL);
            URLConnection ucon = myURL.openConnection();
            final int fileSize = ucon.getContentLength();
            mHandler.post(new Runnable() {
                public void run() {
                    mProgressDialog.setMax(fileSize);
                }
            });

            byte[] buf = new byte[8192];

            InputStream is = ucon.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is, 8192);
            Runnable increaseProgress = new Runnable() {
                public void run() {
                    mProgressDialog.setProgress(mDownloadProgress);
                }
            };
            int len = 0;
            int lenSum = 0;
            while ((len = bis.read(buf)) != -1) {
                out.write(buf, 0, len);
                lenSum += len;
                if (lenSum > fileSize / 50) {
                    /* This is tricky.
                     * The UI thread can not be updated too often.
                     * So we update it only 50 times
                     */
                    mDownloadProgress += lenSum;
                    lenSum = 0;
                    mHandler.post(increaseProgress);
                }
            }
            out.close();
            is.close();
            /* Uncompress the zip file that contains images */
            if (filename.endsWith(".zip")) {
                mHandler.post(new Runnable() {
                    public void run() {
                        mProgressDialog.setProgress(fileSize);
                        mProgressDialog.setMessage(getString(R.string.downloader_extract_zip));
                    }
                });

                BufferedOutputStream dest = null;
                BufferedInputStream ins = null;
                ZipEntry entry;
                ZipFile zipfile = new ZipFile(outFile);
                Enumeration<?> e = zipfile.entries();
                while (e.hasMoreElements()) {
                    entry = (ZipEntry) e.nextElement();
                    Log.v(TAG, "Extracting: " + entry);
                    if (entry.isDirectory()) {
                        new File(sdpath + "/" + entry.getName()).mkdir();
                    } else {
                        ins = new BufferedInputStream(zipfile.getInputStream(entry), 8192);
                        int count;
                        byte data[] = new byte[8192];
                        FileOutputStream fos = new FileOutputStream(sdpath + "/" + entry.getName());
                        dest = new BufferedOutputStream(fos, 8192);
                        while ((count = ins.read(data, 0, 8192)) != -1) {
                            dest.write(data, 0, count);
                        }
                        dest.flush();
                        dest.close();
                        ins.close();
                    }
                }
                /* Delete the zip file if it is successfully decompressed */
                outFile.delete();
            }
            /* We do not check ttf file as db */
            if (!filename.toLowerCase().endsWith(".ttf")) {
                /* Check if the db is correct */
                filename = filename.replace(".zip", ".db");
                DatabaseHelper dh = new DatabaseHelper(DownloaderAnyMemo.this, sdpath, filename);
                dh.close();
            }
        } catch (Exception e) {
            if (outFile.exists()) {
                outFile.delete();
            }
            throw new Exception(e);
        }

    } catch (Exception e) {
        Log.e(TAG, "Error downloading", e);
        throw new Exception(e);
    } finally {
        mHandler.post(new Runnable() {
            public void run() {
                mProgressDialog.dismiss();
            }
        });
    }

}

From source file:com.github.chenxiaolong.dualbootpatcher.switcher.service.BootUIActionTask.java

/**
 * Get currently installed version of boot UI
 *
 * @param iface Mbtool interface/*www .j  av a 2 s  . c o m*/
 * @return The {@link Version} installed or null if an error occurs or the version number is
 *         invalid
 * @throws IOException
 * @throws MbtoolException
 */
@Nullable
private Version getCurrentVersion(MbtoolInterface iface) throws IOException, MbtoolException {
    String mountPoint = getCacheMountPoint(iface);
    String zipPath = mountPoint + MAPPINGS[0].target;

    File tempZip = new File(getContext().getCacheDir() + "/bootui.zip");
    tempZip.delete();

    try {
        iface.pathCopy(zipPath, tempZip.getAbsolutePath());
        iface.pathChmod(tempZip.getAbsolutePath(), 0644);

        // Set SELinux label
        try {
            String label = iface.pathSelinuxGetLabel(tempZip.getParent(), false);
            iface.pathSelinuxSetLabel(tempZip.getAbsolutePath(), label, false);
        } catch (MbtoolCommandException e) {
            Log.w(TAG, tempZip + ": Failed to set SELinux label", e);
        }
    } catch (MbtoolCommandException e) {
        return null;
    }

    ZipFile zf = null;
    String versionStr = null;
    String gitVersionStr = null;

    try {
        zf = new ZipFile(tempZip);

        final Enumeration<? extends ZipEntry> entries = zf.entries();
        while (entries.hasMoreElements()) {
            final ZipEntry ze = entries.nextElement();

            if (ze.getName().equals(PROPERTIES_FILE)) {
                Properties prop = new Properties();
                prop.load(zf.getInputStream(ze));
                versionStr = prop.getProperty(PROP_VERSION);
                gitVersionStr = prop.getProperty(PROP_GIT_VERSION);
                break;
            }
        }
    } catch (IOException e) {
        Log.e(TAG, "Failed to read bootui.zip", e);
    } finally {
        if (zf != null) {
            try {
                zf.close();
            } catch (IOException e) {
                // Ignore
            }
        }

        tempZip.delete();
    }

    Log.d(TAG, "Boot UI version: " + versionStr);
    Log.d(TAG, "Boot UI git version: " + gitVersionStr);

    if (versionStr != null) {
        return Version.from(versionStr);
    } else {
        return null;
    }
}

From source file:org.pentaho.platform.dataaccess.datasource.wizard.service.impl.DatasourceResourceIT.java

@Test
public void testMondrianImportExport() throws Exception {
    final String domainName = "SalesData";
    List<IMimeType> mimeTypeList = new ArrayList<IMimeType>();
    mimeTypeList.add(new MimeType("Mondrian", "mondrian.xml"));
    System.setProperty("org.osjava.sj.root", "test-res/solution1/system/simple-jndi"); //$NON-NLS-1$ //$NON-NLS-2$

    File mondrian = new File("test-res/dsw/testData/SalesData.mondrian.xml");
    RepositoryFile repoMondrianFile = new RepositoryFile.Builder(mondrian.getName()).folder(false).hidden(false)
            .build();/*from   w  ww. java 2s  . c  om*/
    RepositoryFileImportBundle bundle1 = new RepositoryFileImportBundle.Builder().file(repoMondrianFile)
            .charSet("UTF-8").input(new FileInputStream(mondrian)).mime("mondrian.xml")
            .withParam("parameters", "Datasource=Pentaho;overwrite=true").withParam("domain-id", "SalesData")
            .build();
    MondrianImportHandler mondrianImportHandler = new MondrianImportHandler(mimeTypeList,
            PentahoSystem.get(IMondrianCatalogService.class));
    mondrianImportHandler.importFile(bundle1);

    try {
        KettleEnvironment.init();
        Props.init(Props.TYPE_PROPERTIES_EMPTY);
    } catch (Exception e) {
        // may already be initialized by another test
    }

    Domain domain = generateModel();

    ModelerWorkspace model = new ModelerWorkspace(new GwtModelerWorkspaceHelper());
    model.setModelName("ORDERS");
    model.setDomain(domain);
    model.getWorkspaceHelper().populateDomain(model);

    new ModelerService().serializeModels(domain, domainName);

    final Response salesData = new DataSourceWizardResource().doGetDSWFilesAsDownload(domainName + ".xmi");
    Assert.assertEquals(salesData.getStatus(), Response.Status.OK.getStatusCode());
    Assert.assertNotNull(salesData.getMetadata());
    Assert.assertNotNull(salesData.getMetadata().getFirst("Content-Disposition"));
    Assert.assertEquals(salesData.getMetadata().getFirst("Content-Disposition").getClass(), String.class);
    Assert.assertTrue(
            ((String) salesData.getMetadata().getFirst("Content-Disposition")).endsWith(domainName + ".zip\""));

    File file = File.createTempFile(domainName, ".zip");
    final FileOutputStream fileOutputStream = new FileOutputStream(file);
    ((StreamingOutput) salesData.getEntity()).write(fileOutputStream);
    fileOutputStream.close();

    final ZipFile zipFile = new ZipFile(file);
    final Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        final ZipEntry zipEntry = entries.nextElement();
        Assert.assertTrue(zipEntry.getName().equals(domainName + ".xmi")
                || zipEntry.getName().equals(domainName + ".mondrian.xml"));
    }
    zipFile.close();
    file.delete();
}