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.italiangrid.voms.container.Container.java

private void forceTaglibsLoading() {

    if (System.getProperty("voms.disableTaglibsLoading") != null) {
        log.warn("Taglibs loading disabled, as requested by voms.disableTaglibsLoading");
        return;/*from   w  w w.j  a v a2  s .c o m*/
    }

    try {

        String classpath = java.lang.System.getProperty("java.class.path");
        String entries[] = classpath.split(System.getProperty("path.separator"));

        if (entries.length >= 1) {

            JarFile f = new JarFile(entries[0]);
            Attributes attrs = f.getManifest().getMainAttributes();
            Name n = new Name("Class-Path");
            String jarClasspath = attrs.getValue(n);
            String jarEntries[] = jarClasspath.split(" ");

            boolean taglibsFound = false;

            for (String e : jarEntries) {
                if (e.contains(TAGLIBS_JAR_NAME)) {
                    taglibsFound = true;
                    ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();

                    File taglibsJar = new File(e);
                    URLClassLoader newClassLoader = new URLClassLoader(new URL[] { taglibsJar.toURI().toURL() },
                            currentClassLoader);

                    Thread.currentThread().setContextClassLoader(newClassLoader);
                }
            }

            f.close();

            if (!taglibsFound) {
                throw new RuntimeException("Error configuring taglibs classloading!");
            }

        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        System.exit(1);
    }
}

From source file:hotbeans.support.JarFileHotBeanModuleLoader.java

/**
 * Extracts all the files in the module jar file, including nested jar files. The reason for extracting the complete
 * contents of the jar file (and not just the nested jar files) is to make sure the module jar file isn't locked, and
 * thus may be deleted.//from  w  ww  .ja va2  s  .  c  o m
 */
private void extractLibs() throws IOException {
    if (logger.isDebugEnabled())
        logger.debug("Extracting module jar file '" + moduleJarFile + "'.");

    JarFile jarFile = new JarFile(this.moduleJarFile);
    Enumeration entries = jarFile.entries();
    JarEntry entry;
    String entryName;
    File extractedFile = null;
    FileOutputStream extractedFileOutputStream;

    while (entries.hasMoreElements()) {
        entry = (JarEntry) entries.nextElement();
        if ((entry != null) && (!entry.isDirectory())) {
            entryName = entry.getName();
            if (entryName != null) {
                // if( logger.isDebugEnabled() ) logger.debug("Extracting '" + entryName + "'.");

                // Copy nested jar file to temp dir
                extractedFile = new File(this.tempDir, entryName);
                extractedFile.getParentFile().mkdirs();

                extractedFileOutputStream = new FileOutputStream(extractedFile);
                FileCopyUtils.copy(jarFile.getInputStream(entry), extractedFileOutputStream);
                extractedFileOutputStream = null;

                if ((entryName.startsWith(LIB_PATH)) && (entryName.toLowerCase().endsWith(".jar"))) {
                    // Register nested jar file in "class path"
                    super.addURL(extractedFile.toURI().toURL());
                }
            }
        }
    }

    jarFile.close();
    jarFile = null;

    super.addURL(tempDir.toURI().toURL()); // Add temp dir as class path (note that this must be added after all the
                                           // files have been extracted)

    if (logger.isDebugEnabled())
        logger.debug("Done extracting module jar file '" + moduleJarFile + "'.");
}

From source file:org.jtheque.modules.impl.ModuleLoader.java

/**
 * Read the config of the module./*from  w w  w. j  a v a 2  s.  c  o m*/
 *
 * @param file The file of the module.
 *
 * @return The module resources.
 *
 * @throws IOException If an error occurs during Jar File reading.
 * @throws org.jtheque.modules.ModuleException
 *                     If the config cannot be read.
 */
private ModuleResources readConfig(File file) throws IOException, ModuleException {
    JarFile jarFile = null;
    try {
        jarFile = new JarFile(file);

        ZipEntry configEntry = jarFile.getEntry("module.xml");

        if (configEntry == null) {
            return new ModuleResources(CollectionUtils.<ImageResource>emptyList(),
                    CollectionUtils.<I18NResource>emptyList(), CollectionUtils.<Resource>emptyList());
        }

        ModuleResources resources = importConfig(jarFile.getInputStream(configEntry));

        //Install necessary resources before installing the bundle
        for (Resource resource : resources.getResources()) {
            if (resource != null) {
                resourceService.installResource(resource);
            }
        }

        return resources;
    } finally {
        if (jarFile != null) {
            jarFile.close();
        }
    }
}

From source file:org.moe.cli.ParameterParserTest.java

@Test
public void linkFramework() throws Exception {

    File project = tmpDir.newFolder();
    File outputJar = new File(project, "TestFramework.jar");

    // prepare file with ldFlags
    String flags = "-framework TestFramework";
    File ldFlags = new File(project, "ldflags");
    ldFlags.createNewFile();/*ww  w  . ja  va  2s  . c om*/
    PrintWriter write = new PrintWriter(ldFlags);
    write.print(flags);
    write.close();

    ClassLoader cl = this.getClass().getClassLoader();
    URL simFramework = cl.getResource("natives/device/TestFramework.framework");
    URL devFramework = cl.getResource("natives/simulator/TestFramework.framework");

    URL bundle = cl.getResource("moe_logo.png");
    CommandLine argc = parseArgs(new String[] { "--framework",
            String.format("%s:%s", simFramework.getPath(), devFramework.getPath()), "--package-name", "org",
            "--output-file-path", outputJar.getPath(), "--ld-flags", ldFlags.getPath(), "--bundle",
            bundle.getPath() });

    IExecutor executor = ExecutorManager.getExecutorByParams(argc);
    assertNotNull(executor);
    assertTrue(executor instanceof ThirdPartyFrameworkLinkExecutor);

    // generate binding & prepare output jar
    executor.execute();

    // check output jar file existence
    assertTrue(outputJar.exists());

    JarFile jarFile = new JarFile(outputJar);
    Manifest manifest = jarFile.getManifest();

    Attributes attributes = manifest.getMainAttributes();
    String manifestLDFlags = attributes.getValue("MOE_CUSTOM_LINKER_FLAGS");
    assertEquals(flags + ";", manifestLDFlags);

    String manifestBundle = attributes.getValue("MOE_BUNDLE_FILE_RESOURCES");
    assertEquals(manifestBundle, "./bundle/moe_logo.png;");

    String manifestFramework = attributes.getValue("MOE_ThirdpartyFramework_ios_simulator");
    assertEquals(manifestFramework, "./lib/iphonesimulator/TestFramework.framework");

    String manifestDevFramework = attributes.getValue("MOE_ThirdpartyFramework_ios_device");
    assertEquals(manifestDevFramework, "./lib/iphoneos/TestFramework.framework");

    assertNotNull(jarFile.getEntry("bundle/moe_logo.png"));
    assertNotNull(jarFile.getEntry("lib/iphonesimulator/TestFramework.framework"));
    assertNotNull(jarFile.getEntry("lib/iphoneos/TestFramework.framework"));

    jarFile.close();

}

From source file:org.pepstock.jem.util.ReverseURLClassLoader.java

/**
  * Returns the URL of a given resource in the given file which may
  * either be a directory or a jar file.
  *//  w  w  w . j  a  v a2  s  .c  o  m
  * @param file The file (directory or jar) in which to search for
  *             the resource. Must not be <code>null</code>.
  * @param resourceName The name of the resource for which a stream
  *                     is required. Must not be <code>null</code>.
  *
  * @return a stream to the required resource or <code>null</code> if the
  *         resource cannot be found in the given file object.
  */
private URL getResourceURL(URL url, String resourceName) {
    JarFile jFile = null;
    try {
        // gets the file from URL
        File file = new File(url.toURI());
        // if is a directory, then checks on the file system
        // where URL id the parent file and resource name is the file
        if (file.isDirectory()) {
            File resource = new File(file, resourceName);
            // checks if exists
            if (resource.exists()) {
                // returns URL
                return resource.toURI().toURL();
            }
        } else if (file.exists()) {
            // if here, the URL must be a link to a JAR file
            jFile = new JarFile(file);
            // searches in the JAR for the resource name
            JarEntry entry = jFile.getJarEntry(resourceName);
            // if found return the JAR URL
            if (entry != null) {
                return new URL("jar:" + file.toURI().toURL() + "!/" + entry);
            }
        }
    } catch (Exception e) {
        LogAppl.getInstance().ignore(e.getMessage(), e);
    } finally {
        // closes the JAR file if open
        if (jFile != null) {
            try {
                jFile.close();
            } catch (IOException e) {
                LogAppl.getInstance().ignore(e.getMessage(), e);
            }
        }
    }
    return null;
}

From source file:org.primeframework.mvc.util.ClassClasspathResolver.java

private Collection<Class<U>> loadFromJar(File f, Test<Class<U>> test, boolean recursive,
        Iterable<String> locators, boolean embeddable) throws IOException {
    Set<Class<U>> matches = new HashSet<Class<U>>();

    JarFile jarFile;
    try {//from   w  w w  .  java2s.c  o  m
        jarFile = new JarFile(f);
    } catch (IOException e) {
        throw new IOException("Error opening JAR file [" + f.getAbsolutePath() + "]", e);
    }

    Enumeration<JarEntry> en = jarFile.entries();
    while (en.hasMoreElements()) {
        JarEntry entry = en.nextElement();
        String name = entry.getName();

        // Verify against the locators
        for (String locator : locators) {
            int index = name.indexOf(locator + "/");
            boolean match = (!embeddable && index == 0) || (embeddable && index >= 0);
            if (!match) {
                continue;
            }

            match = recursive || name.indexOf('/', index + locator.length() + 1) == -1;
            if (!match) {
                continue;
            }

            Testable<Class<U>> testable = test.prepare(f, jarFile, entry);
            if (testable != null && testable.passes()) {
                matches.add(testable.result());
                break;
            }
        }
    }

    jarFile.close();

    return matches;
}

From source file:org.openmrs.module.ModuleUtil.java

/**
 * Load resource from a jar inside a jar.
 * /*from  ww  w  .j a  v  a 2  s  .co m*/
 * @param outerJarFile jar file that contains a jar file
 * @param innerJarFileLocation inner jar file location relative to the outer jar
 * @param resource path to a resource relative to the inner jar
 * @return resource from the inner jar as an input stream or <code>null</code> if resource cannot be loaded
 */
private static InputStream getResourceFromInnerJar(JarFile outerJarFile, String innerJarFileLocation,
        String resource) {
    File tempFile = null;
    FileOutputStream tempOut = null;
    JarFile innerJarFile = null;
    InputStream innerInputStream = null;
    try {
        tempFile = File.createTempFile("tempFile", "jar");
        tempOut = new FileOutputStream(tempFile);
        ZipEntry innerJarFileEntry = outerJarFile.getEntry(innerJarFileLocation);
        if (innerJarFileEntry != null) {
            IOUtils.copy(outerJarFile.getInputStream(innerJarFileEntry), tempOut);
            innerJarFile = new JarFile(tempFile);
            ZipEntry targetEntry = innerJarFile.getEntry(resource);
            if (targetEntry != null) {
                // clone InputStream to make it work after the innerJarFile is closed
                innerInputStream = innerJarFile.getInputStream(targetEntry);
                byte[] byteArray = IOUtils.toByteArray(innerInputStream);
                return new ByteArrayInputStream(byteArray);
            }
        }
    } catch (IOException e) {
        log.error("Unable to get '" + resource + "' from '" + innerJarFileLocation + "' of '"
                + outerJarFile.getName() + "'", e);
    } finally {
        IOUtils.closeQuietly(tempOut);
        IOUtils.closeQuietly(innerInputStream);

        // close inner jar file before attempting to delete temporary file
        try {
            if (innerJarFile != null) {
                innerJarFile.close();
            }
        } catch (IOException e) {
            log.warn("Unable to close inner jarfile: " + innerJarFile, e);
        }

        // delete temporary file
        if (tempFile != null && !tempFile.delete()) {
            log.warn("Could not delete temporary jarfile: " + tempFile);
        }
    }
    return null;
}

From source file:appeng.recipes.loader.RecipeResourceCopier.java

/**
 * List directory contents for a resource folder. Not recursive. This is basically a brute-force implementation. Works for regular files and also JARs.
 *
 * @param clazz Any java class that lives in the same place as the resources you want.
 * @param path Should end with "/", but not start with one.
 *
 * @return Just the name of each member item, not the full paths.
 *
 * @throws URISyntaxException            if it is a file path and the URL can not be converted to URI
 * @throws IOException                   if jar path can not be decoded
 * @throws UnsupportedOperationException if it is neither in jar nor in file path
 *//*from w w  w  . java 2 s. c o m*/
@Nonnull
private String[] getResourceListing(@Nonnull final Class<?> clazz, @Nonnull final String path)
        throws URISyntaxException, IOException {
    assert clazz != null;
    assert path != null;

    final ClassLoader classLoader = clazz.getClassLoader();
    if (classLoader == null) {
        throw new IllegalStateException(
                "ClassLoader was not found. It was probably loaded at a inappropriate time");
    }

    URL dirURL = classLoader.getResource(path);
    if (dirURL != null) {
        final String protocol = dirURL.getProtocol();
        if (protocol.equals(FILE_PROTOCOL)) {
            // A file path: easy enough

            final URI uriOfURL = dirURL.toURI();
            final File fileOfURI = new File(uriOfURL);
            final String[] filesAndDirectoriesOfURI = fileOfURI.list();

            if (filesAndDirectoriesOfURI == null) {
                throw new IllegalStateException(
                        "Files and Directories were illegal. Either an abstract pathname does not denote a directory, or an I/O error occured.");
            } else {
                return filesAndDirectoriesOfURI;
            }
        }
    }

    if (dirURL == null) {
        /*
         * In case of a jar file, we can't actually find a directory.
         * Have to assume the same jar as clazz.
         */
        final String className = clazz.getName();
        final Matcher matcher = DOT_COMPILE_PATTERN.matcher(className);
        final String me = matcher.replaceAll("/") + CLASS_EXTENSION;
        dirURL = classLoader.getResource(me);
    }

    if (dirURL != null) {
        final String protocol = dirURL.getProtocol();
        if (protocol.equals(JAR_PROTOCOL)) {
            /* A JAR path */
            final String dirPath = dirURL.getPath();
            final String jarPath = dirPath.substring(5, dirPath.indexOf('!')); // strip out only
            // the JAR file
            final JarFile jar = new JarFile(URLDecoder.decode(jarPath, UTF_8_ENCODING));
            try {
                final Enumeration<JarEntry> entries = jar.entries(); // gives ALL entries in jar
                final Collection<String> result = new HashSet<String>(INITIAL_RESOURCE_CAPACITY); // avoid duplicates

                // in case it is a
                // subdirectory
                while (entries.hasMoreElements()) {
                    final JarEntry entry = entries.nextElement();
                    final String entryFullName = entry.getName();
                    if (entryFullName.startsWith(path)) { // filter according to the path
                        String entryName = entryFullName.substring(path.length());
                        final int checkSubDir = entryName.indexOf('/');
                        if (checkSubDir >= 0) {
                            // if it is a subdirectory, we just return the directory name
                            entryName = entryName.substring(0, checkSubDir);
                        }
                        result.add(entryName);
                    }
                }

                return result.toArray(new String[result.size()]);
            } finally {
                jar.close();
            }
        }
    }

    throw new UnsupportedOperationException("Cannot list files for URL " + dirURL);
}

From source file:com.liferay.ide.project.core.util.ProjectImportUtil.java

/**
 * This method is used to validate whether the given plugin binary is a valid Liferay Plugin Archieve
 *
 * @param binaryFile//from w  w  w  . j  av  a2s  .  c  o m
 *            - the binary file to be validated
 * @return
 */
public static boolean isValidLiferayPlugin(File binaryFile) {
    boolean isValid = false;

    JarFile pluginBinary = null;

    try {
        pluginBinary = new JarFile(binaryFile);

        BinaryProjectRecord tempRecord = new BinaryProjectRecord(binaryFile);

        // Check for liferay-plugin-package.properties or liferay-plugin-package.xml
        JarEntry lfrPluginPkgPropsEntry = pluginBinary
                .getJarEntry(getConfigFileLocation(ILiferayConstants.LIFERAY_PLUGIN_PACKAGE_PROPERTIES_FILE));
        JarEntry lfrPluginPkgXmlEntry = pluginBinary.getJarEntry(
                getConfigFileLocation(ILiferayConstants.LIFERAY_PLUGIN_PACKAGE_PROPERTIES_XML_FILE));

        if (lfrPluginPkgPropsEntry != null || lfrPluginPkgXmlEntry != null) {
            isValid = true;
        }

        if (tempRecord.isHook()) {
            isValid = (isValid && pluginBinary
                    .getJarEntry(getConfigFileLocation(ILiferayConstants.LIFERAY_HOOK_XML_FILE)) != null);
        } else if (tempRecord.isLayoutTpl()) {
            isValid = (isValid || pluginBinary
                    .getJarEntry(getConfigFileLocation(ILiferayConstants.LIFERAY_LAYOUTTPL_XML_FILE)) != null);
        } else if (tempRecord.isPortlet()) {
            isValid = (isValid && pluginBinary
                    .getJarEntry(getConfigFileLocation(ILiferayConstants.LIFERAY_PORTLET_XML_FILE)) != null);
        } else if (tempRecord.isTheme()) {
            isValid = (isValid || pluginBinary.getJarEntry(
                    getConfigFileLocation(ILiferayConstants.LIFERAY_LOOK_AND_FEEL_XML_FILE)) != null);
        }

        if (!isValid) {
            return isValid;
        } else {
            // check if its a valid web Archieve
            isValid = isValid
                    || pluginBinary.getJarEntry(getConfigFileLocation(ILiferayConstants.WEB_XML_FILE)) != null;
        }
    } catch (IOException e) {
        isValid = false;
    } finally {
        if (pluginBinary != null) {
            try {
                pluginBinary.close();
            } catch (IOException e) {
            }
        }
    }

    return isValid;
}

From source file:org.spoutcraft.launcher.launch.MinecraftClassLoader.java

private Class<?> findClassInjar(String name, File file) throws ClassNotFoundException {
    byte classByte[];
    Class<?> result = null;
    JarFile jar = null;
    try {/*w  ww  .  j  a  va  2s  .c o  m*/
        jar = new JarFile(file);
        JarEntry entry = jar.getJarEntry(name.replace(".", "/") + ".class");
        if (entry != null) {
            InputStream is = jar.getInputStream(entry);
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
            int next = is.read();
            while (-1 != next) {
                byteStream.write(next);
                next = is.read();
            }

            classByte = byteStream.toByteArray();
            result = defineClass(name, classByte, 0, classByte.length,
                    new CodeSource(file.toURI().toURL(), (CodeSigner[]) null));
            loadedClasses.put(name, result);
            return result;
        }
    } catch (FileNotFoundException e) {
        // Assume temp file has been cleaned if the thread is interrupted
        if (!Thread.currentThread().isInterrupted()) {
            e.printStackTrace();
        }
    } catch (ZipException zipEx) {
        System.out.println("Failed to open " + name + " from " + file.getPath());
        zipEx.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            jar.close();
        } catch (IOException ignore) {
        }
    }
    return null;
}