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.kuali.rice.krad.demo.uif.library.elements.DemoElementMultiFileUploadAft.java

protected String[] getResourceListing(Class clazz, String pathStartsWith) throws Exception {
    System.out.println("In for getResourceListing");
    String classPath = clazz.getName().replace(".", "/") + ".class";
    URL dirUrl = clazz.getClassLoader().getResource(classPath);

    if (!"jar".equals(dirUrl.getProtocol())) {
        throw new UnsupportedOperationException("Cannot list files for URL " + dirUrl);
    }/*from ww w  .  j  a v a 2 s.  c om*/

    String jarPath = dirUrl.getPath().substring(5, dirUrl.getPath().indexOf("!")); //strip out only the JAR file
    JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
    Enumeration<JarEntry> entries = jar.entries();
    Set<String> result = new HashSet<String>();

    while (entries.hasMoreElements()) {
        String entry = entries.nextElement().getName();
        if (entry.startsWith(pathStartsWith) && !entry.endsWith("/")) { //filter according to the pathStartsWith skipping directories
            result.add(entry);
        }
    }

    return result.toArray(new String[result.size()]);
}

From source file:edu.sampleu.admin.EdocLiteXmlIngesterBase.java

protected String[] getResourceListing(Class clazz, String pathStartsWith) throws Exception {
    String classPath = clazz.getName().replace(".", "/") + ".class";
    URL dirUrl = clazz.getClassLoader().getResource(classPath);

    if (!"jar".equals(dirUrl.getProtocol())) {
        throw new UnsupportedOperationException("Cannot list files for URL " + dirUrl);
    }/*  w  w w . ja v  a2 s.c  o  m*/

    String jarPath = dirUrl.getPath().substring(5, dirUrl.getPath().indexOf("!")); //strip out only the JAR file
    JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
    Enumeration<JarEntry> entries = jar.entries();
    Set<String> result = new HashSet<String>();

    while (entries.hasMoreElements()) {
        String entry = entries.nextElement().getName();
        if (entry.startsWith(pathStartsWith) && !entry.endsWith("/")) { //filter according to the pathStartsWith skipping directories
            result.add(entry);
        }
    }

    return result.toArray(new String[result.size()]);
}

From source file:com.smartitengineering.util.simple.reflection.DefaultClassScannerImpl.java

private void scanJar(File jarFile, String parentPath, ClassVisitor classVisitor) {
    final JarFile jar = getJarFile(jarFile);
    try {//ww  w.  j  av  a 2  s. c o m
        final Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            JarEntry e = entries.nextElement();
            if (!e.isDirectory() && e.getName().startsWith(parentPath) && e.getName().endsWith(".class")) {
                visitClassFile(jar, e, classVisitor);
            }
        }
    } catch (Exception e) {
    } finally {
        try {
            if (jar != null) {
                jar.close();
            }
        } catch (IOException ex) {
        }
    }
}

From source file:org.atricore.idbus.kernel.main.util.ClassFinderImpl.java

public ArrayList<Class> getClassesFromJarFile(String pkg, ClassLoader cl) throws ClassNotFoundException {
    try {/*w  w w  .  jav  a  2s  .  co m*/
        ArrayList<Class> classes = new ArrayList<Class>();
        URLClassLoader ucl = (URLClassLoader) cl;
        URL[] srcURL = ucl.getURLs();
        String path = pkg.replace('.', '/');
        //Read resources as URL from class loader.
        for (URL url : srcURL) {
            if ("file".equals(url.getProtocol())) {
                File f = new File(url.toURI().getPath());
                //If file is not of type directory then its a jar file
                if (f.exists() && !f.isDirectory()) {
                    try {
                        JarFile jf = new JarFile(f);
                        Enumeration<JarEntry> entries = jf.entries();
                        //read all entries in jar file
                        while (entries.hasMoreElements()) {
                            JarEntry je = entries.nextElement();
                            String clazzName = je.getName();
                            if (clazzName != null && clazzName.endsWith(".class")) {
                                //Add to class list here.
                                clazzName = clazzName.substring(0, clazzName.length() - 6);
                                clazzName = clazzName.replace('/', '.').replace('\\', '.').replace(':', '.');
                                //We are only going to add the class that belong to the provided package.
                                if (clazzName.startsWith(pkg + ".")) {
                                    try {
                                        Class clazz = forName(clazzName, false, cl);
                                        // Don't add any interfaces or JAXWS specific classes.
                                        // Only classes that represent data and can be marshalled
                                        // by JAXB should be added.
                                        if (!clazz.isInterface() && clazz.getPackage().getName().equals(pkg)
                                                && ClassUtils.getDefaultPublicConstructor(clazz) != null
                                                && !ClassUtils.isJAXWSClass(clazz)) {
                                            if (log.isDebugEnabled()) {
                                                log.debug("Adding class: " + clazzName);
                                            }
                                            classes.add(clazz);

                                        }
                                        //catch Throwable as ClassLoader can throw an NoClassDefFoundError that
                                        //does not extend Exception, so lets catch everything that extends Throwable
                                        //rather than just Exception.
                                    } catch (Throwable e) {
                                        if (log.isDebugEnabled()) {
                                            log.debug("Tried to load class " + clazzName
                                                    + " while constructing a JAXBContext.  This class will be skipped.  Processing Continues.");
                                            log.debug("  The reason that class could not be loaded:"
                                                    + e.toString());
                                            log.trace(JavaUtils.stackToString(e));
                                        }
                                    }
                                }
                            }
                        }
                    } catch (IOException e) {
                        throw new ClassNotFoundException(
                                "An IOException error was thrown when trying to read the jar file.");
                    }
                }
            }
        }
        return classes;
    } catch (Exception e) {
        throw new ClassNotFoundException(e.getMessage());
    }

}

From source file:com.qualogy.qafe.web.css.util.CssProvider.java

private Map<String, InputStream> findResourceInFile(File resourceFile, String fileNamePattern)
        throws IOException {
    Map<String, InputStream> result = new TreeMap<String, InputStream>();
    if (resourceFile.canRead() && resourceFile.getAbsolutePath().endsWith(".jar")) {
        JarFile jarFile = new JarFile(resourceFile);
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry singleEntry = entries.nextElement();
            if (singleEntry.getName().matches(fileNamePattern)) {
                result.put(jarFile.getName() + "/" + singleEntry.getName(),
                        jarFile.getInputStream(singleEntry));
            }//from w w w .j a  v  a  2s. c o m
        }
    }
    return result;
}

From source file:org.lilyproject.runtime.source.JarModuleSource.java

public List<SpringConfigEntry> getSpringConfigs(Mode mode) {
    Pattern modeSpecificSpringPattern = Pattern.compile("LILY-INF/spring/" + mode.getName() + "/[^/]*\\.xml");
    List<SpringConfigEntry> result = new ArrayList<SpringConfigEntry>();
    final JarFile jarFile = this.jarFile;

    Enumeration<JarEntry> jarEntries = jarFile.entries();
    while (jarEntries.hasMoreElements()) {
        final JarEntry jarEntry = jarEntries.nextElement();
        final String name = jarEntry.getName();

        Matcher matcher1 = SPRING_COMMON_CONF_PATTERN.matcher(name);
        Matcher matcher2 = modeSpecificSpringPattern.matcher(name);
        if (matcher1.matches() || matcher2.matches()) {
            result.add(new SpringConfigEntry() {
                public String getLocation() {
                    return name;
                }//  w  ww .  j  av  a2s. c o  m

                public InputStream getStream() throws IOException {
                    return jarFile.getInputStream(jarEntry);
                }
            });
        }
    }

    return result;
}

From source file:uk.co.danielrendall.imagetiler.registry.PluginRegistryBuilder.java

private List<Class> findClassesInJar(URI uriOfJar, String pathInJar, String packageName)
        throws ClassNotFoundException {
    if (pathInJar.startsWith("/"))
        pathInJar = pathInJar.substring(1);
    if (!pathInJar.endsWith("/"))
        pathInJar = pathInJar + "/";
    List<Class> classes = new ArrayList<Class>();
    File theFile = new File(uriOfJar);
    if (!theFile.isFile()) {
        return classes;
    }/*from ww  w.  j a va  2s .c  o m*/
    try {
        JarFile jarFile = new JarFile(theFile);
        for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
            JarEntry entry = entries.nextElement();
            String name = entry.getName();
            if (name.startsWith(pathInJar) && name.endsWith(".class")) {
                Log.app.debug("Found entry: " + entry.getName());
                String className = name.replaceAll("/", ".").substring(0, name.length() - 6);
                classes.add(Class.forName(className));
            }
        }
    } catch (IOException e) {
        Log.app.warn("Couldn't open jar file " + uriOfJar + " - " + e.getMessage());
    }
    return classes;
}

From source file:info.dolezel.fatrat.plugins.helpers.JarClassLoader.java

private Set<Class> findClasses(File directory, String packageName, Class annotation)
        throws ClassNotFoundException, IOException {
    Set<Class> classes = new HashSet<Class>();
    if (!directory.exists()) {

        String fullPath = directory.toString();
        String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
        JarFile jarFile = new JarFile(jarPath);
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String entryName = entry.getName();
            if (entryName.endsWith(".class") && !entryName.contains("$")) {
                String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");
                Class cls = this.loadClass(className);

                if (annotation == null || cls.isAnnotationPresent(annotation))
                    classes.add(cls);/* w w  w. jav a 2  s  . co m*/
            }
        }
    } else {
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                assert !file.getName().contains(".");
                classes.addAll(findClasses(file, packageName + "." + file.getName(), annotation));
            } else if (file.getName().endsWith(".class")) {
                Class cls = this.loadClass(
                        packageName + '.' + file.getName().substring(0, file.getName().length() - 6));

                if (annotation == null || cls.isAnnotationPresent(annotation))
                    classes.add(cls);
            }
        }
    }
    return classes;
}

From source file:org.apache.axis2.jaxws.message.databinding.impl.ClassFinderImpl.java

public ArrayList<Class> getClassesFromJarFile(String pkg, ClassLoader cl) throws ClassNotFoundException {
    try {/*w w  w  .  j av  a  2s.c o  m*/
        ArrayList<Class> classes = new ArrayList<Class>();
        URLClassLoader ucl = (URLClassLoader) cl;
        URL[] srcURL = ucl.getURLs();
        String path = pkg.replace('.', '/');
        //Read resources as URL from class loader.
        for (URL url : srcURL) {
            if ("file".equals(url.getProtocol())) {
                File f = new File(url.toURI().getPath());
                //If file is not of type directory then its a jar file
                if (f.exists() && !f.isDirectory()) {
                    try {
                        JarFile jf = new JarFile(f);
                        Enumeration<JarEntry> entries = jf.entries();
                        //read all entries in jar file
                        while (entries.hasMoreElements()) {
                            JarEntry je = entries.nextElement();
                            String clazzName = je.getName();
                            if (clazzName != null && clazzName.endsWith(".class")) {
                                //Add to class list here.
                                clazzName = clazzName.substring(0, clazzName.length() - 6);
                                clazzName = clazzName.replace('/', '.').replace('\\', '.').replace(':', '.');
                                //We are only going to add the class that belong to the provided package.
                                if (clazzName.startsWith(pkg + ".")) {
                                    try {
                                        Class clazz = forName(clazzName, false, cl);
                                        // Don't add any interfaces or JAXWS specific classes.
                                        // Only classes that represent data and can be marshalled
                                        // by JAXB should be added.
                                        if (!clazz.isInterface() && clazz.getPackage().getName().equals(pkg)
                                                && ClassUtils.getDefaultPublicConstructor(clazz) != null
                                                && !ClassUtils.isJAXWSClass(clazz)) {
                                            if (log.isDebugEnabled()) {
                                                log.debug("Adding class: " + clazzName);
                                            }
                                            classes.add(clazz);

                                        }
                                        //catch Throwable as ClassLoader can throw an NoClassDefFoundError that
                                        //does not extend Exception, so lets catch everything that extends Throwable
                                        //rather than just Exception.
                                    } catch (Throwable e) {
                                        if (log.isDebugEnabled()) {
                                            log.debug("Tried to load class " + clazzName
                                                    + " while constructing a JAXBContext.  This class will be skipped.  Processing Continues.");
                                            log.debug("  The reason that class could not be loaded:"
                                                    + e.toString());
                                            log.trace(JavaUtils.stackToString(e));
                                        }
                                    }
                                }
                            }
                        }
                    } catch (IOException e) {
                        throw new ClassNotFoundException(Messages.getMessage("ClassUtilsErr4"));
                    }
                }
            }
        }
        return classes;
    } catch (Exception e) {
        throw new ClassNotFoundException(e.getMessage());
    }

}

From source file:de.xirp.plugin.PluginLoader.java

/**
 * Looks for plugins in the plugins directory. Plugins which needs
 * are not full filled are not accepted.
 * //from   w w w .  j  av  a  2  s  . c  o m
 * @param manager
 *            instance of the plugin manager which is used for
 *            notifying the application about the loading
 *            progress.
 */
protected static void searchPlugins(PluginManager manager) {
    logClass.info(I18n.getString("PluginLoader.log.searchPlugins")); //$NON-NLS-1$
    // Get all Files in the Plugin Directory with
    // Filetype jar
    File pluginDir = new File(Constants.PLUGIN_DIR);
    File[] fileList = pluginDir.listFiles(new FilenameFilter() {

        public boolean accept(@SuppressWarnings("unused") File dir, String filename) {
            return filename.endsWith(".jar"); //$NON-NLS-1$
        }

    });

    if (fileList != null) {
        double perFile = 1.0 / fileList.length;
        double cnt = 0;
        try {
            // Iterate over all jars and try to find
            // the plugin.properties file
            // The file is loaded and Information
            // extracted to PluginInfo
            // Plugin is added to List of Plugins
            for (File f : fileList) {
                String path = f.getAbsolutePath();
                if (!plugins.containsKey(path)) {
                    manager.throwLoaderProgressEvent(
                            I18n.getString("PluginLoader.progress.searchingInFile", f.getName()), cnt); //$NON-NLS-1$
                    JarFile jar = new JarFile(path);
                    JarEntry entry = jar.getJarEntry("plugin.properties"); //$NON-NLS-1$
                    if (entry != null) {
                        InputStream input = jar.getInputStream(entry);
                        Properties props = new Properties();
                        props.load(input);
                        String mainClass = props.getProperty("plugin.mainclass"); //$NON-NLS-1$
                        PluginInfo info = new PluginInfo(path, mainClass, props);
                        String packageName = ClassUtils.getPackageName(mainClass) + "." //$NON-NLS-1$
                                + AbstractPlugin.DEFAULT_BUNDLE_NAME;
                        String bundleBaseName = packageName.replaceAll("\\.", "/"); //$NON-NLS-1$  //$NON-NLS-2$
                        for (Enumeration<JarEntry> entries = jar.entries(); entries.hasMoreElements();) {
                            JarEntry ent = entries.nextElement();
                            String name = ent.getName();
                            if (name.indexOf(bundleBaseName) != -1) {
                                String locale = name
                                        .substring(name.indexOf(AbstractPlugin.DEFAULT_BUNDLE_NAME));
                                locale = locale.replaceAll(AbstractPlugin.DEFAULT_BUNDLE_NAME + "_", //$NON-NLS-1$
                                        ""); //$NON-NLS-1$
                                locale = locale.substring(0, locale.indexOf(".properties")); //$NON-NLS-1$
                                Locale loc = new Locale(locale);
                                info.addAvailableLocale(loc);
                            }
                        }
                        PluginManager.extractAll(info);
                        if (isPlugin(info)) {
                            plugins.put(mainClass, info);
                        }
                    }
                }
                cnt += perFile;

            }
        } catch (IOException e) {
            logClass.error(
                    I18n.getString("PluginLoader.log.errorSearchingforPlugins") + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
        }
    }
    checkAllNeeds();
    logClass.info(I18n.getString("PluginLoader.log.searchPluginsCompleted") + Constants.LINE_SEPARATOR); //$NON-NLS-1$
}