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:org.nuxeo.apidoc.introspection.ServerInfo.java

protected static BundleInfoImpl computeBundleInfo(Bundle bundle) {
    RuntimeService runtime = Framework.getRuntime();
    BundleInfoImpl binfo = new BundleInfoImpl(bundle.getSymbolicName());
    binfo.setFileName(runtime.getBundleFile(bundle).getName());
    binfo.setLocation(bundle.getLocation());
    if (!(bundle instanceof BundleImpl)) {
        return binfo;
    }/*from www . jav a 2s .  c  o  m*/
    BundleImpl nxBundle = (BundleImpl) bundle;
    File jarFile = nxBundle.getBundleFile().getFile();
    if (jarFile == null) {
        return binfo;
    }
    try {
        if (jarFile.isDirectory()) {
            // directory: run from Eclipse in unit tests
            // .../nuxeo-runtime/nuxeo-runtime/bin
            // or sometimes
            // .../nuxeo-runtime/nuxeo-runtime/bin/main
            File manifest = new File(jarFile, META_INF_MANIFEST_MF);
            if (manifest.exists()) {
                InputStream is = new FileInputStream(manifest);
                String mf = IOUtils.toString(is, Charsets.UTF_8);
                binfo.setManifest(mf);
            }
            // find and parse pom.xml
            File up = new File(jarFile, "..");
            File pom = new File(up, POM_XML);
            if (!pom.exists()) {
                pom = new File(new File(up, ".."), POM_XML);
                if (!pom.exists()) {
                    pom = null;
                }
            }
            if (pom != null) {
                DocumentBuilder b = documentBuilderFactory.newDocumentBuilder();
                Document doc = b.parse(new FileInputStream(pom));
                XPath xpath = xpathFactory.newXPath();
                String groupId = (String) xpath.evaluate("//project/groupId", doc, XPathConstants.STRING);
                if ("".equals(groupId)) {
                    groupId = (String) xpath.evaluate("//project/parent/groupId", doc, XPathConstants.STRING);
                }
                String artifactId = (String) xpath.evaluate("//project/artifactId", doc, XPathConstants.STRING);
                if ("".equals(artifactId)) {
                    artifactId = (String) xpath.evaluate("//project/parent/artifactId", doc,
                            XPathConstants.STRING);
                }
                String version = (String) xpath.evaluate("//project/version", doc, XPathConstants.STRING);
                if ("".equals(version)) {
                    version = (String) xpath.evaluate("//project/parent/version", doc, XPathConstants.STRING);
                }
                binfo.setArtifactId(artifactId);
                binfo.setGroupId(groupId);
                binfo.setArtifactVersion(version);
            }
        } else {
            try (ZipFile zFile = new ZipFile(jarFile)) {
                ZipEntry mfEntry = zFile.getEntry(META_INF_MANIFEST_MF);
                if (mfEntry != null) {
                    try (InputStream mfStream = zFile.getInputStream(mfEntry)) {
                        String mf = IOUtils.toString(mfStream, Charsets.UTF_8);
                        binfo.setManifest(mf);
                    }
                }
                Enumeration<? extends ZipEntry> entries = zFile.entries();
                while (entries.hasMoreElements()) {
                    ZipEntry entry = entries.nextElement();
                    if (entry.getName().endsWith(POM_PROPERTIES)) {
                        try (InputStream is = zFile.getInputStream(entry)) {
                            PropertyResourceBundle prb = new PropertyResourceBundle(is);
                            String groupId = prb.getString("groupId");
                            String artifactId = prb.getString("artifactId");
                            String version = prb.getString("version");
                            binfo.setArtifactId(artifactId);
                            binfo.setGroupId(groupId);
                            binfo.setArtifactVersion(version);
                        }
                        break;
                    }
                }
            }
            try (ZipFile zFile = new ZipFile(jarFile)) {
                EmbeddedDocExtractor.extractEmbeddedDoc(zFile, binfo);
            }
        }
    } catch (IOException | ParserConfigurationException | SAXException | XPathException | NuxeoException e) {
        log.error(e, e);
    }
    return binfo;
}

From source file:com.denimgroup.threadfix.importer.loader.ScanTypeCalculationServiceImpl.java

private String figureOutZip(String fileName) {

    String result = null;/*  ww  w .  ja v  a 2  s . com*/
    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(DiskUtils.getScratchFile(fileName));

        if (zipFile.getEntry("audit.fvdl") != null) {
            result = ScannerType.FORTIFY.getDbName();
        } else if (ZipFileUtils.getZipEntry("issue_index.js", zipFile) != null) {
            result = ScannerType.SKIPFISH.getDisplayName();
        } else if (zipFile.getEntry("index.html") != null && zipFile.getEntry("scanview.css") != null) {
            result = ScannerType.CLANG.getDisplayName();
        }
    } catch (FileNotFoundException e) {
        log.warn("Unable to find zip file.", e);
    } catch (IOException e) {
        log.warn("Exception encountered while trying to identify zip file.", e);
    } finally {
        closeQuietly(zipFile);
    }

    return result;
}

From source file:ca.phon.app.workspace.ExtractProjectArchiveTask.java

/**
 * Extract contents of a zip file to the destination directory.
 *///from  w  w w. j a  v a2  s . co m
private void extractArchive(File archive, File destDir) throws IOException {

    BufferedOutputStream out = null;
    BufferedInputStream in = null;

    try (ZipFile zip = new ZipFile(archive)) {
        // create output directory if it does not exist
        if (destDir.exists() && !destDir.isDirectory()) {
            throw new IOException("'" + destDir.getAbsolutePath() + "' is not a directory.");
        }

        if (!destDir.exists()) {
            setProperty(STATUS_PROP, "Creating output directory");
            destDir.mkdirs();
        }

        Tuple<ZippedProjectType, String> zipDetect = getZipDetect();
        ZipEntry entry = null;
        Enumeration<? extends ZipEntry> entries = zip.entries();
        while (entries.hasMoreElements()) {

            if (isShutdown()) {
                return;
            }

            entry = entries.nextElement();

            String entryName = entry.getName();
            File outFile = null;
            if (zipDetect.getObj1() == ZippedProjectType.PROJECT_BASE_INCLUDED) {
                // dest dir has already b
                outFile = new File(destDir, entryName.replaceFirst(zipDetect.getObj2(), ""));
            } else {
                outFile = new File(destDir, entryName);
            }

            if (entry.isDirectory()) {
                if (!outFile.exists())
                    outFile.mkdirs();
            } else {
                LOGGER.info("Extracting: " + entry);
                setProperty(STATUS_PROP, "Extracting: " + entry);

                in = new BufferedInputStream(zip.getInputStream(entry));
                int count = -1;
                byte data[] = new byte[ZIP_BUFFER];

                if (outFile.exists()) {
                    LOGGER.warning("Overwriting file '" + outFile.getAbsolutePath() + "'");
                }

                File parentFile = outFile.getParentFile();

                if (!parentFile.exists())
                    parentFile.mkdirs();

                FileOutputStream fos = new FileOutputStream(outFile);
                out = new BufferedOutputStream(fos, ZIP_BUFFER);
                while ((count = in.read(data, 0, ZIP_BUFFER)) != -1) {
                    out.write(data, 0, count);
                }
                out.flush();
                out.close();
                in.close();
            }
        }
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
        throw e;
    }

    setProperty(STATUS_PROP, "Finished");
}

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  w  w. j a  v  a  2  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:gobblin.aws.AWSJobConfigurationManager.java

/***
 * Unzip a zip archive/*w w  w . j a va  2  s.  co m*/
 * @param file Zip file to unarchive
 * @param outputDir Output directory for the unarchived file
 * @throws IOException If any issue occurs in unzipping the file
 */
public void unzipArchive(String file, File outputDir) throws IOException {

    try (ZipFile zipFile = new ZipFile(file)) {

        final Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();
            final File entryDestination = new File(outputDir, entry.getName());

            if (entry.isDirectory()) {
                // If entry is directory, create directory
                if (!entryDestination.mkdirs() && !entryDestination.exists()) {
                    throw new IOException("Could not create directory: " + entryDestination
                            + " while un-archiving zip: " + file);
                }
            } else {
                // Create parent dirs if required
                if (!entryDestination.getParentFile().mkdirs() && !entryDestination.getParentFile().exists()) {
                    throw new IOException("Could not create parent directory for: " + entryDestination
                            + " while un-archiving zip: " + file);
                }

                // Extract and save the conf file
                InputStream in = null;
                OutputStream out = null;
                try {
                    in = zipFile.getInputStream(entry);
                    out = new FileOutputStream(entryDestination);
                    IOUtils.copy(in, out);
                } finally {
                    if (null != in)
                        IOUtils.closeQuietly(in);
                    if (null != out)
                        IOUtils.closeQuietly(out);
                }
            }
        }
    }
}

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

/**
 * @param dxpFile//  w ww .j  a va2  s . c om
 * @param outputDir
 * @param dxpOptions
 * @throws Exception 
 */
public static void unpackDxpPackage(File dxpFile, File outputDir, DitaDxpOptions dxpOptions, Log log)
        throws Exception {
    ZipFile zipFile = new ZipFile(dxpFile);
    ZipEntry rootMapEntry = getDxpPackageRootMap(zipFile, dxpOptions);
    // rootMapEntry will have a value if we get this far.

    /**
     * At this point could simply unpack the Zip file blindly or could build
     * the map BOS from the root map by processing the Zip file entries and
     * then only unpacking those that are actually used by the map. The latter
     * case would be appropriate for packages that include multiple maps, for 
     * example, when a set of peer root maps have been packaged together. 
     * 
     * For now, just blindly unpacking the whole zip.
     */

    if (dxpOptions.isUnzipAll()) {
        MultithreadedUnzippingController controller = new MultithreadedUnzippingController(dxpOptions);
        if (!dxpOptions.isQuiet())
            log.info("Unzipping entire DXP package \"" + dxpFile.getAbsolutePath() + "\" to output directory \""
                    + outputDir + "\"...");
        controller.unzip(dxpFile, outputDir, true);
        if (!dxpOptions.isQuiet())
            log.info("Unzip complete");
    } else {
        List<String> mapIds = dxpOptions.getRootMaps();
        List<ZipEntry> mapEntries = new ArrayList<ZipEntry>();
        if (mapIds.size() == 0) {
            mapEntries.add(rootMapEntry);
        } else {
            mapEntries = getMapEntries(zipFile, mapIds);
        }
        for (ZipEntry mapEntry : mapEntries) {
            extractMap(zipFile, mapEntry, outputDir, dxpOptions);
        }
    }

}

From source file:com.cubeia.ProtocolGeneratorMojo.java

private void unzipToTmpDir(File zipFile, File tempDir) throws MojoExecutionException {
    try {/*w  w w  .java  2 s . com*/
        ZipFile zip = new ZipFile(zipFile);
        explode(zip, tempDir);
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to unzip distribution", e);
    }
}

From source file:com.impetus.ankush.common.utils.FileNameUtils.java

/**
 * Gets the path from archive.//from www . j a v  a 2 s .c o  m
 * 
 * @param archiveFile
 *            the archive file
 * @param charSequence
 *            the char sequence
 * @return the path from archive
 */
public static String getPathFromArchive(String archiveFile, String charSequence) {
    String path = null;
    ONSFileType fileType = getFileType(archiveFile);

    if (fileType == ONSFileType.TAR_GZ) {
        try {
            GZIPInputStream gzipInputStream = null;
            gzipInputStream = new GZIPInputStream(new FileInputStream(archiveFile));
            TarArchiveInputStream tarInput = new TarArchiveInputStream(gzipInputStream);

            TarArchiveEntry entry;
            while (null != (entry = tarInput.getNextTarEntry())) {
                if (entry.getName().contains(charSequence)) {
                    path = entry.getName();
                    break;
                }
            }

        } catch (FileNotFoundException e) {
            LOG.error(e.getMessage(), e);
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    } else if (fileType == ONSFileType.ZIP) {
        ZipFile zf;
        try {
            zf = new ZipFile(archiveFile);
            Enumeration<? extends ZipEntry> entries = zf.entries();
            String fileName;
            while (entries.hasMoreElements()) {
                fileName = entries.nextElement().getName();
                if (fileName.contains(charSequence)) {
                    path = fileName;
                    break;
                }
            }
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }

    return path;
}

From source file:com.skcraft.launcher.launch.JavaRuntimeFetcher.java

private void extract(File zip, File destination) {
    if (!zip.exists()) {
        throw new UnsupportedOperationException("Attempted to extract non-existent file: " + zip);
    }//from www.j  ava2  s.co  m

    if (destination.mkdirs()) {
        log.log(Level.INFO, "Creating dir: {0}", destination);
    }

    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(zip);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (!entry.isDirectory()) {
                InputStream inputStream = zipFile.getInputStream(entry);
                File file = new File(destination, entry.getName());
                copyFile(inputStream, file, SharedLocale.tr("runtimeFetcher.extract", file.getName()), -1);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        Closer.close(zipFile);
    }
}

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  av a 2s .  co m
        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;
}