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:jobhunter.persistence.Persistence.java

private Optional<Profile> _readProfile(final File file) {

    try (ZipFile zfile = new ZipFile(file)) {
        l.debug("Reading profile from JHF File");
        final InputStream in = zfile.getInputStream(new ZipEntry("profile.xml"));

        MessageDigest md = MessageDigest.getInstance("MD5");
        DigestInputStream dis = new DigestInputStream(in, md);

        final Object obj = xstream.fromXML(dis);

        updateLastMod(file, md);//from   ww w. j a  v  a2s. co m

        return Optional.of((Profile) obj);
    } catch (Exception e) {
        l.error("Failed to read file: {}", e.getMessage());
    }

    return Optional.empty();
}

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;//  w ww .j  av  a  2  s .c  o 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:com.frostwire.util.ZipUtils.java

private static int getItemCount(File file) throws IOException {
    ZipFile zip = null;//www .  ja v  a2 s .  c  o  m
    int count = 0;
    try {
        zip = new ZipFile(file);
        count = zip.size();
    } finally {
        try {
            zip.close();
        } catch (Throwable e) {
            // ignore
        }
    }
    return count;
}

From source file:edu.harvard.i2b2.eclipse.plugins.metadataLoader.util.FileUtil.java

public static void unZipAll(File source, File destination) throws IOException {
    System.out.println("Unzipping - " + source.getName());
    int BUFFER = 2048;

    ZipFile zip = new ZipFile(source);
    try {/*from www.j a v a 2s .  c  om*/
        destination.getParentFile().mkdirs();
        Enumeration zipFileEntries = zip.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(destination, currentEntry);
            //destFile = new File(newPath, destFile.getName());
            File destinationParent = destFile.getParentFile();

            // create the parent directory structure if needed
            destinationParent.mkdirs();

            if (!entry.isDirectory()) {
                BufferedInputStream is = null;
                FileOutputStream fos = null;
                BufferedOutputStream dest = null;
                try {
                    is = new BufferedInputStream(zip.getInputStream(entry));
                    int currentByte;
                    // establish buffer for writing file
                    byte data[] = new byte[BUFFER];

                    // write the current file to disk
                    fos = new FileOutputStream(destFile);
                    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);
                    }
                } catch (Exception e) {
                    System.out.println("unable to extract entry:" + entry.getName());
                    throw e;
                } finally {
                    if (dest != null) {
                        dest.close();
                    }
                    if (fos != null) {
                        fos.close();
                    }
                    if (is != null) {
                        is.close();
                    }
                }
            } else {
                //Create directory
                destFile.mkdirs();
            }

            if (currentEntry.endsWith(".zip")) {
                // found a zip file, try to extract
                unZipAll(destFile, destinationParent);
                if (!destFile.delete()) {
                    System.out.println("Could not delete zip");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Failed to successfully unzip:" + source.getName());
    } finally {
        zip.close();
    }
    System.out.println("Done Unzipping:" + source.getName());
}

From source file:org.openmrs.module.clinicalsummary.io.UploadSummariesTask.java

/**
 * In order to correctly perform the encryption - decryption process, user must store their init vector table. This init vector will be given to the
 * user as a small file and it is required to perform the decryption process.
 *
 * @throws Exception/*from w  w w. ja  v  a  2 s. co  m*/
 */
protected void processInitVector() throws Exception {
    String encryptedFilename = StringUtils.join(Arrays.asList(filename, TaskConstants.FILE_TYPE_ENCRYPTED),
            ".");
    ZipFile encryptedFile = new ZipFile(new File(TaskUtils.getEncryptedOutputPath(), encryptedFilename));

    Enumeration<? extends ZipEntry> entries = encryptedFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry zipEntry = entries.nextElement();
        if (zipEntry.getName().endsWith(TaskConstants.FILE_TYPE_SECRET)) {
            InputStream inputStream = encryptedFile.getInputStream(zipEntry);
            initVector = FileCopyUtils.copyToByteArray(inputStream);
            if (initVector.length != IV_SIZE) {
                throw new Exception("Secret file is corrupted or invalid secret file are being used.");
            }
        }
    }
}

From source file:de.rub.syssec.saaf.analysis.steps.extract.ApkUnzipper.java

/**
 * Extracts the given apk into the given destination directory
 * //from   ww  w . ja v  a2 s.c  o m
 * @param archive
 *            - the file to extract
 * @param dest
 *            - the destination directory
 * @throws IOException
 */
public static void extractApk(File archive, File dest) throws IOException {

    @SuppressWarnings("resource") // Closing it later results in an error
    ZipFile zipFile = new ZipFile(archive);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    BufferedOutputStream bos = null;
    BufferedInputStream bis = null;

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

        String entryFileName = entry.getName();

        byte[] buffer = new byte[16384];
        int len;

        File dir = buildDirectoryHierarchyFor(entryFileName, dest);// destDir
        if (!dir.exists()) {
            dir.mkdirs();
        }

        if (!entry.isDirectory()) {
            if (entry.getSize() == 0) {
                LOGGER.warn("Found ZipEntry \'" + entry.getName() + "\' with size 0 in " + archive.getName()
                        + ". Looks corrupted.");
                continue;
            }

            try {
                bos = new BufferedOutputStream(new FileOutputStream(new File(dest, entryFileName)));// destDir,...

                bis = new BufferedInputStream(zipFile.getInputStream(entry));

                while ((len = bis.read(buffer)) > 0) {
                    bos.write(buffer, 0, len);
                }
                bos.flush();
            } catch (IOException ioe) {
                LOGGER.warn("Failed to extract entry \'" + entry.getName() + "\' from archive. Results for "
                        + archive.getName() + " may not be accurate");
            } finally {
                if (bos != null)
                    bos.close();
                if (bis != null)
                    bis.close();
                // if (zipFile != null) zipFile.close();
            }
        }

    }

}

From source file:de.tudarmstadt.ukp.clarin.webanno.brat.dao.DaoUtilsTest.java

@SuppressWarnings("resource")
@Test/* w w  w . ja v a 2s  .co m*/
public void testZipFolder() {

    File toBeZippedFiles = new File("src/test/resources");
    File zipedFiles = new File("target/" + toBeZippedFiles.getName() + ".zip");
    try {
        ZipUtils.zipFolder(toBeZippedFiles, zipedFiles);
    } catch (Exception e) {
        LOG.info("Zipping fails" + ExceptionUtils.getRootCauseMessage(e));
    }

    FileInputStream fs;
    try {
        fs = new FileInputStream(zipedFiles);
        ZipInputStream zis = new ZipInputStream(fs);
        ZipEntry zE;
        while ((zE = zis.getNextEntry()) != null) {
            for (File toBeZippedFile : toBeZippedFiles.listFiles()) {
                if ((FilenameUtils.getBaseName(toBeZippedFile.getName()))
                        .equals(FilenameUtils.getBaseName(zE.getName()))) {
                    // Extract the zip file, save it to temp and compare
                    ZipFile zipFile = new ZipFile(zipedFiles);
                    ZipEntry zipEntry = zipFile.getEntry(zE.getName());
                    InputStream is = zipFile.getInputStream(zipEntry);
                    File temp = File.createTempFile("temp", ".txt");
                    OutputStream out = new FileOutputStream(temp);
                    IOUtils.copy(is, out);
                    FileUtils.contentEquals(toBeZippedFile, temp);
                }
            }
            zis.closeEntry();
        }
    } catch (FileNotFoundException e) {
        LOG.info("zipped file not found " + ExceptionUtils.getRootCauseMessage(e));
    } catch (IOException e) {
        LOG.info("Unable to get file " + ExceptionUtils.getRootCauseMessage(e));
    }

}

From source file:com.heliosdecompiler.helios.transformers.disassemblers.KrakatauDisassembler.java

public boolean disassembleClassNode(ClassNode cn, byte[] b, StringBuilder output) {
    if (Helios.ensurePython2Set()) {
        File inputJar = null;//from   w  w  w.  j  av  a2s  .  co  m
        File outputZip = null;
        String processLog = null;

        try {
            inputJar = Files.createTempFile("kdisin", ".jar").toFile();
            outputZip = Files.createTempFile("kdisout", ".zip").toFile();

            Map<String, byte[]> data = Helios.getAllLoadedData();
            data.put(cn.name + ".class", b);

            Utils.saveClasses(inputJar, data);

            Process process = Helios.launchProcess(new ProcessBuilder(
                    com.heliosdecompiler.helios.Settings.PYTHON2_LOCATION.get().asString(), "-O",
                    "disassemble.py", "-path", inputJar.getAbsolutePath(), "-out", outputZip.getAbsolutePath(),
                    cn.name + ".class", Settings.ROUNDTRIP.isEnabled() ? "-roundtrip" : "")
                            .directory(Constants.KRAKATAU_DIR));

            processLog = Utils.readProcess(process);

            ZipFile zipFile = new ZipFile(outputZip);
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            byte[] disassembled = null;
            while (entries.hasMoreElements()) {
                ZipEntry next = entries.nextElement();
                if (next.getName().equals(cn.name + ".j")) {
                    disassembled = IOUtils.toByteArray(zipFile.getInputStream(next));
                }
            }
            zipFile.close();
            output.append(new String(disassembled, "UTF-8"));
            return true;
        } catch (Exception e) {
            output.append(parseException(e)).append(processLog);
            return false;
        } finally {
            FileUtils.deleteQuietly(inputJar);
            FileUtils.deleteQuietly(outputZip);
        }
    } else {
        output.append("You need to set the location of Python 2.x");
    }
    return false;
}

From source file:jp.co.cyberagent.jenkins.plugins.DeployStrategyAndroid.java

private String getStringFromManifest(final String name) {
    File tempApk = null;/*from w  ww . j  a v a 2 s.c o m*/
    InputStream is = null;
    ZipFile zip = null;
    try {
        tempApk = File.createTempFile(getBuild().getId(), "nr-" + getBuild().getNumber());
        mApkFile.copyTo(new FileOutputStream(tempApk));
        zip = new ZipFile(tempApk);
        ZipEntry mft = zip.getEntry("AndroidManifest.xml");
        is = zip.getInputStream(mft);

        byte[] xml = new byte[is.available()];
        is.read(xml);

        String string = AndroidUtils.decompressXML(xml);
        int start = string.indexOf(name + "=\"") + name.length() + 2;
        int end = string.indexOf("\"", start);
        String version = string.substring(start, end);

        if (version.startsWith("resourceID 0x")) {
            int resId = Integer.parseInt(version.substring(13), 16);
            return getStringFromResource(tempApk, resId);
        } else {
            return version;
        }
    } catch (Exception e) {
        getLogger().println(TAG + "Error: " + e.getMessage());
    } finally {
        if (tempApk != null)
            tempApk.delete();
        if (zip != null)
            try {
                zip.close();
            } catch (IOException e) {
                getLogger().println(TAG + "Error: " + e.getMessage());
            }
        if (is != null)
            try {
                is.close();
            } catch (IOException e) {
                getLogger().println(TAG + "Error: " + e.getMessage());
            }
    }
    return null;
}

From source file:edu.umd.cs.marmoset.utilities.ZipExtractor.java

/**
 * Extract the zip file.//from   www. j  a v a  2s . c o  m
 * @throws IOException
 * @throws BuilderException
 */
public void extract(File directory) throws IOException, ZipExtractorException {
    ZipFile z = new ZipFile(zipFile);
    Pattern badName = Pattern.compile("[\\p{Cntrl}<>]");

    try {
        Enumeration<? extends ZipEntry> entries = z.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            String entryName = entry.getName();

            if (!shouldExtract(entryName))
                continue;
            if (badName.matcher(entryName).find()) {
                if (entry.getSize() > 0)
                    getLog().debug("Skipped entry of length " + entry.getSize() + " with bad file name "
                            + java.net.URLEncoder.encode(entryName, "UTF-8"));
                continue;
            }
            try {
                // Get the filename to extract the entry into.
                // Subclasses may define this to be something other
                // than the entry name.
                String entryFileName = transformFileName(entryName);
                if (!entryFileName.equals(entryName)) {
                    getLog().debug("Transformed zip entry name: " + entryName + " ==> " + entryFileName);
                }
                entriesExtractedFromZipArchive.add(entryFileName);

                File entryOutputFile = new File(directory, entryFileName).getAbsoluteFile();

                File parentDir = entryOutputFile.getParentFile();
                if (!parentDir.exists()) {
                    if (!parentDir.mkdirs()) {
                        throw new ZipExtractorException(
                                "Couldn't make directory for entry output file " + entryOutputFile.getPath());
                    }
                }

                if (!parentDir.isDirectory()) {
                    throw new ZipExtractorException(
                            "Parent directory for entry " + entryOutputFile.getPath() + " is not a directory");
                }

                // Make sure the entry output file lies within the build directory.
                // A malicious zip file might have ".." components in it.

                getLog().trace("entryOutputFile path: " + entryOutputFile.getCanonicalPath());
                if (!entryOutputFile.getCanonicalPath().startsWith(directory.getCanonicalPath() + "/")) {

                    if (!entry.isDirectory())
                        getLog().warn("Zip entry " + entryName + " accesses a path " + entryOutputFile.getPath()
                                + "outside the build directory " + directory.getPath());
                    continue;
                }

                if (entry.isDirectory()) {
                    entryOutputFile.mkdir();
                    continue;
                }

                // Extract the entry
                InputStream entryInputStream = null;
                OutputStream entryOutputStream = null;
                try {
                    entryInputStream = z.getInputStream(entry);
                    entryOutputStream = new BufferedOutputStream(new FileOutputStream(entryOutputFile));

                    CopyUtils.copy(entryInputStream, entryOutputStream);
                } finally {
                    IOUtils.closeQuietly(entryInputStream);
                    IOUtils.closeQuietly(entryOutputStream);
                }

                // Hook for subclasses, to specify when entries are
                // successfully extracted.
                successfulFileExtraction(entryName, entryFileName);
                ++numFilesExtacted;
            } catch (RuntimeException e) {
                getLog().error("Error extracting " + entryName, e);
                throw e;
            }
        }
    } finally {
        z.close();
    }

}