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.zilverline.service.CollectionManagerImpl.java

/**
 * unZips a given zip file into cache directory with derived name. e.g. c:\temp\file.zip wil be unziiped into
 * [cacheDir]\file_zip\.//from  w ww.  j  av a 2  s. c  o m
 * 
 * @param sourceZipFile the ZIP file to be unzipped
 * @param thisCollection the collection whose cache and contenDir is used
 * 
 * @return File (new) directory containing zip file
 */
public static File unZip(final File sourceZipFile, final FileSystemCollection thisCollection) {
    // specify buffer size for extraction
    final int aBUFFER = 2048;
    File unzipDestinationDirectory = null;
    ZipFile zipFile = null;
    FileOutputStream fos = null;
    BufferedOutputStream dest = null;
    BufferedInputStream bis = null;

    try {
        // Specify destination where file will be unzipped
        unzipDestinationDirectory = file2CacheDir(sourceZipFile, thisCollection);
        log.info("unzipping " + sourceZipFile + " into " + unzipDestinationDirectory);
        // Open Zip file for reading
        zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);
        // Create an enumeration of the entries in the zip file
        Enumeration zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            // grab a zip file entry
            ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
            String currentEntry = entry.getName();
            log.debug("Extracting: " + entry);
            File destFile = new File(unzipDestinationDirectory, currentEntry);
            // grab file's parent directory structure
            File destinationParent = destFile.getParentFile();
            // create the parent directory structure if needed
            destinationParent.mkdirs();
            // extract file if not a directory
            if (!entry.isDirectory()) {
                bis = new BufferedInputStream(zipFile.getInputStream(entry));
                int currentByte;
                // establish buffer for writing file
                byte[] data = new byte[aBUFFER];
                // write the current file to disk
                fos = new FileOutputStream(destFile);
                dest = new BufferedOutputStream(fos, aBUFFER);
                // read and write until last byte is encountered
                while ((currentByte = bis.read(data, 0, aBUFFER)) != -1) {
                    dest.write(data, 0, currentByte);
                }
                dest.flush();
                dest.close();
                bis.close();
            }
        }
        zipFile.close();
        // delete the zip file if it is in the cache, we don't need to store
        // it, since we've extracted the contents
        if (FileUtils.isIn(sourceZipFile, thisCollection.getCacheDirWithManagerDefaults())) {
            sourceZipFile.delete();
        }
    } catch (Exception e) {
        log.error("Can't unzip: " + sourceZipFile, e);
    } finally {
        try {
            if (fos != null) {
                fos.close();
            }
            if (dest != null) {
                dest.close();
            }
            if (bis != null) {
                bis.close();
            }
        } catch (IOException e1) {
            log.error("Error closing files", e1);
        }
    }

    return unzipDestinationDirectory;
}

From source file:org.alfresco.repo.web.scripts.custommodel.CustomModelImportTest.java

public void testNotZipFileUpload() throws Exception {
    File file = getResourceFile("validModel.zip");
    ZipFile zipFile = new ZipFile(file);
    ZipEntry zipEntry = zipFile.entries().nextElement();

    File unzippedModelFile = TempFileProvider.createTempFile(zipFile.getInputStream(zipEntry), "validModel",
            ".xml");
    tempFiles.add(unzippedModelFile);/* w  w  w  . j av a  2  s  .c  om*/
    zipFile.close();

    PostRequest postRequest = buildMultipartPostRequest(unzippedModelFile);
    sendRequest(postRequest, 400); // CMM upload supports only zip file.
}

From source file:net.solarnetwork.node.backup.FileSystemBackupService.java

@Override
public BackupResourceIterable getBackupResources(Backup backup) {
    final File archiveFile = new File(backupDir, String.format(ARCHIVE_KEY_NAME_FORMAT, backup.getKey()));
    if (!(archiveFile.isFile() && archiveFile.canRead())) {
        log.warn("No backup archive exists for key [{}]", backup.getKey());
        Collection<BackupResource> col = Collections.emptyList();
        return new CollectionBackupResourceIterable(col);
    }//from w w  w.j  av a2 s.com
    try {
        final ZipFile zf = new ZipFile(archiveFile);
        Enumeration<? extends ZipEntry> entries = zf.entries();
        List<BackupResource> result = new ArrayList<BackupResource>(20);
        while (entries.hasMoreElements()) {
            result.add(new ZipEntryBackupResource(zf, entries.nextElement()));
        }
        return new CollectionBackupResourceIterable(result) {

            @Override
            public void close() throws IOException {
                zf.close();
            }

        };
    } catch (IOException e) {
        log.error("Error extracting backup archive entries: {}", e.getMessage());
    }
    Collection<BackupResource> col = Collections.emptyList();
    return new CollectionBackupResourceIterable(col);
}

From source file:com.josue.lottery.eap.service.core.LotoImporter.java

private void readZip(File file) {

    ZipFile zipFile = null;
    try {//w  w w  .ja  va 2  s . c  o m
        logger.info("unzipping ************");

        zipFile = new ZipFile(file);

        File dataDir = new File(System.getProperty("jboss.server.data.dir"));
        File dest = new File(dataDir, "deziped.htm");

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

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.getName().endsWith(".HTM")) {

                InputStream stream = zipFile.getInputStream(entry);
                OutputStream oStr = null;
                try {
                    oStr = new FileOutputStream(dest);
                    IOUtils.copy(stream, oStr);

                    parseHtml(dest);

                } catch (IOException e) {
                    throw new RuntimeException(e);
                } finally {
                    IOUtils.closeQuietly(oStr);
                }
            }

        }
    } catch (IOException ex) {
        logger.error(ex);
    } finally {
        try {
            zipFile.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:com.enioka.jqm.tools.LibraryResolverFS.java

private void loadCache(Node node, JobDef jd, EntityManager em) throws JqmPayloadException {
    jqmlogger.debug("Resolving classpath for job definition " + jd.getApplicationName());

    File jarFile = new File(FilenameUtils.concat(new File(node.getRepo()).getAbsolutePath(), jd.getJarPath()));
    File jarDir = jarFile.getParentFile();
    File libDir = new File(FilenameUtils.concat(jarDir.getAbsolutePath(), "lib"));
    File libDirExtracted = new File(FilenameUtils.concat(jarDir.getAbsolutePath(), "libFromJar"));
    File pomFile = new File(FilenameUtils.concat(jarDir.getAbsolutePath(), "pom.xml"));

    if (!jarFile.canRead()) {
        jqmlogger.warn("Cannot read file at " + jarFile.getAbsolutePath()
                + ". Job instance will crash. Check job definition or permissions on file.");
        throw new JqmPayloadException("File " + jarFile.getAbsolutePath() + " cannot be read");
    }/*from w  w  w .  ja  v  a2 s .  c om*/

    // POM file should be deleted if it comes from the jar file. Otherwise, it would stay into place and modifications to the internal
    // pom would be ignored.
    boolean pomFromJar = false;

    // 1st: if no pom, no lib dir => find a pom inside the JAR. (& copy it, we will read later)
    if (!pomFile.exists() && !libDir.exists()) {
        jqmlogger.trace("No pom inside jar directory. Checking for a pom inside the jar file");
        InputStream is = null;
        FileOutputStream os = null;
        ZipFile zf = null;

        try {
            zf = new ZipFile(jarFile);
            Enumeration<? extends ZipEntry> zes = zf.entries();
            while (zes.hasMoreElements()) {
                ZipEntry ze = zes.nextElement();
                if (ze.getName().endsWith("pom.xml")) {

                    is = zf.getInputStream(ze);
                    os = new FileOutputStream(pomFile);
                    IOUtils.copy(is, os);
                    pomFromJar = true;
                    break;
                }
            }
        } catch (Exception e) {
            throw new JqmPayloadException("Could not handle pom inside jar", e);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
            Helpers.closeQuietly(zf);
        }
    }

    // 2nd: no pom, no pom inside jar, no lib dir => find a lib dir inside the jar
    if (!pomFile.exists() && !libDir.exists()) {
        jqmlogger.trace("Checking for a lib directory inside jar");
        InputStream is = null;
        FileOutputStream os = null;
        ZipFile zf = null;
        FileUtils.deleteQuietly(libDirExtracted);

        try {
            zf = new ZipFile(jarFile);
            Enumeration<? extends ZipEntry> zes = zf.entries();
            while (zes.hasMoreElements()) {
                ZipEntry ze = zes.nextElement();
                if (ze.getName().startsWith("lib/") && ze.getName().endsWith(".jar")) {
                    if (!libDirExtracted.isDirectory() && !libDirExtracted.mkdir()) {
                        throw new JqmPayloadException("Could not extract libraries from jar");
                    }

                    is = zf.getInputStream(ze);
                    os = new FileOutputStream(FilenameUtils.concat(libDirExtracted.getAbsolutePath(),
                            FilenameUtils.getName(ze.getName())));
                    IOUtils.copy(is, os);
                }
            }
        } catch (Exception e) {
            throw new JqmPayloadException("Could not handle internal lib directory", e);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
            Helpers.closeQuietly(zf);
        }

        // If libs were extracted, put in cache and return
        if (libDirExtracted.isDirectory()) {
            FileFilter fileFilter = new WildcardFileFilter("*.jar");
            File[] files = libDirExtracted.listFiles(fileFilter);
            URL[] libUrls = new URL[files.length];
            try {
                for (int i = 0; i < files.length; i++) {
                    libUrls[i] = files[i].toURI().toURL();
                }
            } catch (Exception e) {
                throw new JqmPayloadException("Could not handle internal lib directory", e);
            }

            // Put in cache
            putInCache(libUrls, jd.getApplicationName());
            return;
        }
    }

    // 3rd: if pom, use pom!
    if (pomFile.exists() && !libDir.exists()) {
        jqmlogger.trace("Reading a pom file");

        ConfigurableMavenResolverSystem resolver = LibraryResolverMaven.getMavenResolver(em);

        // Resolve
        File[] depFiles = null;
        try {
            depFiles = resolver.loadPomFromFile(pomFile).importRuntimeDependencies().resolve()
                    .withTransitivity().asFile();
        } catch (IllegalArgumentException e) {
            // Happens when no dependencies inside pom, which is a weird use of the feature...
            jqmlogger.trace("No dependencies inside pom.xml file - no libs will be used", e);
            depFiles = new File[0];
        }

        // Extract results
        URL[] tmp = LibraryResolverMaven.extractMavenResults(depFiles);

        // Put in cache
        putInCache(tmp, jd.getApplicationName());

        // Cleanup
        if (pomFromJar && !pomFile.delete()) {
            jqmlogger.warn("Could not delete the temp pom file extracted from the jar.");
        }
        return;
    }

    // 4: if lib, use lib... (lib has priority over pom)
    if (libDir.exists()) {
        jqmlogger.trace(
                "Using the lib directory " + libDir.getAbsolutePath() + " as the source for dependencies");
        FileFilter fileFilter = new WildcardFileFilter("*.jar");
        File[] files = libDir.listFiles(fileFilter);
        URL[] tmp = new URL[files.length];
        for (int i = 0; i < files.length; i++) {
            try {
                tmp[i] = files[i].toURI().toURL();
            } catch (MalformedURLException e) {
                throw new JqmPayloadException("incorrect file inside lib directory", e);
            }
        }

        // Put in cache
        putInCache(tmp, jd.getApplicationName());
        return;
    }

    throw new JqmPayloadException(
            "There is no lib dir or no pom.xml inside the directory containing the jar or inside the jar. The jar cannot be launched.");
}

From source file:io.jxcore.node.jxcore.java

private void Initialize(String home) {
    // assets.list is terribly slow, trick below is literally 100 times faster
    StringBuilder assets = new StringBuilder();
    assets.append("{");
    boolean first_entry = true;
    try {/*from   w w w  .  j a  va  2s  .c om*/
        ZipFile zf = new ZipFile(activity.getBaseContext().getApplicationInfo().sourceDir);
        try {
            for (Enumeration<? extends ZipEntry> e = zf.entries(); e.hasMoreElements();) {
                ZipEntry ze = e.nextElement();
                String name = ze.getName();
                if (name.startsWith("assets/www/jxcore/")) {
                    if (first_entry)
                        first_entry = false;
                    else
                        assets.append(",");
                    int size = FileManager.aproxFileSize(name.substring(7));
                    assets.append("\"" + name.substring(18) + "\":" + size);
                }
            }
        } finally {
            zf.close();
        }
    } catch (Exception e) {
    }
    assets.append("}");

    prepareEngine(home + "/www/jxcore", assets.toString());

    String mainFile = FileManager.readFile("jxcore_cordova.js");

    String data = "process.setPaths = function(){ process.cwd = function() { return '" + home
            + "/www/jxcore';};\n" + "process.userPath ='"
            + activity.getBaseContext().getFilesDir().getAbsolutePath() + "';\n" + "};" + mainFile;

    defineMainFile(data);

    startEngine();

    jxcoreInitialized = true;
}

From source file:org.bigbluebuttonproject.fileupload.document.ZipDocumentHandler.java

/**
 * This method extracts the zip file given to the destDir. It uses ZipFile API
 * to parse through the files in the zip file.
 * Only files that the zip file can have are .jpg, .png and .gif formats.
 * //  ww w. ja  v  a 2 s. c  o  m
 * @param fileInput pointing to the zip file
 * @param destDir directory where extracted files should go
 */
public void convert(File fileInput, File destDir) {
    try {
        // Setup the ZipFile used to read entries
        ZipFile zf = new ZipFile(fileInput.getAbsolutePath());

        // Ensure the extraction directories exist
        //            File directoryStructure = new File(destDir);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }

        // Loop through all entries in the zip and extract as necessary
        ZipEntry currentEntry;
        for (Enumeration entries = zf.entries(); entries.hasMoreElements();) {
            currentEntry = (ZipEntry) entries.nextElement();

            if (!currentEntry.isDirectory()) {
                File fileEntry = new File(currentEntry.getName());
                String fileName = fileEntry.getName().toLowerCase();
                // Make sure to only deal with image files
                if ((fileName.endsWith(".jpg")) || (fileName.endsWith(".png")) || (fileName.endsWith(".gif"))) {
                    // extracts the corresponding file in dest Directory
                    copyInputStream(zf.getInputStream(currentEntry), new BufferedOutputStream(
                            new FileOutputStream(destDir + File.separator + fileEntry.getName())));
                }
            }
        }
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("Could not load zip document for " + fileInput.getName(), e);
        }
    }
}

From source file:mobac.mapsources.loader.MapPackManager.java

/**
 * Calculate the md5sum on all files in the map pack file (except those in META-INF) and their filenames inclusive
 * path in the map pack file).//from  ww w .j av a2s  .  com
 * 
 * @param mapPackFile
 * @return
 * @throws IOException
 * @throws NoSuchAlgorithmException
 */
public String generateMappackMD5(File mapPackFile) throws IOException, NoSuchAlgorithmException {
    ZipFile zip = new ZipFile(mapPackFile);
    try {
        Enumeration<? extends ZipEntry> entries = zip.entries();
        MessageDigest md5Total = MessageDigest.getInstance("MD5");
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();

            if (entry.isDirectory())
                continue;
            // Do not hash files from META-INF
            String name = entry.getName();
            if (name.toUpperCase().startsWith("META-INF"))
                continue;
            md5.reset();
            InputStream in = zip.getInputStream(entry);
            byte[] data = Utilities.getInputBytes(in);
            in.close();
            // name = name.replaceAll("\\\\", "/");
            byte[] digest = md5.digest(data);
            log.trace("Hashsum " + Hex.encodeHexString(digest) + " includes \"" + name + "\"");
            md5Total.update(digest);
            md5Total.update(name.getBytes());
        }
        String md5sum = Hex.encodeHexString(md5Total.digest());
        log.trace("md5sum of " + mapPackFile.getName() + ": " + md5sum);
        return md5sum;
    } finally {
        zip.close();
    }
}

From source file:com.wolvereness.overmapped.OverMapped.java

private void readClasses(final MultiProcessor executor, final Map<String, ByteClass> byteClasses,
        final List<Pair<ZipEntry, byte[]>> fileEntries)
        throws ZipException, IOException, InterruptedException, ExecutionException, MojoFailureException {
    final List<Future<ByteClass>> classBuffer = newArrayList();
    final List<Future<Pair<ZipEntry, byte[]>>> fileBuffer = newArrayList();

    final ZipFile zipInput = new ZipFile(input);
    final Enumeration<? extends ZipEntry> zipEntries = zipInput.entries();
    while (zipEntries.hasMoreElements()) {
        final ZipEntry zipEntry = zipEntries.nextElement();
        if (ByteClass.isClass(zipEntry.getName())) {
            classBuffer.add(executor.submit(new Callable<ByteClass>() {
                @Override// w  w w  .j  av a 2s  .com
                public ByteClass call() throws Exception {
                    return new ByteClass(zipEntry.getName(), zipInput.getInputStream(zipEntry));
                }
            }));
        } else {
            fileBuffer.add(executor.submit(new Callable<Pair<ZipEntry, byte[]>>() {
                @Override
                public Pair<ZipEntry, byte[]> call() throws Exception {
                    return new ImmutablePair<ZipEntry, byte[]>(new ZipEntry(zipEntry),
                            ByteStreams.toByteArray(zipInput.getInputStream(zipEntry)));
                }
            }));
        }
    }

    for (final Future<Pair<ZipEntry, byte[]>> file : fileBuffer) {
        fileEntries.add(file.get());
    }
    for (final Future<ByteClass> clazzFuture : classBuffer) {
        ByteClass clazz = clazzFuture.get();
        clazz = byteClasses.put(clazz.getToken(), clazz);
        if (clazz != null)
            throw new MojoFailureException(
                    String.format("Duplicate class definition %s - %s", clazz, clazzFuture.get()));
    }

    zipInput.close();
}

From source file:com.denimgroup.threadfix.importer.impl.upload.SkipfishChannelImporter.java

private String findFolderName(@Nonnull ZipFile zipFile) {

    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 w ww  . j  a  va2 s.  c o m

    return null;
}