Example usage for java.util.jar JarFile close

List of usage examples for java.util.jar JarFile close

Introduction

In this page you can find the example usage for java.util.jar JarFile close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP file.

Usage

From source file:org.ops4j.pax.runner.platform.internal.PlatformImpl.java

/**
 * Validate that the file is an valid bundle.
 * A valid bundle will be a loadable jar file that has manifest and the manifest contains at least an entry for
 * Bundle-SymboliName or Bundle-Name (R3).
 *
 * @param url  original url from where the bundle was created.
 * @param file file to be validated/*from   w  w w  .jav  a2 s.  c  om*/
 *
 * @throws PlatformException if the jar is not a valid bundle
 */
void validateBundle(final URL url, final File file) throws PlatformException {
    String bundleSymbolicName = null;
    String bundleName = null;
    JarFile jar = null;
    try {
        // verify that is a valid jar. Do not verify that is signed (the false param).
        jar = new JarFile(file, false);
        final Manifest manifest = jar.getManifest();
        if (manifest == null) {
            throw new PlatformException("[" + url + "] is not a valid bundle");
        }
        bundleSymbolicName = manifest.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME);
        bundleName = manifest.getMainAttributes().getValue(Constants.BUNDLE_NAME);
    } catch (IOException e) {
        throw new PlatformException("[" + url + "] is not a valid bundle", e);
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException ignore) {
                // just ignore as this is less probably to happen.
            }
        }
    }
    if (bundleSymbolicName == null && bundleName == null) {
        throw new PlatformException("[" + url + "] is not a valid bundle");
    }
}

From source file:com.taobao.android.builder.tasks.app.bundle.ProcessAwbAndroidResources.java

@Override
protected void doFullTaskAction() throws IOException {
    // we have to clean the source folder output in case the package name changed.
    File srcOut = getSourceOutputDir();
    if (srcOut != null) {
        //            FileUtils.emptyFolder(srcOut);
        srcOut.delete();//from w  w w.  j av  a  2s  . c o m
        srcOut.mkdirs();
    }

    getTextSymbolOutputDir().mkdirs();
    getPackageOutputFile().getParentFile().mkdirs();

    @Nullable
    File resOutBaseNameFile = getPackageOutputFile();

    // If are in instant run mode and we have an instant run enabled manifest
    File instantRunManifest = getInstantRunManifestFile();
    File manifestFileToPackage = instantRunBuildContext.isInInstantRunMode() && instantRunManifest != null
            && instantRunManifest.exists() ? instantRunManifest : getManifestFile();

    //awb????
    addAaptOptions();
    AaptPackageProcessBuilder aaptPackageCommandBuilder = new AaptPackageProcessBuilder(manifestFileToPackage,
            getAaptOptions()).setAssetsFolder(getAssetsDir()).setResFolder(getResDir())
                    .setLibraries(getLibraries()).setPackageForR(getPackageForR())
                    .setSourceOutputDir(absolutePath(srcOut))
                    .setSymbolOutputDir(absolutePath(getTextSymbolOutputDir()))
                    .setResPackageOutput(absolutePath(resOutBaseNameFile))
                    .setProguardOutput(absolutePath(getProguardOutputFile())).setType(getType())
                    .setDebuggable(getDebuggable()).setPseudoLocalesEnabled(getPseudoLocalesEnabled())
                    .setResourceConfigs(getResourceConfigs()).setSplits(getSplits())
                    .setPreferredDensity(getPreferredDensity());

    @NonNull
    AtlasBuilder builder = (AtlasBuilder) getBuilder();

    //        MergingLog mergingLog = new MergingLog(getMergeBlameLogFolder());
    //
    //        ProcessOutputHandler processOutputHandler = new ParsingProcessOutputHandler(
    //                new ToolOutputParser(new AaptOutputParser(), getILogger()),
    //                 builder.getErrorReporter());

    ProcessOutputHandler processOutputHandler = new LoggedProcessOutputHandler(getILogger());
    try {
        builder.processAwbResources(aaptPackageCommandBuilder, getEnforceUniquePackageName(),
                processOutputHandler, getMainSymbolFile());
        if (resOutBaseNameFile != null) {
            if (instantRunBuildContext.isInInstantRunMode()) {

                instantRunBuildContext.addChangedFile(FileType.RESOURCES, resOutBaseNameFile);

                // get the new manifest file CRC
                JarFile jarFile = new JarFile(resOutBaseNameFile);
                String currentIterationCRC = null;
                try {
                    ZipEntry entry = jarFile.getEntry(SdkConstants.ANDROID_MANIFEST_XML);
                    if (entry != null) {
                        currentIterationCRC = String.valueOf(entry.getCrc());
                    }
                } finally {
                    jarFile.close();
                }

                // check the manifest file binary format.
                File crcFile = new File(instantRunSupportDir, "manifest.crc");
                if (crcFile.exists() && currentIterationCRC != null) {
                    // compare its content with the new binary file crc.
                    String previousIterationCRC = Files.readFirstLine(crcFile, Charsets.UTF_8);
                    if (!currentIterationCRC.equals(previousIterationCRC)) {
                        instantRunBuildContext.close();
                        //instantRunBuildContext.setVerifierResult(InstantRunVerifierStatus
                        // .BINARY_MANIFEST_FILE_CHANGE);
                    }
                }

                // write the new manifest file CRC.
                Files.createParentDirs(crcFile);
                Files.write(currentIterationCRC, crcFile, Charsets.UTF_8);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new GradleException("process res exception", e);
    }
}

From source file:org.hyperic.hq.product.server.session.ProductPluginDeployer.java

private void unpackJar(File pluginJarFile, File destDir, String prefix) throws Exception {

    JarFile jar = null;
    try {//from ww  w.  ja v  a 2s .  co m
        jar = new JarFile(pluginJarFile);
        for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) {
            JarEntry entry = e.nextElement();
            String name = entry.getName();

            if (name.startsWith(prefix)) {
                name = name.substring(prefix.length());
                if (name.length() == 0) {
                    continue;
                }
                File file = new File(destDir, name);
                if (entry.isDirectory()) {
                    file.mkdirs();
                } else {
                    FileUtil.copyStream(jar.getInputStream(entry), new FileOutputStream(file));
                }
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
    } finally {
        if (jar != null)
            jar.close();
    }
}

From source file:request.processing.ServletLoader.java

public static void loadServlet(String servletDir) {
    try {// w  w  w . ja va  2s .  com
        JarFile jarFile = new JarFile(servletDir);
        Enumeration<JarEntry> e = jarFile.entries();

        URL[] urls = { new URL("jar:file:" + servletDir + "!/") };
        URLClassLoader cl = URLClassLoader.newInstance(urls);
        while (e.hasMoreElements()) {
            try {
                JarEntry je = (JarEntry) e.nextElement();
                if (je.isDirectory() || !je.getName().endsWith(".class")) {
                    continue;
                }
                String className = je.getName().substring(0, je.getName().length() - 6);
                className = className.replace('/', '.');
                Class c = cl.loadClass(className);
                if (Servlet.class.isAssignableFrom(c)) {
                    Constructor<Servlet> constructor = c.getConstructor();
                    Servlet i = constructor.newInstance();
                    namesToServlets.put(c.getSimpleName(), i);
                } else {
                    continue;
                }

            } catch (ClassNotFoundException cnfe) {
                System.err.println("Class not found");
                cnfe.printStackTrace();
            } catch (NoSuchMethodException e1) {
                System.err.println("No such method");
                e1.printStackTrace();
            } catch (SecurityException e1) {
                System.err.println("Security Exception");
                e1.printStackTrace();
            } catch (InstantiationException e1) {
                System.err.println("Instantiation Exception");
                e1.printStackTrace();
            } catch (IllegalAccessException e1) {
                System.err.println("IllegalAccessException");
                e1.printStackTrace();
            } catch (IllegalArgumentException e1) {
                System.err.println("IllegalArgumentException");
                e1.printStackTrace();
            } catch (InvocationTargetException e1) {
                System.err.println("InvocationTargetException");
                e1.printStackTrace();
            }

        }
        jarFile.close();
    } catch (IOException e) {
        System.err.println("Not a jarFile, no biggie. Moving on.");
    }
}

From source file:org.eclipse.ecr.testlib.NXRuntimeTestCase.java

protected void initUrls() throws Exception {
    ClassLoader classLoader = NXRuntimeTestCase.class.getClassLoader();
    if (classLoader instanceof URLClassLoader) {
        urls = ((URLClassLoader) classLoader).getURLs();
    } else if (classLoader.getClass().getName().equals("org.apache.tools.ant.AntClassLoader")) {
        Method method = classLoader.getClass().getMethod("getClasspath");
        String cp = (String) method.invoke(classLoader);
        String[] paths = cp.split(File.pathSeparator);
        urls = new URL[paths.length];
        for (int i = 0; i < paths.length; i++) {
            urls[i] = new URL("file:" + paths[i]);
        }/*from w  w w .j av a2  s .  c o m*/
    } else {
        log.warn("Unknow classloader type: " + classLoader.getClass().getName()
                + "\nWon't be able to load OSGI bundles");
        return;
    }
    // special case for maven surefire with useManifestOnlyJar
    if (urls.length == 1) {
        try {
            URI uri = urls[0].toURI();
            if (uri.getScheme().equals("file") && uri.getPath().contains("surefirebooter")) {
                JarFile jar = new JarFile(new File(uri));
                try {
                    String cp = jar.getManifest().getMainAttributes().getValue(Attributes.Name.CLASS_PATH);
                    if (cp != null) {
                        String[] cpe = cp.split(" ");
                        URL[] newUrls = new URL[cpe.length];
                        for (int i = 0; i < cpe.length; i++) {
                            // Don't need to add 'file:' with maven surefire
                            // >= 2.4.2
                            String newUrl = cpe[i].startsWith("file:") ? cpe[i] : "file:" + cpe[i];
                            newUrls[i] = new URL(newUrl);
                        }
                        urls = newUrls;
                    }
                } finally {
                    jar.close();
                }
            }
        } catch (Exception e) {
            // skip
        }
    }
    StringBuilder sb = new StringBuilder();
    sb.append("URLs on the classpath: ");
    for (URL url : urls) {
        sb.append(url.toString());
        sb.append('\n');
    }
    log.debug(sb.toString());
    readUris = new HashSet<URI>();
    bundles = new HashMap<String, BundleFile>();
}

From source file:org.rhq.enterprise.server.core.plugin.ProductPluginDeployer.java

private boolean isDeploymentValidZipFile(File pluginFile) {
    boolean isValid;
    JarFile jarFile = null;
    try {//from ww w . jav a  2 s.co  m
        // Try to access the plugin jar using the JarFile API.
        // Any weird errors usually mean the file is currently being written but isn't finished yet.
        // Errors could also mean the file is simply corrupted.
        jarFile = new JarFile(pluginFile);
        if (jarFile.size() <= 0) {
            throw new Exception("There are no entries in the plugin file");
        }
        JarEntry entry = jarFile.entries().nextElement();
        entry.getName();
        isValid = true;
    } catch (Exception e) {
        log.info("File [" + pluginFile + "] is not a valid jarfile - "
                + " the file may not have been fully written yet. Cause: " + e);
        isValid = false;
    } finally {
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (Exception e) {
                log.error("Failed to close jar file [" + pluginFile + "]");
            }
        }
    }
    return isValid;
}

From source file:org.ebayopensource.turmeric.plugins.maven.resources.ResourceLocator.java

private URI findFileResource(File path, String pathref) {
    if (path.isFile()) {
        // Assume its an archive.
        String extn = FilenameUtils.getExtension(path.getName());
        if (StringUtils.isBlank(extn)) {
            log.debug("No extension found for file: " + path);
            return null;
        }/*from   w  w  w  .jav  a 2 s.  c o  m*/

        extn = extn.toLowerCase();
        if ("jar".equals(extn)) {
            log.debug("looking inside of jar file: " + path);
            JarFile jar = null;
            try {
                jar = new JarFile(path);
                JarEntry entry = jar.getJarEntry(pathref);
                if (entry == null) {
                    log.debug("JarEntry not found: " + pathref);
                    return null;
                }

                String uripath = String.format("jar:%s!/%s", path.toURI(), entry.getName());
                try {
                    return new URI(uripath);
                } catch (URISyntaxException e) {
                    log.debug("Unable to create URI reference: " + path, e);
                    return null;
                }
            } catch (JarException e) {
                log.debug("Unable to open archive: " + path, e);
                return null;
            } catch (IOException e) {
                log.debug("Unable to open archive: " + path, e);
                return null;
            } finally {
                if (jar != null) {
                    try {
                        jar.close();
                    } catch (IOException e) {
                        log.debug("Unable to close jar: " + path, e);
                    }
                }
            }
        }

        log.debug("Unsupported archive file: " + path);
        return null;
    }

    if (path.isDirectory()) {
        File testFile = new File(path, FilenameUtils.separatorsToSystem(pathref));
        if (testFile.exists() && testFile.isFile()) {
            return testFile.toURI();
        }

        log.debug("Not found in directory: " + testFile);
        return null;
    }

    log.debug("Unable to handle non-file, non-directory " + File.class.getName() + " objects: " + path);
    return null;
}

From source file:org.hyperic.hq.agent.server.AgentDaemon.java

private void loadAgentServerHandlerJars(File[] libJars) throws AgentConfigException {
    AgentServerHandler loadedHandler;/*w  ww. jav a  2s  .  c  o  m*/

    // Save the current context loader, and reset after we load plugin jars
    ClassLoader currentContext = Thread.currentThread().getContextClassLoader();

    for (File libJar : libJars) {
        try {
            JarFile jarFile = new JarFile(libJar);
            Manifest manifest = jarFile.getManifest();
            String mainClass = manifest.getMainAttributes().getValue("Main-Class");
            if (mainClass != null) {
                String jarPath = libJar.getAbsolutePath();
                loadedHandler = this.handlerLoader.loadServerHandler(jarPath);
                this.serverHandlers.add(loadedHandler);
                this.dispatcher.addServerHandler(loadedHandler);
            }
            jarFile.close();
        } catch (Exception e) {
            throw new AgentConfigException("Failed to load " + "'" + libJar + "': " + e.getMessage());
        }
    }

    // Restore the class loader
    Thread.currentThread().setContextClassLoader(currentContext);
}

From source file:org.jahia.configuration.configurators.JahiaGlobalConfiguratorTest.java

public void testGlobalConfiguration() throws Exception {

    JahiaConfigBean websphereDerbyConfigBean;

    Logger logger = LoggerFactory.getLogger(JahiaGlobalConfiguratorTest.class);

    URL configuratorsResourceURL = this.getClass().getClassLoader().getResource("configurators");
    File configuratorsFile = new File(configuratorsResourceURL.toURI());

    websphereDerbyConfigBean = new JahiaConfigBean();
    websphereDerbyConfigBean.setDatabaseType("derby_embedded");
    websphereDerbyConfigBean.setTargetServerType("was");
    websphereDerbyConfigBean.setTargetServerVersion("6.1.0.25");
    websphereDerbyConfigBean.setTargetConfigurationDirectory(configuratorsFile.toString());
    websphereDerbyConfigBean.setCluster_activated("true");
    websphereDerbyConfigBean.setCluster_node_serverId("jahiaServer1");
    websphereDerbyConfigBean.setProcessingServer("true");
    websphereDerbyConfigBean.setLdapActivated("true");
    websphereDerbyConfigBean.setExternalizedConfigActivated(true);
    websphereDerbyConfigBean.setExternalizedConfigExploded(false);
    websphereDerbyConfigBean.setExternalizedConfigTargetPath(configuratorsFile.getPath());
    websphereDerbyConfigBean.setExternalizedConfigClassifier("jahiaServer1");
    websphereDerbyConfigBean.setExternalizedConfigFinalName("jahia-externalized-config");
    websphereDerbyConfigBean.setJeeApplicationLocation(configuratorsFile.toString());
    websphereDerbyConfigBean.setJeeApplicationModuleList(
            "jahia-war:web:jahia.war:jahia,portlet-testsuite:web:websphere-testsuite.war:testsuite,java-example:java:somecode.jar");
    websphereDerbyConfigBean.setJahiaToolManagerUsername("toolmgr");

    JahiaGlobalConfigurator jahiaGlobalConfigurator = new JahiaGlobalConfigurator(new SLF4JLogger(logger),
            websphereDerbyConfigBean);/*from  ww  w  .  j a  v  a  2  s  .co m*/
    jahiaGlobalConfigurator.execute();

    File configFile = new File(configuratorsFile, "jahia-externalized-config-jahiaServer1.jar");
    JarFile configJarFile = new JarFile(configFile);
    try {
        JarEntry licenseJarEntry = configJarFile.getJarEntry("jahia/license.xml");
        assertNotNull("Missing license file in jahia-externalized-config-jahiaServer1.jar file!",
                licenseJarEntry);
        JarEntry jahiaPropertiesJarEntry = configJarFile.getJarEntry("jahia/jahia.jahiaServer1.properties");
        assertNotNull(
                "Missing jahia.jahiaServer1.properties file in jahia-externalized-config-jahiaServer1.jar file!",
                jahiaPropertiesJarEntry);
        JarEntry jahiaAdvancedPropertiesJarEntry = configJarFile
                .getJarEntry("jahia/jahia.node.jahiaServer1.properties");
        assertNotNull(
                "Missing jahia.node.jahiaServer1.properties file in jahia-externalized-config-jahiaServer1.jar file!",
                jahiaAdvancedPropertiesJarEntry);

        InputStream jahiaPropsInputStream = configJarFile.getInputStream(jahiaPropertiesJarEntry);
        Properties jahiaProperties = new Properties();
        jahiaProperties.load(jahiaPropsInputStream);
        assertEquals("Tool manager is not set", "toolmgr", jahiaProperties.get("jahiaToolManagerUsername"));
    } finally {
        configJarFile.close();
    }
    // The following tests are NOT exhaustive
    SAXBuilder saxBuilder = new SAXBuilder();
    saxBuilder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    Document jdomDocument = saxBuilder.build(configuratorsFile.toString() + "/META-INF/application.xml");
    String prefix = "";

    assertAllTextEquals(jdomDocument, "//application/module[@id=\"jahia-war\"]/web/web-uri/text()", prefix,
            "jahia.war");
    assertAllTextEquals(jdomDocument, "//application/module[@id=\"jahia-war\"]/web/context-root/text()", prefix,
            "jahia");
    assertAllTextEquals(jdomDocument, "//application/module[@id=\"portlet-testsuite\"]/web/web-uri/text()",
            prefix, "websphere-testsuite.war");
    assertAllTextEquals(jdomDocument, "//application/module[@id=\"portlet-testsuite\"]/web/context-root/text()",
            prefix, "testsuite");
    assertAllTextEquals(jdomDocument, "//application/module[@id=\"java-example\"]/java/text()", prefix,
            "somecode.jar");

}

From source file:com.taobao.android.builder.tools.multidex.mutli.JarRefactor.java

private Collection<File> generateFirstDexJar(List<String> mainDexList, Collection<File> files)
        throws IOException {

    List<File> jarList = new ArrayList<>();
    List<File> folderList = new ArrayList<>();
    for (File file : files) {
        if (file.isDirectory()) {
            folderList.add(file);/*  ww w . j  a  va2  s.c  o  m*/
        } else {
            jarList.add(file);
        }
    }

    File dir = new File(appVariantContext.getScope().getGlobalScope().getIntermediatesDir(),
            "fastmultidex/" + appVariantContext.getVariantName());
    FileUtils.deleteDirectory(dir);
    dir.mkdirs();

    if (!folderList.isEmpty()) {
        File mergedJar = new File(dir, "jarmerging/combined.jar");
        mergedJar.getParentFile().mkdirs();
        mergedJar.delete();
        mergedJar.createNewFile();
        JarMerger jarMerger = new JarMerger(mergedJar.toPath());
        for (File folder : folderList) {
            jarMerger.addDirectory(folder.toPath());
        }
        jarMerger.close();
        if (mergedJar.length() > 0) {
            jarList.add(mergedJar);
        }
    }

    List<File> result = new ArrayList<>();
    File maindexJar = new File(dir, DexMerger.FASTMAINDEX_JAR + ".jar");

    JarOutputStream mainJarOuputStream = new JarOutputStream(
            new BufferedOutputStream(new FileOutputStream(maindexJar)));

    //First order
    Collections.sort(jarList, new NameComparator());

    for (File jar : jarList) {
        File outJar = new File(dir, FileNameUtils.getUniqueJarName(jar) + ".jar");

        result.add(outJar);
        JarFile jarFile = new JarFile(jar);
        JarOutputStream jos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(outJar)));
        Enumeration<JarEntry> jarFileEntries = jarFile.entries();

        List<String> pathList = new ArrayList<>();
        while (jarFileEntries.hasMoreElements()) {
            JarEntry ze = jarFileEntries.nextElement();
            String pathName = ze.getName();
            if (mainDexList.contains(pathName)) {
                copyStream(jarFile.getInputStream(ze), mainJarOuputStream, ze, pathName);
                pathList.add(pathName);
            }
        }

        if (!pathList.isEmpty()) {
            jarFileEntries = jarFile.entries();
            while (jarFileEntries.hasMoreElements()) {
                JarEntry ze = jarFileEntries.nextElement();
                String pathName = ze.getName();
                if (!pathList.contains(pathName)) {
                    copyStream(jarFile.getInputStream(ze), jos, ze, pathName);
                }
            }
        }

        jarFile.close();
        IOUtils.closeQuietly(jos);

        if (pathList.isEmpty()) {
            FileUtils.copyFile(jar, outJar);
        }
        if (!appVariantContext.getAtlasExtension().getTBuildConfig().isFastProguard() && files.size() == 1) {
            JarUtils.splitMainJar(result, outJar, 1, MAX_CLASSES);
        }
    }

    IOUtils.closeQuietly(mainJarOuputStream);

    Collections.sort(result, new NameComparator());

    result.add(0, maindexJar);

    return result;
}