Example usage for java.util.jar JarFile entries

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

Introduction

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

Prototype

public Enumeration<JarEntry> entries() 

Source Link

Document

Returns an enumeration of the jar file entries.

Usage

From source file:org.argouml.moduleloader.ModuleLoader2.java

/**
 * Check a jar file for an ArgoUML extension/module.
 * <p>/* w w w  .  ja v a  2s  . c  o  m*/
 *
 * If there isn't a manifest or it isn't readable, we fall back to using the
 * raw JAR entries.
 *
 * @param classloader
 *            The classloader to use.
 * @param file
 *            The file to process.
 * @throws ClassNotFoundException
 *             if the manifest file contains a class that doesn't exist.
 */
private void processJarFile(ClassLoader classloader, File file) throws ClassNotFoundException {

    LOG.log(Level.INFO, "Opening jar file {0}", file);
    JarFile jarfile = null;
    try {
        jarfile = new JarFile(file);
    } catch (IOException e) {
        LOG.log(Level.SEVERE, "Unable to open " + file, e);
        return;
    } finally {
        IOUtils.closeQuietly(jarfile);
    }

    Manifest manifest;
    try {
        manifest = jarfile.getManifest();
        if (manifest == null) {
            // We expect all extensions to have a manifest even though we
            // can operate without one if necessary.
            LOG.log(Level.WARNING, file + " does not have a manifest");
        }
    } catch (IOException e) {
        LOG.log(Level.SEVERE, "Unable to read manifest of " + file, e);
        return;
    }

    // TODO: It is a performance drain to load all classes at startup time.
    // They should be lazy loaded when needed. Instead of scanning all
    // classes for ones which implement our loadable module interface, we
    // should use a manifest entry or a special name/name pattern that we
    // look for to find the single main module class to load here. - tfm

    boolean loadedClass = false;
    if (manifest == null) {
        Enumeration<JarEntry> jarEntries = jarfile.entries();
        while (jarEntries.hasMoreElements()) {
            JarEntry entry = jarEntries.nextElement();
            loadedClass = loadedClass | processEntry(classloader, entry.getName());
        }
    } else {
        Map<String, Attributes> entries = manifest.getEntries();
        for (String key : entries.keySet()) {
            // Look for our specification
            loadedClass = loadedClass | processEntry(classloader, key);
        }
    }

    // Add this to search list for I18N properties
    // (Done for both modules & localized property file sets)
    Translator.addClassLoader(classloader);

    // If it didn't have a loadable module class and it doesn't look like
    // a localized property set, warn the user that something funny is in
    // their extension directory
    if (!loadedClass && !file.getName().contains("argouml-i18n-")) {
        LOG.log(Level.SEVERE, "Failed to find any loadable ArgoUML modules in jar " + file);
    }
}

From source file:org.olat.core.util.i18n.I18nManager.java

/**
 * Searches within a jar file for available languages.
 * //from  w w w  .j  a  v  a2 s  . c  om
 * @param jarFile
 * @param checkForExecutables true: check if jar contains java or class files
 *          and return an empty set if such executable files are found; false
 *          don't check or care
 * @return Set of language keys, can be empty but never null
 */
public Set<String> sarchForAvailableLanguagesInJarFile(File jarFile, boolean checkForExecutables) {
    Set<String> foundLanguages = new TreeSet<String>();
    JarFile jar = null;
    try {
        jar = new JarFile(jarFile);
        Enumeration<JarEntry> jarEntries = jar.entries();
        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();
            String jarEntryName = jarEntry.getName();
            // check for executables
            if (checkForExecutables && (jarEntryName.endsWith("java") || jarEntryName.endsWith("class"))) {
                return new TreeSet<String>();
            }
            // search for core util in jar
            if (jarEntryName
                    .indexOf(I18nModule.getCoreFallbackBundle().replace(".", "/") + "/" + I18N_DIRNAME) != -1) {
                // don't add overlayLocales as selectable
                // availableLanguages
                if (jarEntryName.indexOf("__") == -1
                        && jarEntryName.indexOf(I18nModule.LOCAL_STRINGS_FILE_PREFIX) != -1) {
                    String lang = jarEntryName.substring(
                            jarEntryName.indexOf(I18nModule.LOCAL_STRINGS_FILE_PREFIX)
                                    + I18nModule.LOCAL_STRINGS_FILE_PREFIX.length(),
                            jarEntryName.lastIndexOf("."));
                    foundLanguages.add(lang);
                    if (isLogDebugEnabled())
                        logDebug("Adding lang::" + lang + " from filename::" + jarEntryName + " in jar::"
                                + jar.getName(), null);
                }
            }
        }
    } catch (IOException e) {
        throw new OLATRuntimeException("Error when looking up i18n files in jar::" + jarFile.getAbsolutePath(),
                e);
    } finally {
        IOUtils.closeQuietly(jar);
    }
    return foundLanguages;
}

From source file:org.olat.core.util.i18n.I18nManager.java

/**
 * Copy the given set of languages from the given jar to the configured i18n
 * source directories. This method can only be called in a translation
 * server environment./*www. j  a v a  2  s  .  c  om*/
 * 
 * @param jarFile
 * @param toCopyI18nKeys
 */
public void copyLanguagesFromJar(File jarFile, Collection<String> toCopyI18nKeys) {
    if (!I18nModule.isTransToolEnabled()) {
        throw new AssertException(
                "Programming error - can only copy i18n files from a language pack to the source when in translation mode");
    }
    JarFile jar = null;
    try {
        jar = new JarFile(jarFile);
        Enumeration<JarEntry> jarEntries = jar.entries();
        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();
            String jarEntryName = jarEntry.getName();
            // Check if this entry is a language file
            for (String i18nKey : toCopyI18nKeys) {
                if (jarEntryName.endsWith(I18N_DIRNAME + "/" + I18nModule.LOCAL_STRINGS_FILE_PREFIX + i18nKey
                        + I18nModule.LOCAL_STRINGS_FILE_POSTFIX)) {
                    File targetBaseDir;
                    if (i18nKey.equals("de") || i18nKey.equals("en")) {
                        targetBaseDir = I18nModule.getTransToolApplicationLanguagesSrcDir();
                    } else {
                        targetBaseDir = I18nModule.getTransToolApplicationOptLanguagesSrcDir();
                    }
                    // Copy file
                    File targetFile = new File(targetBaseDir, jarEntryName);
                    targetFile.getParentFile().mkdirs();
                    FileUtils.save(jar.getInputStream(jarEntry), targetFile);
                    // Check that saved properties file is empty, if so remove it 
                    Properties props = new Properties();
                    props.load(new FileInputStream(targetFile));
                    if (props.size() == 0) {
                        targetFile.delete();
                        // Delete empty parent dirs recursively
                        File parent = targetFile.getParentFile();
                        while (parent != null && parent.list() != null && parent.list().length == 0) {
                            parent.delete();
                            parent = parent.getParentFile();
                        }
                    }
                    // Continue with next jar entry
                    break;
                }
            }
        }
    } catch (IOException e) {
        throw new OLATRuntimeException(
                "Error when copying up i18n files from a jar::" + jarFile.getAbsolutePath(), e);
    } finally {
        IOUtils.closeQuietly(jar);
    }
}

From source file:org.voltdb.compiler.VoltCompiler.java

public List<Class<?>> getInnerClasses(Class<?> c) throws VoltCompilerException {
    ImmutableList.Builder<Class<?>> builder = ImmutableList.builder();
    ClassLoader cl = c.getClassLoader();
    if (cl == null) {
        cl = Thread.currentThread().getContextClassLoader();
    }/*from  ww w  .j av a 2 s.c o  m*/

    // if loading from an InMemoryJarFile, the process is a bit different...
    if (cl instanceof JarLoader) {
        String[] classes = ((JarLoader) cl).getInnerClassesForClass(c.getName());
        for (String innerName : classes) {
            Class<?> clz = null;
            try {
                clz = cl.loadClass(innerName);
            } catch (ClassNotFoundException e) {
                String msg = "Unable to load " + c + " inner class " + innerName
                        + " from in-memory jar representation.";
                throw new VoltCompilerException(msg);
            }
            assert (clz != null);
            builder.add(clz);
        }
    } else {
        String stem = c.getName().replace('.', '/');
        String cpath = stem + ".class";
        URL curl = cl.getResource(cpath);
        if (curl == null) {
            throw new VoltCompilerException(String.format("Failed to find class file %s in jar.", cpath));
        }

        // load from an on-disk jar
        if ("jar".equals(curl.getProtocol())) {
            Pattern nameRE = Pattern.compile("\\A(" + stem + "\\$[^/]+).class\\z");
            String jarFN;
            try {
                jarFN = URLDecoder.decode(curl.getFile(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                String msg = "Unable to UTF-8 decode " + curl.getFile() + " for class " + c;
                throw new VoltCompilerException(msg);
            }
            jarFN = jarFN.substring(5, jarFN.indexOf('!'));
            JarFile jar = null;
            try {
                jar = new JarFile(jarFN);
                Enumeration<JarEntry> entries = jar.entries();
                while (entries.hasMoreElements()) {
                    String name = entries.nextElement().getName();
                    Matcher mtc = nameRE.matcher(name);
                    if (mtc.find()) {
                        String innerName = mtc.group(1).replace('/', '.');
                        Class<?> inner;
                        try {
                            inner = cl.loadClass(innerName);
                        } catch (ClassNotFoundException e) {
                            String msg = "Unable to load " + c + " inner class " + innerName;
                            throw new VoltCompilerException(msg);
                        }
                        builder.add(inner);
                    }
                }
            } catch (IOException e) {
                String msg = "Cannot access class " + c + " source code location of " + jarFN;
                throw new VoltCompilerException(msg);
            } finally {
                if (jar != null)
                    try {
                        jar.close();
                    } catch (Exception ignoreIt) {
                    }
                ;
            }
        }
        // load directly from a classfile
        else if ("file".equals(curl.getProtocol())) {
            Pattern nameRE = Pattern.compile("/(" + stem + "\\$[^/]+).class\\z");
            File sourceDH = new File(curl.getFile()).getParentFile();
            for (File f : sourceDH.listFiles()) {
                Matcher mtc = nameRE.matcher(f.getAbsolutePath());
                if (mtc.find()) {
                    String innerName = mtc.group(1).replace('/', '.');
                    Class<?> inner;
                    try {
                        inner = cl.loadClass(innerName);
                    } catch (ClassNotFoundException e) {
                        String msg = "Unable to load " + c + " inner class " + innerName;
                        throw new VoltCompilerException(msg);
                    }
                    builder.add(inner);
                }
            }

        }
    }
    return builder.build();
}

From source file:org.grails.io.support.PathMatchingResourcePatternResolver.java

/**
 * Find all resources in jar files that match the given location pattern
 * via the Ant-style PathMatcher.//from   w w  w.ja  v  a  2 s  . c  o  m
 * @param rootDirResource the root directory as Resource
 * @param subPattern the sub pattern to match (below the root directory)
 * @return the Set of matching Resource instances
 * @throws IOException in case of I/O errors
 * @see java.net.JarURLConnection
 */
protected Set<Resource> doFindPathMatchingJarResources(Resource rootDirResource, String subPattern)
        throws IOException {

    URLConnection con = rootDirResource.getURL().openConnection();
    JarFile jarFile;
    String jarFileUrl;
    String rootEntryPath;
    boolean newJarFile = false;

    if (con instanceof JarURLConnection) {
        // Should usually be the case for traditional JAR files.
        JarURLConnection jarCon = (JarURLConnection) con;
        GrailsResourceUtils.useCachesIfNecessary(jarCon);
        jarFile = jarCon.getJarFile();
        jarFileUrl = jarCon.getJarFileURL().toExternalForm();
        JarEntry jarEntry = jarCon.getJarEntry();
        rootEntryPath = (jarEntry != null ? jarEntry.getName() : "");
    } else {
        // No JarURLConnection -> need to resort to URL file parsing.
        // We'll assume URLs of the format "jar:path!/entry", with the protocol
        // being arbitrary as long as following the entry format.
        // We'll also handle paths with and without leading "file:" prefix.
        String urlFile = rootDirResource.getURL().getFile();
        int separatorIndex = urlFile.indexOf(GrailsResourceUtils.JAR_URL_SEPARATOR);
        if (separatorIndex != -1) {
            jarFileUrl = urlFile.substring(0, separatorIndex);
            rootEntryPath = urlFile.substring(separatorIndex + GrailsResourceUtils.JAR_URL_SEPARATOR.length());
            jarFile = getJarFile(jarFileUrl);
        } else {
            jarFile = new JarFile(urlFile);
            jarFileUrl = urlFile;
            rootEntryPath = "";
        }
        newJarFile = true;
    }

    try {
        if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) {
            // Root entry path must end with slash to allow for proper matching.
            // The Sun JRE does not return a slash here, but BEA JRockit does.
            rootEntryPath = rootEntryPath + "/";
        }
        Set<Resource> result = new LinkedHashSet<Resource>(8);
        for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
            JarEntry entry = entries.nextElement();
            String entryPath = entry.getName();
            if (entryPath.startsWith(rootEntryPath)) {
                String relativePath = entryPath.substring(rootEntryPath.length());
                if (getPathMatcher().match(subPattern, relativePath)) {
                    result.add(rootDirResource.createRelative(relativePath));
                }
            }
        }
        return result;
    } finally {
        // Close jar file, but only if freshly obtained -
        // not from JarURLConnection, which might cache the file reference.
        if (newJarFile) {
            jarFile.close();
        }
    }
}

From source file:org.codehaus.groovy.grails.io.support.PathMatchingResourcePatternResolver.java

/**
 * Find all resources in jar files that match the given location pattern
 * via the Ant-style PathMatcher.//w  w  w.j ava  2 s .  co  m
 * @param rootDirResource the root directory as Resource
 * @param subPattern the sub pattern to match (below the root directory)
 * @return the Set of matching Resource instances
 * @throws IOException in case of I/O errors
 * @see java.net.JarURLConnection
 */
protected Set<Resource> doFindPathMatchingJarResources(Resource rootDirResource, String subPattern)
        throws IOException {

    URLConnection con = rootDirResource.getURL().openConnection();
    JarFile jarFile;
    String jarFileUrl;
    String rootEntryPath;
    boolean newJarFile = false;

    if (con instanceof JarURLConnection) {
        // Should usually be the case for traditional JAR files.
        JarURLConnection jarCon = (JarURLConnection) con;
        GrailsResourceUtils.useCachesIfNecessary(jarCon);
        jarFile = jarCon.getJarFile();
        jarFileUrl = jarCon.getJarFileURL().toExternalForm();
        JarEntry jarEntry = jarCon.getJarEntry();
        rootEntryPath = (jarEntry != null ? jarEntry.getName() : "");
    } else {
        // No JarURLConnection -> need to resort to URL file parsing.
        // We'll assume URLs of the format "jar:path!/entry", with the protocol
        // being arbitrary as long as following the entry format.
        // We'll also handle paths with and without leading "file:" prefix.
        String urlFile = rootDirResource.getURL().getFile();
        int separatorIndex = urlFile.indexOf(GrailsResourceUtils.JAR_URL_SEPARATOR);
        if (separatorIndex != -1) {
            jarFileUrl = urlFile.substring(0, separatorIndex);
            rootEntryPath = urlFile.substring(separatorIndex + GrailsResourceUtils.JAR_URL_SEPARATOR.length());
            jarFile = getJarFile(jarFileUrl);
        } else {
            jarFile = new JarFile(urlFile);
            jarFileUrl = urlFile;
            rootEntryPath = "";
        }
        newJarFile = true;
    }

    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Looking for matching resources in jar file [" + jarFileUrl + "]");
        }
        if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) {
            // Root entry path must end with slash to allow for proper matching.
            // The Sun JRE does not return a slash here, but BEA JRockit does.
            rootEntryPath = rootEntryPath + "/";
        }
        Set<Resource> result = new LinkedHashSet<Resource>(8);
        for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
            JarEntry entry = entries.nextElement();
            String entryPath = entry.getName();
            if (entryPath.startsWith(rootEntryPath)) {
                String relativePath = entryPath.substring(rootEntryPath.length());
                if (getPathMatcher().match(subPattern, relativePath)) {
                    result.add(rootDirResource.createRelative(relativePath));
                }
            }
        }
        return result;
    } finally {
        // Close jar file, but only if freshly obtained -
        // not from JarURLConnection, which might cache the file reference.
        if (newJarFile) {
            jarFile.close();
        }
    }
}

From source file:org.zkoss.spring.core.io.support.PathMatchingResourcePatternResolver.java

/**
 * Find all resources in jar files that match the given location pattern
 * via the Ant-style PathMatcher./*from  w w  w.  jav  a 2 s  . c o m*/
 * @param rootDirResource the root directory as Resource
 * @param subPattern the sub pattern to match (below the root directory)
 * @return the Set of matching Resource instances
 * @throws IOException in case of I/O errors
 * @see java.net.JarURLConnection
 * @see org.springframework.util.PathMatcher
 */
protected Set<Resource> doFindPathMatchingJarResources(Resource rootDirResource, String subPattern)
        throws IOException {

    URLConnection con = rootDirResource.getURL().openConnection();
    JarFile jarFile;
    String jarFileUrl;
    String rootEntryPath;
    boolean newJarFile = false;

    if (con instanceof JarURLConnection) {
        // Should usually be the case for traditional JAR files.
        JarURLConnection jarCon = (JarURLConnection) con;
        jarCon.setUseCaches(false);
        jarFile = jarCon.getJarFile();
        jarFileUrl = jarCon.getJarFileURL().toExternalForm();
        JarEntry jarEntry = jarCon.getJarEntry();
        rootEntryPath = (jarEntry != null ? jarEntry.getName() : "");
    } else {
        // No JarURLConnection -> need to resort to URL file parsing.
        // We'll assume URLs of the format "jar:path!/entry", with the protocol
        // being arbitrary as long as following the entry format.
        // We'll also handle paths with and without leading "file:" prefix.
        String urlFile = rootDirResource.getURL().getFile();
        int separatorIndex = urlFile.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
        if (separatorIndex != -1) {
            jarFileUrl = urlFile.substring(0, separatorIndex);
            rootEntryPath = urlFile.substring(separatorIndex + ResourceUtils.JAR_URL_SEPARATOR.length());
            jarFile = getJarFile(jarFileUrl);
        } else {
            jarFile = new JarFile(urlFile);
            jarFileUrl = urlFile;
            rootEntryPath = "";
        }
        newJarFile = true;
    }

    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Looking for matching resources in jar file [" + jarFileUrl + "]");
        }
        if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) {
            // Root entry path must end with slash to allow for proper matching.
            // The Sun JRE does not return a slash here, but BEA JRockit does.
            rootEntryPath = rootEntryPath + "/";
        }
        Set<Resource> result = new LinkedHashSet<Resource>(8);
        for (Enumeration entries = jarFile.entries(); entries.hasMoreElements();) {
            JarEntry entry = (JarEntry) entries.nextElement();
            String entryPath = entry.getName();
            if (entryPath.startsWith(rootEntryPath)) {
                String relativePath = entryPath.substring(rootEntryPath.length());
                if (getPathMatcher().match(subPattern, relativePath)) {
                    result.add(rootDirResource.createRelative(relativePath));
                }
            }
        }
        return result;
    } finally {
        // Close jar file, but only if freshly obtained -
        // not from JarURLConnection, which might cache the file reference.
        if (newJarFile) {
            jarFile.close();
        }
    }
}

From source file:JNLPAppletLauncher.java

/**
 * Enumerate the list of entries in the jar file and return those that are
 * the root entries./*w  w w  .  j  a v  a  2  s  . c  o  m*/
 */
private Set/*<String>*/ getRootEntries(JarFile jarFile) {
    if (VERBOSE) {
        System.err.println("getRootEntries:");
    }

    Set/*<String>*/ names = new HashSet/*<String>*/();
    Enumeration/*<JarEntry>*/ entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = (JarEntry) entries.nextElement();
        String entryName = entry.getName();

        if (VERBOSE) {
            System.err.println("JarEntry : " + entryName);
        }

        // only look at entries with no "/"
        if (entryName.indexOf('/') == -1 && entryName.indexOf(File.separatorChar) == -1) {
            names.add(entryName);
        }
    }

    return names;
}

From source file:JNLPAppletLauncher.java

/**
 * Validate the certificates for each native Lib in the jar file.
 * Throws an IOException if any certificate is not valid.
 *///from   www  .  ja  va 2s .com
private void validateCertificates(JarFile jarFile, Set/*<String>*/ nativeLibNames) throws IOException {

    if (DEBUG) {
        System.err.println("validateCertificates:");
    }

    byte[] buf = new byte[1000];
    Enumeration/*<JarEntry>*/ entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = (JarEntry) entries.nextElement();
        String entryName = entry.getName();

        if (VERBOSE) {
            System.err.println("JarEntry : " + entryName);
        }

        if (nativeLibNames.contains(entryName)) {

            if (DEBUG) {
                System.err.println("VALIDATE: " + entryName);
            }

            if (!checkNativeCertificates(jarFile, entry, buf)) {
                throw new IOException("Cannot validate certificate for " + entryName);
            }
        }
    }

}

From source file:JNLPAppletLauncher.java

/**
 * Extract the specified set of native libraries in the given jar file.
 *///w  ww.  j a v  a2 s  . com
private void extractNativeLibs(JarFile jarFile, Set/*<String>*/ rootEntries, Set/*<String>*/ nativeLibNames)
        throws IOException {

    if (DEBUG) {
        System.err.println("extractNativeLibs:");
    }

    Enumeration/*<JarEntry>*/ entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = (JarEntry) entries.nextElement();
        String entryName = entry.getName();

        if (VERBOSE) {
            System.err.println("JarEntry : " + entryName);
        }

        // In order to be compatible with Java Web Start, we need
        // to extract all root entries from the jar file. However,
        // we only allow direct loading of the previously
        // discovered native library names.
        if (rootEntries.contains(entryName)) {
            // strip prefix & suffix
            String libName = entryName.substring(nativePrefix.length(),
                    entryName.length() - nativeSuffix.length());
            if (DEBUG) {
                System.err.println("EXTRACT: " + entryName + "(" + libName + ")");
            }

            File nativeLib = new File(nativeTmpDir, entryName);
            InputStream in = new BufferedInputStream(jarFile.getInputStream(entry));
            OutputStream out = new BufferedOutputStream(new FileOutputStream(nativeLib));
            int numBytesWritten = copyStream(in, out, -1);
            in.close();
            out.close();
            if (nativeLibNames.contains(entryName)) {
                nativeLibMap.put(libName, nativeLib.getAbsolutePath());
            }
        }
    }
}