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:io.github.wysohn.triggerreactor.tools.ReflectionUtil.java

public static List<String> getAllClasses(ClassLoader cl, String packageName) {
    packageName = packageName.replace('.', '/');

    List<String> classes = new ArrayList<>();

    URL[] urls = ((URLClassLoader) cl).getURLs();
    for (URL url : urls) {
        //System.out.println(url.getFile());
        File jar = new File(url.getFile());

        if (jar.isDirectory()) {
            File subdir = new File(jar, packageName);
            if (!subdir.exists())
                continue;
            File[] files = subdir.listFiles();
            for (File file : files) {
                if (!file.isFile())
                    continue;
                if (file.getName().endsWith(".class"))
                    classes.add(file.getName().substring(0, file.getName().length() - 6).replace('/', '.'));
            }//w  ww  .j  av a 2  s.  c  o  m
        }

        else {
            // try to open as ZIP
            try {
                ZipFile zip = new ZipFile(jar);
                for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {
                    ZipEntry entry = entries.nextElement();
                    String name = entry.getName();
                    if (!name.startsWith(packageName))
                        continue;
                    if (name.endsWith(".class") && name.indexOf('$') < 0)
                        classes.add(name.substring(0, name.length() - 6).replace('/', '.'));
                }
                zip.close();
            } catch (ZipException e) {
                //System.out.println("Not a ZIP: " + e.getMessage());
            } catch (IOException e) {
                System.err.println(e.getMessage());
            }
        }
    }

    return classes;
}

From source file:gdt.data.entity.facet.ExtensionHandler.java

public static InputStream getResourceStream(Entigrator entigrator, String extension$, String resource$) {
    try {// w w w .  j a  v a 2s . co m

        System.out.println(
                "ExtensionHandler:getResourceStream:extension=" + extension$ + " resource=" + resource$);
        Sack extension = entigrator.getEntityAtKey(extension$);
        String lib$ = extension.getElementItemAt("field", "lib");
        String jar$ = entigrator.getEntihome() + "/" + extension$ + "/" + lib$;
        //      System.out.println("ExtensionHandler:loadIcon:jar="+jar$);
        ZipFile zf = new ZipFile(jar$);
        Enumeration<? extends ZipEntry> entries = zf.entries();
        ZipEntry ze;
        String[] sa;
        while (entries.hasMoreElements()) {
            try {
                ze = entries.nextElement();
                sa = ze.getName().split("/");
                //     System.out.println("ExtensionHandler:loadIcon:zip entry="+sa[sa.length-1]);
                if (resource$.equals(sa[sa.length - 1])) {
                    InputStream is = zf.getInputStream(ze);
                    if (is != null)
                        return is;

                }
            } catch (Exception e) {

            }
        }
        return null;
    } catch (Exception e) {
        Logger.getLogger(ExtensionHandler.class.getName()).severe(e.toString());
        return null;
    }

}

From source file:gdt.data.entity.facet.ExtensionHandler.java

public static String loadIcon(Entigrator entigrator, String extension$, String resource$) {
    try {/*from   www  .j  av  a2 s  .  c  om*/

        //System.out.println("ExtensionHandler:loadIcon:extension="+extension$+" handler="+handlerClass$);
        Sack extension = entigrator.getEntityAtKey(extension$);
        String lib$ = extension.getElementItemAt("field", "lib");
        String jar$ = entigrator.getEntihome() + "/" + extension$ + "/" + lib$;
        //      System.out.println("ExtensionHandler:loadIcon:jar="+jar$);
        ZipFile zf = new ZipFile(jar$);
        Enumeration<? extends ZipEntry> entries = zf.entries();
        ZipEntry ze;
        String[] sa;
        while (entries.hasMoreElements()) {
            try {
                ze = entries.nextElement();
                sa = ze.getName().split("/");
                //         System.out.println("ExtensionHandler:loadIcon:zip entry="+sa[sa.length-1]);
                if (resource$.equals(sa[sa.length - 1])) {
                    InputStream is = zf.getInputStream(ze);
                    //            System.out.println("ExtensionHandler:loadIcon:input stream="+is.toString());
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    byte[] b = new byte[1024];
                    int bytesRead = 0;
                    while ((bytesRead = is.read(b)) != -1) {
                        bos.write(b, 0, bytesRead);
                    }
                    byte[] ba = bos.toByteArray();
                    is.close();
                    return Base64.encodeBase64String(ba);
                }
            } catch (Exception e) {

            }
        }
        return null;
    } catch (Exception e) {
        Logger.getLogger(ExtensionHandler.class.getName()).severe(e.toString());
        return null;
    }

}

From source file:com.blazemeter.bamboo.plugin.ServiceManager.java

public static void unzip(String srcZipFileName, String destDirectoryName, BuildLogger logger) {
    try {/*from   www  .  j  av a2  s . c om*/
        BufferedInputStream bufIS = null;
        // create the destination directory structure (if needed)
        File destDirectory = new File(destDirectoryName);
        destDirectory.mkdirs();

        // open archive for reading
        File file = new File(srcZipFileName);
        ZipFile zipFile = new ZipFile(file, ZipFile.OPEN_READ);

        //for every zip archive entry do
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
            logger.addBuildLogEntry("\tExtracting jtl report: " + entry);

            //create destination file
            File destFile = new File(destDirectory, entry.getName());

            //create parent directories if needed
            File parentDestFile = destFile.getParentFile();
            parentDestFile.mkdirs();

            bufIS = new BufferedInputStream(zipFile.getInputStream(entry));
            int currentByte;

            // buffer for writing file
            byte data[] = new byte[BUFFER_SIZE];

            // write the current file to disk
            FileOutputStream fOS = new FileOutputStream(destFile);
            BufferedOutputStream bufOS = new BufferedOutputStream(fOS, BUFFER_SIZE);

            while ((currentByte = bufIS.read(data, 0, BUFFER_SIZE)) != -1) {
                bufOS.write(data, 0, currentByte);
            }

            // close BufferedOutputStream
            bufOS.flush();
            bufOS.close();
        }
        bufIS.close();
    } catch (Exception e) {
        logger.addErrorLogEntry("Failed to unzip report: check that it is downloaded");
    }
}

From source file:net.amigocraft.mpt.util.MiscUtil.java

public static boolean unzip(ZipFile zip, File dest, List<String> files) throws MPTException {
    boolean returnValue = true;
    try {//from ww  w.j  a  va2 s  . c o  m
        List<String> existingDirs = new ArrayList<>();
        Enumeration<? extends ZipEntry> en = zip.entries();
        entryLoop: while (en.hasMoreElements()) {
            ZipEntry entry = en.nextElement();
            String name = entry.getName().startsWith("./")
                    ? entry.getName().substring(2, entry.getName().length())
                    : entry.getName();
            File file = new File(dest, name);
            if (entry.isDirectory()) {
                if (file.exists()) {
                    if (DISALLOW_MERGE) {
                        existingDirs.add(name);
                        if (VERBOSE)
                            Main.log.warning("Refusing to extract directory " + name + ": already exists");
                    }
                }
            } else {
                files.add(name);
                for (String dir : DISALLOWED_DIRECTORIES) {
                    if (file.getPath().startsWith(dir)) {
                        if (VERBOSE)
                            Main.log.warning("Refusing to extract " + name + " from " + zip.getName()
                                    + ": parent directory \"" + dir + "\" is not allowed");
                        continue entryLoop;
                    }
                }
                if (DISALLOW_MERGE) {
                    for (String dir : existingDirs) {
                        if (file.getPath().substring(2, file.getPath().length()).replace(File.separator, "/")
                                .startsWith(dir)) {
                            continue entryLoop;
                        }
                    }
                }
                if (!DISALLOW_OVERWRITE || !file.exists()) {
                    file.getParentFile().mkdirs();
                    for (String ext : DISALLOWED_EXTENSIONS) {
                        if (file.getName().endsWith(ext)) {
                            if (VERBOSE)
                                Main.log.warning("Refusing to extract " + name + " from " + zip.getName()
                                        + ": extension \"" + ext + "\" is not allowed");
                            returnValue = false;
                            continue entryLoop;
                        }
                    }
                    BufferedInputStream bIs = new BufferedInputStream(zip.getInputStream(entry));
                    int b;
                    byte[] buffer = new byte[1024];
                    FileOutputStream fOs = new FileOutputStream(file);
                    BufferedOutputStream bOs = new BufferedOutputStream(fOs, 1024);
                    while ((b = bIs.read(buffer, 0, 1024)) != -1)
                        bOs.write(buffer, 0, b);
                    bOs.flush();
                    bOs.close();
                    bIs.close();
                } else {
                    if (VERBOSE)
                        Main.log.warning(
                                "Refusing to extract " + name + " from " + zip.getName() + ": already exists");
                    returnValue = false;
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace(); //TODO
        throw new MPTException(ERROR_COLOR + "Failed to extract archive!");
    }
    return returnValue;
}

From source file:apim.restful.exportimport.utils.APIImportUtil.java

/**
 * This method decompresses the archive/*from   ww  w.  j  a va 2 s  . c  o  m*/
 *
 * @param sourceFile           the archive containing the API
 * @param destinationDirectory location of the archive to be extracted
 * @return extractedFolder the name of the zip
 */
public static String unzipArchive(File sourceFile, File destinationDirectory) throws APIManagementException {

    InputStream inputStream = null;
    FileOutputStream fileOutputStream = null;
    File destinationFile;
    ZipFile zipfile = null;
    String extractedFolder = null;

    try {
        zipfile = new ZipFile(sourceFile);
        Enumeration zipEntries = null;
        if (zipfile != null) {
            zipEntries = zipfile.entries();
        }
        if (zipEntries != null) {
            int index = 0;
            while (zipEntries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) zipEntries.nextElement();

                if (entry.isDirectory()) {

                    //This index variable is used to get the extracted folder name; that is root directory
                    if (index == 0) {

                        //Get the folder name without the '/' character at the end
                        extractedFolder = entry.getName().substring(0, entry.getName().length() - 1);
                    }
                    index = -1;
                    new File(destinationDirectory, entry.getName()).mkdir();
                    continue;
                }
                inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
                destinationFile = new File(destinationDirectory, entry.getName());
                fileOutputStream = new FileOutputStream(destinationFile);
                copyStreams(inputStream, fileOutputStream);
            }
        }
    } catch (ZipException e) {
        log.error("Error in retrieving archive files.");
        throw new APIManagementException("Error in retrieving archive files.", e);
    } catch (IOException e) {
        log.error("Error in decompressing API archive files.");
        throw new APIManagementException("Error in decompressing API archive files.", e);
    } finally {
        try {
            if (zipfile != null) {
                zipfile.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            if (fileOutputStream != null) {
                fileOutputStream.flush();
                fileOutputStream.close();
            }
        } catch (IOException e) {
            log.error("Error in closing streams while decompressing files.");
        }
    }
    return extractedFolder;
}

From source file:com.ibm.amc.FileManager.java

public static File decompress(URI temporaryFileUri) {
    final File destination = new File(getUploadDirectory(), temporaryFileUri.getSchemeSpecificPart());
    if (!destination.mkdirs()) {
        throw new AmcRuntimeException(Status.INTERNAL_SERVER_ERROR, "CWZBA2001E_DIRECTORY_CREATION_FAILED",
                destination.getPath());//from  w  ww  . j a va2 s . c o m
    }

    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(getFileForUri(temporaryFileUri));

        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            File newDirOrFile = new File(destination, entry.getName());
            if (newDirOrFile.getParentFile() != null && !newDirOrFile.getParentFile().exists()) {
                if (!newDirOrFile.getParentFile().mkdirs()) {
                    throw new AmcRuntimeException(Status.INTERNAL_SERVER_ERROR,
                            "CWZBA2001E_DIRECTORY_CREATION_FAILED", newDirOrFile.getParentFile().getPath());
                }
            }
            if (entry.isDirectory()) {
                if (!newDirOrFile.mkdir()) {
                    throw new AmcRuntimeException(Status.INTERNAL_SERVER_ERROR,
                            "CWZBA2001E_DIRECTORY_CREATION_FAILED", newDirOrFile.getPath());
                }
            } else {
                BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
                int size;
                byte[] buffer = new byte[ZIP_BUFFER];
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newDirOrFile),
                        ZIP_BUFFER);
                while ((size = bis.read(buffer, 0, ZIP_BUFFER)) != -1) {
                    bos.write(buffer, 0, size);
                }
                bos.flush();
                bos.close();
                bis.close();
            }
        }
    } catch (Exception e) {
        throw new AmcRuntimeException(e);
    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException e) {
                logger.debug("decompress", "close failed with " + e);
            }
        }
    }

    return destination;
}

From source file:net.sourceforge.dita4publishers.tools.dxp.DitaDxpHelper.java

/**
 * @param zipFile//from   w w w.j av a 2  s  .co  m
 * @param dxpOptions 
 * @return
 * @throws DitaDxpException 
 */
public static ZipEntry getDxpPackageRootMap(ZipFile zipFile, MapBosProcessorOptions dxpOptions)
        throws DitaDxpException {

    List<ZipEntry> candidateRootEntries = new ArrayList<ZipEntry>();
    List<ZipEntry> candidateDirs = new ArrayList<ZipEntry>();

    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        File temp = new File(entry.getName());
        String parentPath = temp.getParent();
        if (entry.isDirectory()) {
            if (parentPath == null || "".equals(parentPath)) {
                candidateDirs.add(entry);
            }
        } else {
            if (entry.getName().equals("dita_dxp_manifest.ditamap")) {
                return entry;
            }
            if (entry.getName().endsWith(".ditamap")) {
                if (parentPath == null || "".equals(parentPath)) {
                    candidateRootEntries.add(entry);
                }
            }
        }
    }

    // If we get here then we didn't find a manifest map, so look for
    // root map.

    // If exactly one map at the top level, must be the root map of the package.
    if (candidateRootEntries.size() == 1) {
        if (!dxpOptions.isQuiet())
            log.info("Using root map " + candidateRootEntries.get(0).getName());
        return candidateRootEntries.get(0);
    }

    // If there is more than one top-level dir, thank you for playing:

    if (candidateRootEntries.size() == 0 & candidateDirs.size() > 1) {
        throw new DitaDxpException(
                "No manifest map, no map in root of package, and more than one top-level directory in package.");
    }

    // If there is exactly one root directory, look in it for exactly one map:
    if (candidateDirs.size() == 1) {
        String parentPath = candidateDirs.get(0).getName();
        entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            File temp = new File(entry.getName());
            String entryParent = temp.getParent();
            if (entryParent == null)
                entryParent = "/";
            else
                entryParent += "/";
            if (parentPath.equals(entryParent) && entry.getName().endsWith(".ditamap")) {
                candidateRootEntries.add(entry);
            }
        }
        if (candidateRootEntries.size() == 1) {
            // Must be the root map
            if (!dxpOptions.isQuiet())
                log.info("Using root map " + candidateRootEntries.get(0).getName());
            return candidateRootEntries.get(0);
        }
        if (candidateRootEntries.size() > 1) {
            throw new DitaDxpException(
                    "No manifest map and found more than one map in the root directory of the package.");
        }
    }

    // Should never get here:

    throw new DitaDxpException("Unable to find package manifest map or single root map in DXP package.");

}

From source file:es.eucm.eadandroid.homeapp.repository.resourceHandler.RepoResourceHandler.java

/**
 * Uncompresses any zip file/*w w  w.  j a  v a2s  . c  o  m*/
 */
public static void unzip(String path_from, String path_to, String name, boolean deleteZip) {

    StringTokenizer separator = new StringTokenizer(name, ".", true);
    String file_name = separator.nextToken();

    File f = new File(path_to + file_name);

    if (f.exists())
        removeDirectory(f);

    separator = new StringTokenizer(path_to + file_name, "/", true);

    String partial_path = null;
    String total_path = separator.nextToken();

    while (separator.hasMoreElements()) {

        partial_path = separator.nextToken();
        total_path = total_path + partial_path;
        if (!new File(total_path).exists()) {

            if (separator.hasMoreElements())
                total_path = total_path + separator.nextToken();
            else
                (new File(total_path)).mkdir();

        } else
            total_path = total_path + separator.nextToken();

    }

    Enumeration<? extends ZipEntry> entries = null;
    ZipFile zipFile = null;

    try {
        String location_ead = path_from + name;
        zipFile = new ZipFile(location_ead);

        entries = zipFile.entries();

        BufferedOutputStream file;

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();

            separator = new StringTokenizer(entry.getName(), "/", true);
            partial_path = null;
            total_path = "";

            while (separator.hasMoreElements()) {

                partial_path = separator.nextToken();
                total_path = total_path + partial_path;
                if (!new File(entry.getName()).exists()) {

                    if (separator.hasMoreElements()) {
                        total_path = total_path + separator.nextToken();
                        (new File(path_to + file_name + "/" + total_path)).mkdir();
                    } else {

                        file = new BufferedOutputStream(
                                new FileOutputStream(path_to + file_name + "/" + total_path));

                        System.err.println("Extracting file: " + entry.getName());
                        copyInputStream(zipFile.getInputStream(entry), file);
                    }
                } else {
                    total_path = total_path + separator.nextToken();
                }
            }

        }

        zipFile.close();
    } catch (IOException ioe) {
        ioe.printStackTrace();
        return;
    }

    if (deleteZip)
        (new File(path_from + name)).delete();

}

From source file:com.aurel.track.lucene.util.FileUtil.java

public static void unzipFile(File uploadZip, File unzipDestinationDirectory) throws IOException {
    if (!unzipDestinationDirectory.exists()) {
        unzipDestinationDirectory.mkdirs();
    }// w  ww  .  j a va2 s. com
    final int BUFFER = 2048;
    // Open Zip file for reading
    ZipFile zipFile = new ZipFile(uploadZip, ZipFile.OPEN_READ);

    // Create an enumeration of the entries in the zip file
    Enumeration zipFileEntries = zipFile.entries();

    // Process each entry
    while (zipFileEntries.hasMoreElements()) {
        // grab a zip file entry
        ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
        String currentEntry = entry.getName();
        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()) {
            BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry));
            int currentByte;
            // establish buffer for writing file
            byte data[] = new byte[BUFFER];

            // write the current file to disk
            FileOutputStream fos = new FileOutputStream(destFile);
            BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);

            // read and write until last byte is encountered
            while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                dest.write(data, 0, currentByte);
            }
            dest.flush();
            dest.close();
            is.close();
        }
    }
    zipFile.close();
}