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.symbian.driver.remoting.client.TestClient.java

/**
 * Update a test package to be sent to a remote master.
 * //from w w  w. jav  a  2  s .c  o  m
 * @param aWorkingFolder
 *            String a working directory
 * @param aTestPackage
 *            String a test package name
 * @param aImage
 *            String a image name
 * @param aPlatsec
 *            true/false ON/OFF
 * 
 * @return the name of the updated test package
 */
public String updatePackage(String aWorkingFolder, String aTestPackage, String aImage, boolean aPlatsec,
        boolean aSysbin, boolean aTestexec, String aTransport, String aRdebug, boolean aTefLite) {
    String lTPUpdatedName = "updated_" + aTestPackage;
    try {
        Zipper lZip = new Zipper();

        File lWorkingFolder = new File(aWorkingFolder);
        File lTestPackageFile = new File(lWorkingFolder, aTestPackage);
        LOGGER.fine("Unzipping " + lTestPackageFile.toString() + "  To: " + lWorkingFolder.toString());

        // enumerate the contained files to be removed after being
        // repackaged
        Enumeration<? extends ZipEntry> lEnumer = (new ZipFile(lTestPackageFile)).entries();
        Vector<String> lUnzippedFileNames = new Vector<String>();

        while (lEnumer.hasMoreElements()) {
            String entryName = ((ZipEntry) lEnumer.nextElement()).getName();
            lUnzippedFileNames.addElement(entryName);
        }

        LOGGER.fine("Unzipping " + lTestPackageFile.toString() + "  To: " + lWorkingFolder.toString());

        // unzip testpackage
        Zipper.Unzip(lTestPackageFile, lWorkingFolder);

        // update manifest
        BufferedWriter lBw = new BufferedWriter(
                new FileWriter(lWorkingFolder.getCanonicalPath() + File.separator + "Manifest.mf", true));
        PrintWriter lPw = new PrintWriter(lBw);

        if (aImage != null) {
            lPw.println("romFile=" + aImage);
        }

        lPw.println("platsec=" + aPlatsec);

        if (aTransport != null) {
            lPw.println("transport=" + aTransport);
        }

        lPw.println("sysbin=" + aSysbin);

        lPw.println("statlite=" + aSysbin);

        lPw.println("teflite=" + aTefLite);

        lPw.println("testexec=" + aTestexec);

        if (aRdebug != null) {
            lPw.println("rdebug=" + aRdebug);
        }

        lPw.flush();
        lPw.close();
        lBw.close();

        // add image (rom by the moment)
        if (aImage != null) {
            lZip.addFile(new File(lWorkingFolder.getCanonicalPath() + File.separator + aImage));
        }
        // zip testpackage

        for (int i = 0; i < lUnzippedFileNames.size(); i++) {
            LOGGER.fine("Adding file : " + lWorkingFolder.toString() + " + " + lUnzippedFileNames.elementAt(i));
            lZip.addFile(
                    new File(lWorkingFolder.toString() + File.separator + lUnzippedFileNames.elementAt(i)));
        }

        LOGGER.fine("Zipping the updated package");
        lZip.zip(new File(lWorkingFolder, lTPUpdatedName), lWorkingFolder.getCanonicalPath());

        // delete all files previously unzipped in the working folder

        for (int i = 0; i < lUnzippedFileNames.size(); i++) {
            new File(lWorkingFolder + lUnzippedFileNames.elementAt(i)).delete();
        }

    } catch (IOException lException) {
        LOGGER.log(Level.SEVERE, "Failed to update package. " + lException.getMessage(), lException);
        return null;
    }

    return lTPUpdatedName;
}

From source file:com.asakusafw.m3bp.compiler.inspection.cli.Cli.java

private static InspectionNode load0(File file, InspectionNodeRepository repository) throws IOException {
    LOG.debug("loading file: {}", file); //$NON-NLS-1$
    if (file.getName().endsWith(".jar")) {
        LOG.debug("extracting file from jar: {} ({})", file, M3bpPackage.PATH_PLAN_INSPECTION); //$NON-NLS-1$
        try (ZipFile zip = new ZipFile(file)) {
            ZipEntry entry = zip.getEntry(M3bpPackage.PATH_PLAN_INSPECTION.toPath());
            if (entry == null) {
                throw new FileNotFoundException(MessageFormat.format("{0} does not contain {1}", file,
                        M3bpPackage.PATH_PLAN_INSPECTION));
            }/*  w  w w.ja v  a  2  s . co  m*/
            try (InputStream input = zip.getInputStream(entry)) {
                return repository.load(input);
            }
        }
    } else {
        try (InputStream input = new FileInputStream(file)) {
            return repository.load(input);
        }
    }
}

From source file:org.cloudfoundry.client.lib.SampleProjects.java

private static File explodeTestApp(File file, TemporaryFolder temporaryFolder) throws IOException {
    File unpackDir = temporaryFolder.newFolder(file.getName());
    if (unpackDir.exists()) {
        FileUtils.forceDelete(unpackDir);
    }// w  w  w  .j  av a2  s.c  om
    unpackDir.mkdir();
    ZipFile zipFile = new ZipFile(file);
    try {
        unpackZip(zipFile, unpackDir);
    } finally {
        zipFile.close();
    }
    return unpackDir;
}

From source file:net.firejack.platform.installation.processor.OFRInstallProcessor.java

private void installOFR(File ofr) throws IOException {
    ZipFile zipFile = null;/*from ww w .ja v a 2s.  com*/
    try {
        zipFile = new ZipFile(ofr);

        String packageXmlUploadedFile = null;
        String resourceZipUploadedFile = null;
        String codeWarUploadedFile = null;
        Enumeration entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();

            if (PackageFileType.PACKAGE_XML.getOfrFileName().equals(entry.getName())) {
                packageXmlUploadedFile = SecurityHelper.generateRandomSequence(16)
                        + PackageFileType.PACKAGE_XML.getDotExtension();
                OPFEngine.FileStoreService.upload(OpenFlame.FILESTORE_BASE, packageXmlUploadedFile,
                        zipFile.getInputStream(entry), helper.getTemp());
            } else if (PackageFileType.RESOURCE_ZIP.getOfrFileName().equals(entry.getName())) {
                resourceZipUploadedFile = SecurityHelper.generateRandomSequence(16)
                        + PackageFileType.RESOURCE_ZIP.getDotExtension();
                OPFEngine.FileStoreService.upload(OpenFlame.FILESTORE_BASE, resourceZipUploadedFile,
                        zipFile.getInputStream(entry), helper.getTemp());
            } else if (PackageFileType.APP_WAR.getOfrFileName().equals(entry.getName())) {
                codeWarUploadedFile = SecurityHelper.generateRandomSequence(16)
                        + PackageFileType.APP_WAR.getDotExtension();
                OPFEngine.FileStoreService.upload(OpenFlame.FILESTORE_BASE, codeWarUploadedFile,
                        zipFile.getInputStream(entry), helper.getTemp());
            }
        }

        InputStream packageXml = OPFEngine.FileStoreService.download(OpenFlame.FILESTORE_BASE,
                packageXmlUploadedFile, helper.getTemp());
        InputStream resourceZip = OPFEngine.FileStoreService.download(OpenFlame.FILESTORE_BASE,
                resourceZipUploadedFile, helper.getTemp());
        StatusProviderTranslationResult statusResult = packageInstallationService.activatePackage(packageXml,
                resourceZip);
        IOUtils.closeQuietly(packageXml);
        IOUtils.closeQuietly(resourceZip);

        if (statusResult.getResult() && statusResult.getPackage() != null) {
            PackageModel packageRN = statusResult.getPackage();
            if (packageRN != null) {
                Integer oldVersion = packageRN.getVersion();
                packageRN = packageStore.updatePackageVersion(packageRN.getId(),
                        statusResult.getVersionNumber());

                if (statusResult.getOldPackageXml() != null) {
                    packageVersionHelper.archiveVersion(packageRN, oldVersion, statusResult.getOldPackageXml());
                }

                String packageXmlName = packageRN.getName() + PackageFileType.PACKAGE_XML.getDotExtension();
                packageXml = OPFEngine.FileStoreService.download(OpenFlame.FILESTORE_BASE,
                        packageXmlUploadedFile, helper.getTemp());
                OPFEngine.FileStoreService.upload(OpenFlame.FILESTORE_BASE, packageXmlName, packageXml,
                        helper.getVersion(), String.valueOf(packageRN.getId()),
                        String.valueOf(packageRN.getVersion()));
                IOUtils.closeQuietly(packageXml);

                if (resourceZipUploadedFile != null) {
                    String resourceZipName = packageRN.getName()
                            + PackageFileType.RESOURCE_ZIP.getDotExtension();
                    resourceZip = OPFEngine.FileStoreService.download(OpenFlame.FILESTORE_BASE,
                            resourceZipUploadedFile, helper.getTemp());
                    OPFEngine.FileStoreService.upload(OpenFlame.FILESTORE_BASE, resourceZipName, resourceZip,
                            helper.getVersion(), String.valueOf(packageRN.getId()),
                            String.valueOf(packageRN.getVersion()));
                    IOUtils.closeQuietly(resourceZip);
                }

                //                    File webapps = new File(Env.CATALINA_BASE.getValue(), "webapps");
                //                    if (codeWarUploadedFile != null && webapps.exists()) {
                //                        FileUtils.copyFile(codeWarUploadedFile, new File(webapps, packageRN.getName() + PackageFileType.APP_WAR.getDotExtension()));
                //                    }

                if (codeWarUploadedFile != null) {
                    String codeWarName = packageRN.getName() + PackageFileType.APP_WAR.getDotExtension();
                    InputStream warstream = OPFEngine.FileStoreService.download(OpenFlame.FILESTORE_BASE,
                            codeWarUploadedFile, helper.getTemp());
                    OPFEngine.FileStoreService.upload(OpenFlame.FILESTORE_BASE, codeWarName, warstream,
                            helper.getVersion(), String.valueOf(packageRN.getId()),
                            String.valueOf(packageRN.getVersion()));
                    IOUtils.closeQuietly(warstream);
                }

                String packageFilename = packageRN.getName() + PackageFileType.PACKAGE_OFR.getDotExtension();
                FileInputStream stream = new FileInputStream(ofr);
                OPFEngine.FileStoreService.upload(OpenFlame.FILESTORE_BASE, packageFilename, stream,
                        helper.getVersion(), String.valueOf(packageRN.getId()),
                        String.valueOf(packageRN.getVersion()));
                IOUtils.closeQuietly(stream);
            } else {
                throw new BusinessFunctionException("Package archive has not created.");
            }
        }
    } finally {
        if (zipFile != null)
            zipFile.close();
    }
}

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  ww.  jav  a  2  s  .c  o  m

    // 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:com.enioka.jqm.tools.LibraryCache.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"));

    // 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;/*from  www  . java 2  s  .c o m*/
        FileOutputStream os = null;

        try {
            ZipFile 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;
                }
            }
            zf.close();
        } catch (Exception e) {
            throw new JqmPayloadException("Could not handle pom inside jar", e);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
        }
    }

    // 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);
                    IOUtils.closeQuietly(is);
                    IOUtils.closeQuietly(os);
                }
            }
        } catch (Exception e) {
            throw new JqmPayloadException("Could not handle internal lib directory", e);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
            try {
                zf.close();
            } catch (Exception e) {
                jqmlogger.warn("could not close jar file", e);
            }
        }

        // 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");

        // Retrieve resolver configuration
        List<GlobalParameter> repolist = em
                .createQuery("SELECT gp FROM GlobalParameter gp WHERE gp.key = :repo", GlobalParameter.class)
                .setParameter("repo", "mavenRepo").getResultList();
        List<GlobalParameter> settings = em
                .createQuery("SELECT gp FROM GlobalParameter gp WHERE gp.key = :k", GlobalParameter.class)
                .setParameter("k", "mavenSettingsCL").getResultList();
        List<GlobalParameter> settingFiles = em
                .createQuery("SELECT gp FROM GlobalParameter gp WHERE gp.key = :k", GlobalParameter.class)
                .setParameter("k", "mavenSettingsFile").getResultList();

        boolean withCentral = false;
        String withCustomSettings = null;
        String withCustomSettingsFile = null;
        if (settings.size() == 1 && settingFiles.isEmpty()) {
            jqmlogger.trace("Custom settings file will be used: " + settings.get(0).getValue());
            withCustomSettings = settings.get(0).getValue();
        }
        if (settingFiles.size() == 1) {
            jqmlogger.trace("Custom settings file will be used: " + settingFiles.get(0).getValue());
            withCustomSettingsFile = settingFiles.get(0).getValue();
        }

        // Configure resolver
        ConfigurableMavenResolverSystem resolver = Maven.configureResolver();
        if (withCustomSettings != null && withCustomSettingsFile == null) {
            resolver.fromClassloaderResource(withCustomSettings);
        }
        if (withCustomSettingsFile != null) {
            resolver.fromFile(withCustomSettingsFile);
        }

        for (GlobalParameter gp : repolist) {
            if (gp.getValue().contains("repo1.maven.org")) {
                withCentral = true;
            }
            resolver = resolver.withRemoteRepo(MavenRemoteRepositories
                    .createRemoteRepository(gp.getId().toString(), gp.getValue(), "default")
                    .setUpdatePolicy(MavenUpdatePolicy.UPDATE_POLICY_NEVER));
        }
        resolver.withMavenCentralRepo(withCentral);

        // 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
        int size = 0;
        for (File artifact : depFiles) {
            if (!"pom".equals(FilenameUtils.getExtension(artifact.getName()))) {
                size++;
            }
        }
        URL[] tmp = new URL[size];
        int i = 0;
        for (File artifact : depFiles) {
            if ("pom".equals(FilenameUtils.getExtension(artifact.getName()))) {
                continue;
            }
            try {
                tmp[i] = artifact.toURI().toURL();
            } catch (MalformedURLException e) {
                throw new JqmPayloadException("Incorrect dependency in POM file", e);
            }
            i++;
        }

        // 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:com.googlecode.android_scripting.ZipExtractorTask.java

private long unzip() throws Exception {
    long extractedSize = 0l;
    Enumeration<? extends ZipEntry> entries;
    if (mInput.isFile() && mInput.getName().contains(".gz")) {
        InputStream stream = new FileInputStream(mInput);
        GZIPInputStream gzipStream = new GZIPInputStream(stream);
        InputSource is = new InputSource(gzipStream);
        InputStream input = new BufferedInputStream(is.getByteStream());
        File destination = new File(mOutput, "php");
        ByteArrayBuffer baf = new ByteArrayBuffer(255000);
        int current = 0;
        while ((current = input.read()) != -1) {
            baf.append((byte) current);
        }/*from   w  ww  . j av  a  2s  . com*/

        FileOutputStream output = new FileOutputStream(destination);
        output.write(baf.toByteArray());
        output.close();
        Log.d("written!");
        return baf.toByteArray().length;
    }
    ZipFile zip = new ZipFile(mInput);
    long uncompressedSize = getOriginalSize(zip);

    publishProgress(0, (int) uncompressedSize);

    entries = zip.entries();

    try {
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.isDirectory()) {
                // Not all zip files actually include separate directory entries.
                // We'll just ignore them
                // and create them as necessary for each actual entry.
                continue;
            }
            File destination = new File(mOutput, entry.getName());
            if (!destination.getParentFile().exists()) {
                destination.getParentFile().mkdirs();
            }
            if (destination.exists() && mContext != null && !mReplaceAll) {
                Replace answer = showDialog(entry.getName());
                switch (answer) {
                case YES:
                    break;
                case NO:
                    continue;
                case YESTOALL:
                    mReplaceAll = true;
                    break;
                default:
                    return extractedSize;
                }
            }
            ProgressReportingOutputStream outStream = new ProgressReportingOutputStream(destination);
            extractedSize += IoUtils.copy(zip.getInputStream(entry), outStream);
            outStream.close();
        }
    } finally {
        try {
            zip.close();
        } catch (Exception e) {
            // swallow this exception, we are only interested in the original one
        }
    }
    Log.v("Extraction is complete.");
    return extractedSize;
}

From source file:ClassFinder.java

/**
 * Recursively search through Directories with special checks to recognize
 * zip and jar files. (Zip and Jar files return true from
 * &lt;File&gt;.isDirectory())/*from  w  w  w.  ja v  a  2 s  . co  m*/
 * @param base the base file path to search
 * @param current the current recursively searched file path being searched
 */
private void processFile(String base, String current) {
    File currentDirectory = new File(base + File.separatorChar + current);

    // Handle special for archives
    if (isArchive(currentDirectory.getName())) {
        try {
            processZip(new ZipFile(currentDirectory));
        } catch (Exception e) {
            // The directory was not found so the classpath was probably in
            // error or we don't have rights to it
        }
        return;
    } else {

        Set directories = new HashSet();

        File[] children = currentDirectory.listFiles();

        // if no children, return
        if (children == null || children.length == 0) {
            return;
        }

        // check for classfiles
        for (int i = 0; i < children.length; i++) {
            File child = children[i];
            if (child.isDirectory()) {
                directories.add(children[i]);
            } else {
                if (child.getName().endsWith(".class")) {
                    String className = getClassName(
                            current + ((current == "") ? "" : File.separator) + child.getName());
                    addClassName(className);
                    this.foundClasses++;
                }
            }
        }

        //call process file on each directory.  This is an iterative call!!
        for (Iterator i = directories.iterator(); i.hasNext();) {
            processFile(base, current + ((current == "") ? "" : File.separator) + ((File) i.next()).getName());
        }
    }
}

From source file:com.wavemaker.tools.deployment.cloudfoundry.CloudFoundryDeploymentTarget.java

@Deprecated
String deploy(File webapp, DeploymentInfo deploymentInfo) throws DeploymentStatusException {
    try {/*from  w w w  .ja  va  2 s  .com*/
        validateWar(webapp);
        ZipFile zipFile = new ZipFile(webapp);
        ApplicationArchive applicationArchive = new ZipApplicationArchive(zipFile);
        return doDeploy(applicationArchive, deploymentInfo);
    } catch (IOException e) {
        throw new WMRuntimeException(e);
    }
}

From source file:gov.nih.nci.caintegrator.common.Cai2Util.java

/**
 * Validate a ZIP file./*  ww w.  j  av a2s.c  om*/
 * @param file the zip file to be validated.
 * @return boolean if valid or not.
 */
public static boolean isValidZipFile(final File file) {
    ZipFile zipfile = null;
    try {
        zipfile = new ZipFile(file);
        ZipFile zipIn2 = new ZipFile(file);
        zipIn2.close();
        LOGGER.info("zipFile validated = " + file.getAbsolutePath());
        return true;
    } catch (ZipException e) {
        return false;
    } catch (IOException e) {
        return false;
    } catch (Exception e) {
        return false;
    } finally {
        try {
            if (zipfile != null) {
                zipfile.close();
                zipfile = null;
            }
        } catch (Exception e) {
            LOGGER.info("Exception in isValidZipFile = " + e);
        }
    }
}