Example usage for java.util.zip ZipFile ZipFile

List of usage examples for java.util.zip ZipFile ZipFile

Introduction

In this page you can find the example usage for java.util.zip ZipFile ZipFile.

Prototype

public ZipFile(File file) throws ZipException, IOException 

Source Link

Document

Opens a ZIP file for reading given the specified File object.

Usage

From source file:com.redhat.red.koji.build.BuildFinder.java

Set<String> findMissingBuilds(File zipFile, int skipParts) throws IOException, KojiClientException {
    ZipFile zf = new ZipFile(zipFile);
    Logger logger = LoggerFactory.getLogger(getClass());
    final Set<String> missingBuilds = new HashSet<>();

    client.withKojiSession((session) -> {
        zf.stream().parallel().filter((entry) -> !entry.isDirectory()).forEach((entry) -> {
            String entryName = entry.getName();

            if (entryName.endsWith(".md5") || entryName.endsWith(".sha1")
                    || entryName.endsWith("maven-metadata.xml")) {
                logger.debug("Skipping checksum file: {}", entryName);
            } else {
                String[] parts = entryName.split("/");
                if (parts.length > skipParts) {
                    String[] realParts = new String[parts.length - skipParts];
                    System.arraycopy(parts, skipParts, realParts, 0, realParts.length);
                    String path = join(realParts, "/");

                    Boolean foundT_missingF = null;
                    synchronized (missing) {
                        if (missing.contains(path)) {
                            foundT_missingF = false;
                        }/*from w  ww  .j av  a 2 s. c o m*/
                    }

                    synchronized (found) {
                        if (found.contains(path)) {
                            foundT_missingF = true;
                        }
                    }

                    if (foundT_missingF == null) {
                        ArtifactPathInfo pathInfo = ArtifactPathInfo.parse(path);
                        if (pathInfo != null) {
                            ArtifactRef aref = pathInfo.getArtifact();
                            logger.info("??? {} (trimmed path: '{}', real path: '{}'", aref, path, entryName);
                            try {
                                List<KojiBuildInfo> builds = client.listBuildsContaining(aref, session);
                                if (builds == null || builds.isEmpty()) {
                                    synchronized (missing) {
                                        missing.add(path);
                                    }

                                    synchronized (missingBuilds) {
                                        missingBuilds.add(entryName);
                                    }
                                } else {
                                    synchronized (found) {
                                        found.add(path);
                                    }
                                }
                            } catch (KojiClientException e) {
                                logger.error("Failed to query koji for artifact: " + aref, e);
                            }
                        }
                    } else if (!foundT_missingF) {
                        synchronized (missingBuilds) {
                            missingBuilds.add(entryName);
                        }
                    }
                }
            }
        });

        return null;
    });

    return missingBuilds;
}

From source file:local.edg.ClassDB.java

/**
 * Generates a data base with class informations about a given application
 * /* w  w w. ja  va 2s.  com*/
 * @param appClasses
 *            The classes of the application as directories to class-files or as path to jar-files.
 *            
 * @return Data base with class information.
 */
public static Map<String, Class> create(String[] appClasses) {
    ClassDbVisitor cv = new ClassDbVisitor();
    for (String s : appClasses) {
        File f = new File(s);
        if (f.isDirectory()) {
            Collection<File> files = FileUtils.listFiles(f, new String[] { "class" }, true);
            for (File cf : files) {
                try {
                    ClassReader cr = new ClassReader(new FileInputStream(cf));
                    cr.accept(cv, 0);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else if (f.isFile() && s.toLowerCase().endsWith(".jar")) {
            try {
                ZipFile zf = new ZipFile(f);
                Enumeration<? extends ZipEntry> en = zf.entries();
                while (en.hasMoreElements()) {
                    ZipEntry e = en.nextElement();
                    String name = e.getName();
                    if (name.endsWith(".class")) {
                        new ClassReader(zf.getInputStream(e)).accept(cv, 0);
                    }
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
    return cv.getClassDb();
}

From source file:com.mc.printer.model.utils.ZipHelper.java

/**
 * jar????/*from   ww  w  . ja va 2  s .  c  om*/
 *
 * @param jar ????jar
 * @param subDir jar???????
 * @param loc ????
 * @param force ????
 * @return
 */
public static boolean unZip(String jar, String subDir, String loc, boolean force) {
    try {
        File base = new File(loc);
        if (!base.exists()) {
            base.mkdirs();
        }

        ZipFile zip = new ZipFile(new File(jar));
        Enumeration<? extends ZipEntry> entrys = zip.entries();
        while (entrys.hasMoreElements()) {
            ZipEntry entry = entrys.nextElement();
            String name = entry.getName();
            if (!name.startsWith(subDir)) {
                continue;
            }
            //subDir
            name = name.replace(subDir, "").trim();
            if (name.length() < 2) {
                log.debug(name + "  < 2");
                continue;
            }
            if (entry.isDirectory()) {
                File dir = new File(base, name);
                if (!dir.exists()) {
                    dir.mkdirs();
                    log.debug("create directory");
                } else {
                    log.debug("the directory is existing.");
                }
                log.debug(name + " is a directory");
            } else {
                File file = new File(base, name);
                if (file.exists() && force) {
                    file.delete();
                }
                if (!file.exists()) {
                    InputStream in = zip.getInputStream(entry);
                    FileUtils.copyInputStreamToFile(in, file);
                    log.debug("create file.");
                    in.close();
                } else {
                    log.debug("the file is existing");
                }
                log.debug(name + " is not a directory");
            }
        }
        zip.close();
    } catch (ZipException ex) {
        ex.printStackTrace();
        log.error("file unzip failed.", ex);
        return false;
    } catch (IOException ex) {
        ex.printStackTrace();
        log.error("file IO failed", ex);
        return false;
    }
    return true;
}

From source file:org.cloudfoundry.client.lib.archive.AbstractApplicationArchiveTest.java

@Before
public void setup() throws ZipException, IOException {
    this.zipFile = new ZipFile(SampleProjects.springTravel());
    this.archive = newApplicationArchive(zipFile);
    this.archiveEntries = new HashMap<String, ApplicationArchive.Entry>();
    for (ApplicationArchive.Entry entry : archive.getEntries()) {
        archiveEntries.put(entry.getName(), entry);
    }//ww  w . j  ava2  s. c  o m
}

From source file:edu.umd.cs.guitar.testcase.plugin.edg.ClassDB.java

/**
 * Generates a database containing class information about given application classes
 * @param appClasses The classes of an application as directories to class-files or as path to jar-files
 * @return Database containing class information
 *///from  w  w  w .  java 2 s.com
public static Map<String, Class> create(String[] appClasses) {
    ClassDBVisitor cv = new ClassDBVisitor();
    for (String s : appClasses) {
        File f = new File(s);
        if (f.isDirectory()) {
            Collection<File> files = FileUtils.listFiles(f, new String[] { "class" }, true);
            for (File cf : files) {
                try {
                    ClassReader cr = new ClassReader(new FileInputStream(cf));
                    cr.accept(cv, 0);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else if (f.isFile() && s.toLowerCase().endsWith(".jar")) {
            try {
                ZipFile zf = new ZipFile(f);
                Enumeration<? extends ZipEntry> en = zf.entries();
                while (en.hasMoreElements()) {
                    ZipEntry e = en.nextElement();
                    String name = e.getName();
                    if (name.endsWith(".class")) {
                        new ClassReader(zf.getInputStream(e)).accept(cv, 0);
                    }
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
    return cv.getClassDb();
}

From source file:com.idocbox.common.file.ZipExtracter.java

/**
 * extract given entry in zip file to destination directory.
 * if given entry is a directory, extract all folder and files under it to
 * destination directory./*from w  w w.j  a va2 s. co  m*/
 * @param zipFileName  name of zip file.
 * @param entry   it can be a directory or a file.(if it is end with "/",it 
 *                will be treated as a directory.) . For example, 
 *                conf/ represents subdirectory in zip file.
 *                Use "/" to represent root of zip file.
  *                
 * @param desDir  destination directory.
 * @param startDirLevel the level to start create directory.
 *                      Its value is 1,2,...
 * @throws IOException 
 * @throws ZipException 
 */
public static void extract(final String zipFileName, final String entry, final String desDir,
        final int... startDirLevel) throws ZipException, IOException {
    File f = new File(zipFileName);
    if (f.exists()) {
        //check destination directory.
        File desf = new File(desDir);
        if (!desf.exists()) {
            desf.mkdirs();
        }

        boolean toExtractDir = false;
        if (entry.endsWith("/")) {
            toExtractDir = true;
        }

        //create zip file object.
        ZipFile zf = new ZipFile(f);

        if (toExtractDir) {
            Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zf.entries();
            ZipEntry ent = null;
            while (entries.hasMoreElements()) {
                ent = entries.nextElement();
                if (isUnderDir(ent, entry)) { //the entry is under directory 
                                              //which should to be extracted.
                                              //extract the entry.
                    extract(zf, ent, desDir, startDirLevel);
                } else {
                    //nothing to do.
                }
            }
        } else {//extract given zip entry file to destination directory.
            ZipEntry zipEntry = zf.getEntry(entry);
            if (null != zipEntry) {
                extract(zf, zipEntry, desDir, startDirLevel);
            }
        }
        if (null != zf) {
            //close zip file.
            zf.close();
        }
    }
}

From source file:com.shazam.fork.io.ClassesDexFileExtractor.java

private void dumpDexFilesFromApk(File apkFile, File outputFolder) {
    ZipFile zip = null;//from w  ww .j  av  a 2 s  .  c o  m
    InputStream classesDexInputStream = null;
    FileOutputStream fileOutputStream = null;

    try {
        zip = new ZipFile(apkFile);
        int index = 1;
        String currentDex;
        while (true) {
            currentDex = CLASSES_PREFIX + (index > 1 ? index : "") + DEX_EXTENSION;
            ZipEntry classesDex = zip.getEntry(currentDex);
            if (classesDex != null) {
                File dexFileDestination = new File(outputFolder, currentDex);
                classesDexInputStream = zip.getInputStream(classesDex);
                fileOutputStream = new FileOutputStream(dexFileDestination);
                copyLarge(classesDexInputStream, fileOutputStream);
                index++;
            } else {
                break;
            }
        }
    } catch (IOException e) {
        throw new DexFileExtractionException(
                "Error when trying to scan " + apkFile.getAbsolutePath() + " for test classes.", e);
    } finally {
        closeQuietly(classesDexInputStream);
        closeQuietly(fileOutputStream);
        closeQuietly(zip);
    }
}

From source file:eu.europa.esig.dss.asic.signature.asice.ASiCESignatureFilenameTest.java

@Override
public void signAndVerify() throws IOException {
    String containerTemporaryPath = temporaryFolder.newFile().getPath();
    getSignatureParameters().aSiC().setSignatureFileName("signatures2047.xml");
    documentToSign = sign();//w w  w .  j  a v a2 s  .co  m
    documentToSign.save(containerTemporaryPath);
    ZipFile zip = new ZipFile(containerTemporaryPath);
    assertNotNull("Signature file name is not correct", zip.getEntry("META-INF/signatures2047.xml"));
    IOUtils.closeQuietly(zip);
}

From source file:io.apiman.common.plugin.PluginClassLoader.java

/**
 * Constructor.//from   w  w  w  .ja  v  a 2s.  co  m
 * @param pluginArtifactFile plugin artifact
 * @throws IOException if an I/O error has occurred
 */
public PluginClassLoader(File pluginArtifactFile) throws IOException {
    super();
    closed = false;
    this.pluginArtifactZip = new ZipFile(pluginArtifactFile);
    this.workDir = createWorkDir(pluginArtifactFile);
    indexPluginArtifact();
}

From source file:com.l2jfree.gameserver.util.JarClassLoader.java

private byte[] loadClassData(String name) throws IOException {
    byte[] classData = null;
    for (String jarFile : _jars) {
        ZipFile zipFile = null;//from  www.  ja  v  a2s  .  c om
        DataInputStream zipStream = null;

        try {
            File file = new File(jarFile);
            zipFile = new ZipFile(file);
            String fileName = name.replace('.', '/') + ".class";
            ZipEntry entry = zipFile.getEntry(fileName);
            if (entry == null)
                continue;
            classData = new byte[(int) entry.getSize()];
            zipStream = new DataInputStream(zipFile.getInputStream(entry));
            zipStream.readFully(classData, 0, (int) entry.getSize());
            break;
        } catch (IOException e) {
            _log.warn(jarFile + ":", e);
            continue;
        } finally {
            try {
                if (zipFile != null)
                    zipFile.close();
            } catch (Exception e) {
                _log.warn("", e);
            }
            try {
                if (zipStream != null)
                    zipStream.close();
            } catch (Exception e) {
                _log.warn("", e);
            }
        }
    }
    if (classData == null)
        throw new IOException("class not found in " + _jars);
    return classData;
}