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:request.processing.ServletLoader.java

public static void loadServlet(String servletDir) {
    try {//from  www  . ja  v a 2 s .co m
        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:net.dataforte.commons.resources.ClassUtils.java

/**
 * Returns all resources beneath a folder. Supports filesystem, JARs and JBoss VFS
 * /* w ww  . j  av  a  2s.  c o  m*/
 * @param folder
 * @return
 * @throws IOException
 */
public static URL[] getResources(String folder) throws IOException {
    List<URL> urls = new ArrayList<URL>();
    ArrayList<File> directories = new ArrayList<File>();
    try {
        ClassLoader cld = Thread.currentThread().getContextClassLoader();
        if (cld == null) {
            throw new IOException("Can't get class loader.");
        }
        // Ask for all resources for the path
        Enumeration<URL> resources = cld.getResources(folder);
        while (resources.hasMoreElements()) {
            URL res = resources.nextElement();
            String resProtocol = res.getProtocol();
            if (resProtocol.equalsIgnoreCase("jar")) {
                JarURLConnection conn = (JarURLConnection) res.openConnection();
                JarFile jar = conn.getJarFile();
                for (JarEntry e : Collections.list(jar.entries())) {
                    if (e.getName().startsWith(folder) && !e.getName().endsWith("/")) {
                        urls.add(new URL(
                                joinUrl(res.toString(), "/" + e.getName().substring(folder.length() + 1)))); // FIXME: fully qualified name
                    }
                }
            } else if (resProtocol.equalsIgnoreCase("vfszip") || resProtocol.equalsIgnoreCase("vfs")) { // JBoss 5+
                try {
                    Object content = res.getContent();
                    Method getChildren = content.getClass().getMethod("getChildren");
                    List<?> files = (List<?>) getChildren.invoke(res.getContent());
                    Method toUrl = null;
                    for (Object o : files) {
                        if (toUrl == null) {
                            toUrl = o.getClass().getMethod("toURL");
                        }
                        urls.add((URL) toUrl.invoke(o));
                    }
                } catch (Exception e) {
                    throw new IOException("Error while scanning " + res.toString(), e);
                }
            } else if (resProtocol.equalsIgnoreCase("file")) {
                directories.add(new File(URLDecoder.decode(res.getPath(), "UTF-8")));
            } else {
                throw new IOException("Unknown protocol for resource: " + res.toString());
            }
        }
    } catch (NullPointerException x) {
        throw new IOException(folder + " does not appear to be a valid folder (Null pointer exception)");
    } catch (UnsupportedEncodingException encex) {
        throw new IOException(folder + " does not appear to be a valid folder (Unsupported encoding)");
    }

    // For every directory identified capture all the .class files
    for (File directory : directories) {
        if (directory.exists()) {
            // Get the list of the files contained in the package
            String[] files = directory.list();
            for (String file : files) {
                urls.add(new URL("file:///" + joinPath(directory.getAbsolutePath(), file)));
            }
        } else {
            throw new IOException(
                    folder + " (" + directory.getPath() + ") does not appear to be a valid folder");
        }
    }
    URL[] urlsA = new URL[urls.size()];
    urls.toArray(urlsA);
    return urlsA;
}

From source file:javadepchecker.Main.java

private static boolean depNeeded(String pkg, Collection<String> deps) throws IOException {
    Collection<String> jars = getPackageJars(pkg);
    // We have a virtual with VM provider here
    if (jars.size() == 0) {
        return true;
    }//ww  w . j a v  a 2s  .co m
    for (String jarName : jars) {
        JarFile jar = new JarFile(jarName);
        for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) {
            String name = e.nextElement().getName();
            if (deps.contains(name)) {
                return true;
            }
        }
    }
    return false;
}

From source file:org.jsweet.transpiler.candies.CandyDescriptor.java

public static CandyDescriptor fromCandyJar(JarFile jarFile, String jsOutputDirPath) throws IOException {
    JarEntry pomEntry = null;/*w w w.  ja  v  a2 s  . com*/
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry current = entries.nextElement();
        if (current.getName().endsWith("pom.xml")) {
            pomEntry = current;
        }
    }

    String pomContent = IOUtils.toString(jarFile.getInputStream(pomEntry));

    // take only general part
    int dependenciesIndex = pomContent.indexOf("<dependencies>");
    String pomGeneralPart = dependenciesIndex > 0 ? pomContent.substring(0, dependenciesIndex) : pomContent;

    // extract candy model version from <groupId></groupId>
    Matcher matcher = MODEL_VERSION_PATTERN.matcher(pomGeneralPart);
    String modelVersion = "unknown";
    if (matcher.find()) {
        modelVersion = matcher.group(1);
    }

    // extract name from <artifactId></artifactId>
    matcher = ARTIFACT_ID_PATTERN.matcher(pomGeneralPart);
    String name = "unknown";
    if (matcher.find()) {
        name = matcher.group(1);
    }

    matcher = VERSION_PATTERN.matcher(pomGeneralPart);
    String version = "unknown";
    if (matcher.find()) {
        version = matcher.group(1);
    }

    long lastUpdateTimestamp = jarFile.getEntry("META-INF/MANIFEST.MF").getTime();

    String transpilerVersion = null;

    ZipEntry metadataEntry = jarFile.getEntry("META-INF/candy-metadata.json");
    if (metadataEntry != null) {
        String metadataContent = IOUtils.toString(jarFile.getInputStream(metadataEntry));

        @SuppressWarnings("unchecked")
        Map<String, ?> metadata = gson.fromJson(metadataContent, Map.class);

        transpilerVersion = (String) metadata.get("transpilerVersion");
    }

    String jsDirPath = "META-INF/resources/webjars/" + name + "/" + version;
    ZipEntry jsDirEntry = jarFile.getEntry(jsDirPath);
    List<String> jsFilesPaths = new LinkedList<>();
    if (jsDirEntry != null) {
        // collects js files
        jarFile.stream() //
                .filter(entry -> entry.getName().startsWith(jsDirPath) && entry.getName().endsWith(".js")) //
                .map(entry -> entry.getName()) //
                .forEach(jsFilesPaths::add);
    }

    return new CandyDescriptor( //
            name, //
            version, //
            lastUpdateTimestamp, //
            modelVersion, //
            transpilerVersion, //
            jsOutputDirPath, //
            jsDirPath, //
            jsFilesPaths);
}

From source file:org.jiemamy.utils.ResourceTraversal.java

/**
 * ???/*  ww  w . j a  v  a2 s.  co m*/
 * 
 * @param jarFile JarFile
 * @param handler ?
 * @throws IOException ????
 * @throws TraversalHandlerException ??????? 
 * @throws IllegalArgumentException ?{@code null}???
 */
public static void forEach(JarFile jarFile, ResourceHandler handler)
        throws IOException, TraversalHandlerException {
    Validate.notNull(jarFile);
    Validate.notNull(handler);
    Enumeration<JarEntry> enumeration = jarFile.entries();
    while (enumeration.hasMoreElements()) {
        JarEntry entry = enumeration.nextElement();
        if (!entry.isDirectory()) {
            String entryName = entry.getName().replace('\\', '/');
            InputStream is = jarFile.getInputStream(entry);
            try {
                handler.processResource(entryName, is);
            } finally {
                IOUtils.closeQuietly(is);
            }
        }
    }
}

From source file:org.opoo.util.ClassPathUtils.java

/**
 * //from ww w  . j  a  v  a2 s .c  o m
 * @param jarFileURL
 * @param sourcePath
 * @param destination
 * @param overwrite
 * @throws Exception
 */
protected static void copyJarPath(URL jarFileURL, String sourcePath, File destination, boolean overwrite)
        throws Exception {
    //URL jarFileURL = ResourceUtils.extractJarFileURL(url);
    if (!sourcePath.endsWith("/")) {
        sourcePath += "/";
    }
    String root = jarFileURL.toString() + "!/";
    if (!root.startsWith("jar:")) {
        root = "jar:" + root;
    }

    JarFile jarFile = new JarFile(new File(jarFileURL.toURI()));
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry jarEntry = entries.nextElement();
        String name = jarEntry.getName();
        //log.debug(name + "." + sourcePath + "." + name.startsWith(sourcePath));
        if (name.startsWith(sourcePath)) {
            String relativePath = name.substring(sourcePath.length());
            //log.debug("relativePath: " + relativePath);
            if (relativePath != null && relativePath.length() > 0) {
                File tmp = new File(destination, relativePath);
                //not exists or overwrite permitted
                if (overwrite || !tmp.exists()) {
                    if (jarEntry.isDirectory()) {
                        tmp.mkdirs();
                        if (IS_DEBUG_ENABLED) {
                            log.debug("Create directory: " + tmp);
                        }
                    } else {
                        File parent = tmp.getParentFile();
                        if (!parent.exists()) {
                            parent.mkdirs();
                        }
                        //1.FileCopyUtils.copy
                        //InputStream is = jarFile.getInputStream(jarEntry);
                        //FileCopyUtils.copy(is, new FileOutputStream(tmp));

                        //2. url copy
                        URL u = new URL(root + name);
                        //log.debug(u.toString());
                        FileUtils.copyURLToFile(u, tmp);
                        if (IS_DEBUG_ENABLED) {
                            log.debug("Copyed file '" + u + "' to '" + tmp + "'.");
                        }
                    }
                }
            }
        }
    }

    try {
        jarFile.close();
    } catch (Exception ie) {
    }
}

From source file:org.apache.hive.beeline.ClassNameCompleter.java

public static String[] getClassNames() throws IOException {
    Set urls = new HashSet();

    for (ClassLoader loader = Thread.currentThread().getContextClassLoader(); loader != null; loader = loader
            .getParent()) {/*w w w . ja v a2 s  .com*/
        if (!(loader instanceof URLClassLoader)) {
            continue;
        }

        urls.addAll(Arrays.asList(((URLClassLoader) loader).getURLs()));
    }

    // Now add the URL that holds java.lang.String. This is because
    // some JVMs do not report the core classes jar in the list of
    // class loaders.
    Class[] systemClasses = new Class[] { String.class, javax.swing.JFrame.class };

    for (int i = 0; i < systemClasses.length; i++) {
        URL classURL = systemClasses[i]
                .getResource("/" + systemClasses[i].getName().replace('.', '/') + clazzFileNameExtension);

        if (classURL != null) {
            URLConnection uc = classURL.openConnection();

            if (uc instanceof JarURLConnection) {
                urls.add(((JarURLConnection) uc).getJarFileURL());
            }
        }
    }

    Set classes = new HashSet();

    for (Iterator i = urls.iterator(); i.hasNext();) {
        URL url = (URL) i.next();
        File file = new File(url.getFile());

        if (file.isDirectory()) {
            Set files = getClassFiles(file.getAbsolutePath(), new HashSet(), file, new int[] { 200 });
            classes.addAll(files);

            continue;
        }

        if ((file == null) || !file.isFile()) {
            continue;
        }

        JarFile jf = new JarFile(file);

        for (Enumeration e = jf.entries(); e.hasMoreElements();) {
            JarEntry entry = (JarEntry) e.nextElement();

            if (entry == null) {
                continue;
            }

            String name = entry.getName();

            if (isClazzFile(name)) {
                /* only use class file*/
                classes.add(name);
            } else if (isJarFile(name)) {
                classes.addAll(getClassNamesFromJar(name));
            } else {
                continue;
            }
        }
    }

    // now filter classes by changing "/" to "." and trimming the
    // trailing ".class"
    Set classNames = new TreeSet();

    for (Iterator i = classes.iterator(); i.hasNext();) {
        String name = (String) i.next();
        classNames.add(name.replace('/', '.').substring(0, name.length() - 6));
    }

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

From source file:net.dataforte.commons.resources.ClassUtils.java

/**
 * Returns all classes within the specified package. Supports filesystem, JARs and JBoss VFS
 * /*from   w w w . j a v a  2 s .  c o  m*/
 * @param folder
 * @return
 * @throws IOException
 */
public static Class<?>[] getClassesForPackage(String pckgname) throws ClassNotFoundException {
    // This will hold a list of directories matching the pckgname.
    // There may be more than one if a package is split over multiple
    // jars/paths
    List<Class<?>> classes = new ArrayList<Class<?>>();
    ArrayList<File> directories = new ArrayList<File>();
    try {
        ClassLoader cld = Thread.currentThread().getContextClassLoader();
        if (cld == null) {
            throw new ClassNotFoundException("Can't get class loader.");
        }
        // Ask for all resources for the path
        Enumeration<URL> resources = cld.getResources(pckgname.replace('.', '/'));
        while (resources.hasMoreElements()) {
            URL res = resources.nextElement();
            if (res.getProtocol().equalsIgnoreCase("jar")) {
                JarURLConnection conn = (JarURLConnection) res.openConnection();
                JarFile jar = conn.getJarFile();
                for (JarEntry e : Collections.list(jar.entries())) {

                    if (e.getName().startsWith(pckgname.replace('.', '/')) && e.getName().endsWith(".class")
                            && !e.getName().contains("$")) {
                        String className = e.getName().replace("/", ".").substring(0, e.getName().length() - 6);
                        classes.add(Class.forName(className, true, cld));
                    }
                }
            } else if (res.getProtocol().equalsIgnoreCase("vfszip")) { // JBoss 5+
                try {
                    Object content = res.getContent();
                    Method getChildren = content.getClass().getMethod("getChildren");
                    List<?> files = (List<?>) getChildren.invoke(res.getContent());
                    Method getPathName = null;
                    for (Object o : files) {
                        if (getPathName == null) {
                            getPathName = o.getClass().getMethod("getPathName");
                        }
                        String pathName = (String) getPathName.invoke(o);
                        if (pathName.endsWith(".class")) {
                            String className = pathName.replace("/", ".").substring(0, pathName.length() - 6);
                            classes.add(Class.forName(className, true, cld));
                        }
                    }
                } catch (Exception e) {
                    throw new IOException("Error while scanning " + res.toString(), e);
                }
            } else {
                directories.add(new File(URLDecoder.decode(res.getPath(), "UTF-8")));
            }
        }
    } catch (NullPointerException x) {
        throw new ClassNotFoundException(
                pckgname + " does not appear to be a valid package (Null pointer exception)", x);
    } catch (UnsupportedEncodingException encex) {
        throw new ClassNotFoundException(
                pckgname + " does not appear to be a valid package (Unsupported encoding)", encex);
    } catch (IOException ioex) {
        throw new ClassNotFoundException(
                "IOException was thrown when trying to get all resources for " + pckgname, ioex);
    }

    // For every directory identified capture all the .class files
    for (File directory : directories) {
        if (directory.exists()) {
            // Get the list of the files contained in the package
            String[] files = directory.list();
            for (String file : files) {
                // we are only interested in .class files
                if (file.endsWith(".class")) {
                    // removes the .class extension
                    classes.add(Class.forName(pckgname + '.' + file.substring(0, file.length() - 6)));
                }
            }
        } else {
            throw new ClassNotFoundException(
                    pckgname + " (" + directory.getPath() + ") does not appear to be a valid package");
        }
    }
    Class<?>[] classesA = new Class[classes.size()];
    classes.toArray(classesA);
    return classesA;
}

From source file:org.schemaspy.util.ResourceWriter.java

/**
 * Copies resources from the jar file of the current thread and extract it
 * to the destination path.// w w w  . jav a 2  s  .co  m
 *
 * @param jarConnection
 * @param destPath destination file or directory
 */
private static void copyJarResourceToPath(JarURLConnection jarConnection, File destPath, FileFilter filter) {
    try {
        JarFile jarFile = jarConnection.getJarFile();
        String jarConnectionEntryName = jarConnection.getEntryName();

        /**
         * Iterate all entries in the jar file.
         */
        for (Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {
            JarEntry jarEntry = e.nextElement();
            String jarEntryName = jarEntry.getName();

            /**
             * Extract files only if they match the path.
             */
            if (jarEntryName.startsWith(jarConnectionEntryName + "/")) {
                String filename = jarEntryName.substring(jarConnectionEntryName.length());
                File currentFile = new File(destPath, filename);

                if (jarEntry.isDirectory()) {
                    FileUtils.forceMkdir(currentFile);
                } else {
                    if (filter == null || filter.accept(currentFile)) {
                        InputStream is = jarFile.getInputStream(jarEntry);
                        OutputStream out = FileUtils.openOutputStream(currentFile);
                        IOUtils.copy(is, out);
                        is.close();
                        out.close();
                    }
                }
            }
        }
    } catch (IOException e) {
        LOGGER.warn(e.getMessage(), e);
    }
}

From source file:org.jdesktop.wonderland.modules.service.ModuleManagerUtils.java

/**
 * Expands a jar file into a given directory, given the jar file and the
 * directory into which the contents should be written.
 * /*from w w  w. j av  a  2 s. c o  m*/
 * @throw IOException Upon error expanding the Jar file
 */
public static void expandJar(JarFile jarFile, File root) throws IOException {
    /*
     * Loop through each entry, fetchs its input stream, and write to an
     * output stream for the file.
     */
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements() == true) {
        JarEntry entry = entries.nextElement();
        InputStream is = jarFile.getInputStream(entry);
        String entryName = entry.getName();

        /* Don't expand anything that beings with META-INF */
        if (entryName.startsWith("META-INF") == true) {
            continue;
        }

        /* Ignore if it is a directory, then create it */
        if (entryName.endsWith("/") == true) {
            File file = new File(root, entryName);
            file.mkdirs();
            continue;
        }

        /* Write out to a file in 'root' */
        File file = new File(root, entryName);
        FileOutputStream os = new FileOutputStream(file);
        byte[] b = new byte[CHUNK_SIZE];
        while (true) {
            int len = is.read(b);
            if (len == -1) {
                break;
            }
            os.write(b, 0, len);
        }
        is.close();
        os.close();
    }
}