Search in sources :

Example 16 with JarURLConnection

use of java.net.JarURLConnection in project hale by halestudio.

the class ReflectionHelper method getFilesFromPackage.

/**
 * Returns an array of all files contained by a given package
 *
 * @param pkg the package (e.g. "de.igd.fhg.CityServer3D")
 * @return an array of files
 * @throws IOException if the package could not be found
 */
public static synchronized File[] getFilesFromPackage(String pkg) throws IOException {
    File[] files;
    JarFile jarFile = null;
    try {
        URL u = _packageResolver.resolve(pkg);
        if (u != null && !u.toString().startsWith("jar:")) {
            // $NON-NLS-1$
            // we got the package as an URL. Simply create a file
            // from this URL
            File dir;
            try {
                dir = new File(u.toURI());
            } catch (URISyntaxException e) {
                // if the URL contains spaces and they have not been
                // replaced by %20 then we'll have to use the following line
                dir = new File(u.getFile());
            }
            if (!dir.isDirectory()) {
                // try another method
                dir = new File(u.getFile());
            }
            files = null;
            if (dir.isDirectory()) {
                files = dir.listFiles();
            }
        } else {
            // get the current jar file and search it
            if (u != null && u.toString().startsWith("jar:file:")) {
                // first try using URL and File
                try {
                    String p = u.toString().substring(4);
                    // $NON-NLS-1$
                    p = p.substring(0, p.indexOf("!/"));
                    File file = new File(URI.create(p));
                    p = file.getAbsolutePath();
                    try {
                        jarFile = new JarFile(p);
                    } catch (ZipException e) {
                        // $NON-NLS-1$
                        throw new IllegalArgumentException("No zip file: " + p, e);
                    }
                } catch (Throwable e1) {
                    // second try directly using path
                    String p = u.toString().substring(9);
                    // $NON-NLS-1$
                    p = p.substring(0, p.indexOf("!/"));
                    try {
                        jarFile = new JarFile(p);
                    } catch (ZipException e2) {
                        // $NON-NLS-1$
                        throw new IllegalArgumentException("No zip file: " + p, e2);
                    }
                }
            } else {
                u = getCurrentJarURL();
                // open jar file
                JarURLConnection juc = (JarURLConnection) u.openConnection();
                jarFile = juc.getJarFile();
            }
            // enumerate entries and add those that match the package path
            Enumeration<JarEntry> entries = jarFile.entries();
            ArrayList<String> file_names = new ArrayList<String>();
            // $NON-NLS-1$ //$NON-NLS-2$
            String package_path = pkg.replaceAll("\\.", "/");
            boolean slashed = false;
            if (package_path.charAt(0) == '/') {
                package_path = package_path.substring(1);
                slashed = true;
            }
            while (entries.hasMoreElements()) {
                JarEntry j = entries.nextElement();
                if (j.getName().matches("^" + package_path + ".+\\..+")) {
                    // $NON-NLS-1$ //$NON-NLS-2$
                    if (slashed) {
                        // $NON-NLS-1$
                        file_names.add("/" + j.getName());
                    } else {
                        file_names.add(j.getName());
                    }
                }
            }
            // convert list to array
            files = new File[file_names.size()];
            Iterator<String> i = file_names.iterator();
            int n = 0;
            while (i.hasNext()) {
                files[n++] = new File(i.next());
            }
        }
    } catch (Throwable e) {
        // $NON-NLS-1$
        throw new IOException("Could not find package: " + pkg, e);
    } finally {
        if (jarFile != null) {
            jarFile.close();
        }
    }
    if (files != null && files.length == 0)
        // let's not require paranoid callers
        return null;
    return files;
}
Also used : JarURLConnection(java.net.JarURLConnection) ArrayList(java.util.ArrayList) ZipException(java.util.zip.ZipException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) URL(java.net.URL) JarFile(java.util.jar.JarFile) File(java.io.File)

Example 17 with JarURLConnection

use of java.net.JarURLConnection in project mondrian by pentaho.

the class I18n method getResourcesInPackage.

/**
 * Enumerates the resouces in a give package name.
 * This works even if the resources are loaded from a jar file!
 *
 * <p/>Adapted from code by mikewse
 * on the java.sun.com message boards.
 * http://forum.java.sun.com/thread.jsp?forum=22&thread=30984
 *
 * <p>The resulting set is deterministically ordered.
 *
 * @param coreClass   Class for class loader to find the resources
 * @param packageName The package to enumerate
 * @return A Set of Strings for each resouce in the package.
 */
public static Set<String> getResourcesInPackage(Class coreClass, String packageName) throws IOException {
    String localPackageName;
    if (packageName.endsWith("/")) {
        localPackageName = packageName;
    } else {
        localPackageName = packageName + '/';
    }
    ClassLoader cl = coreClass.getClassLoader();
    Enumeration<URL> dirEnum = cl.getResources(localPackageName);
    // deterministic
    Set<String> names = new LinkedHashSet<String>();
    while (dirEnum.hasMoreElements()) {
        URL resUrl = dirEnum.nextElement();
        // Pointing to filesystem directory
        if (resUrl.getProtocol().equals("file")) {
            try {
                File dir = new File(resUrl.getFile());
                File[] files = dir.listFiles();
                if (files != null) {
                    for (int i = 0; i < files.length; i++) {
                        File file = files[i];
                        if (file.isDirectory()) {
                            continue;
                        }
                        names.add(localPackageName + file.getName());
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        // Pointing to Jar file
        } else if (resUrl.getProtocol().equals("jar")) {
            JarURLConnection jconn = (JarURLConnection) resUrl.openConnection();
            JarFile jfile = jconn.getJarFile();
            Enumeration entryEnum = jfile.entries();
            while (entryEnum.hasMoreElements()) {
                JarEntry entry = (JarEntry) entryEnum.nextElement();
                String entryName = entry.getName();
                // Exclude our own directory
                if (entryName.equals(localPackageName)) {
                    continue;
                }
                String parentDirName = entryName.substring(0, entryName.lastIndexOf('/') + 1);
                if (!parentDirName.equals(localPackageName)) {
                    continue;
                }
                names.add(entryName);
            }
        } else {
        // Invalid classpath entry
        }
    }
    return names;
}
Also used : JarURLConnection(java.net.JarURLConnection) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) URL(java.net.URL) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) File(java.io.File)

Example 18 with JarURLConnection

use of java.net.JarURLConnection in project jgnash by ccavanaugh.

the class ActionParser method findActionClasses.

/**
     * Recursive method used to find all classes in a given directory and
     * subdirectories.
     *
     * @param directory   The base directory
     * @param packageName The package name for classes found inside the base directory
     * @return The classes
     * @throws ClassNotFoundException error
     */
private static List<Class<?>> findActionClasses(final File directory, final String packageName) throws ClassNotFoundException {
    List<Class<?>> classes = new ArrayList<>();
    if (directory.getPath().contains(".jar!")) {
        // loading from the jar distribution
        try {
            int index = directory.getPath().indexOf(".jar!");
            URL url = new URL("jar:" + directory.getPath().substring(0, index).replace('/', File.separatorChar) + ".jar!/");
            JarURLConnection conn = (JarURLConnection) url.openConnection();
            try (JarFile jar = conn.getJarFile()) {
                Enumeration<JarEntry> entries = jar.entries();
                String path = packageName.replace('.', '/');
                while (entries.hasMoreElements()) {
                    JarEntry entry = entries.nextElement();
                    String name = entry.getName();
                    if (name.startsWith(path) && name.endsWith(".class") && !name.contains("$")) {
                        Class<?> clazz = Class.forName(name.substring(0, name.length() - 6).replace('/', '.'));
                        if (Action.class.isAssignableFrom(clazz)) {
                            classes.add(Class.forName(name.substring(0, name.length() - 6).replace('/', '.')));
                        }
                    }
                }
            }
        } catch (IOException | ClassNotFoundException e) {
            log.log(Level.SEVERE, e.getMessage(), e);
        }
    } else if (!directory.exists()) {
        log.info("Was not a directory");
    } else {
        // loading through an IDE or jar file has been expanded
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                final String fileName = file.getName();
                if (file.isDirectory()) {
                    assert !file.getName().contains(".");
                    classes.addAll(findActionClasses(file, packageName + "." + file.getName()));
                } else if (file.getName().endsWith(".class") && !fileName.contains("$")) {
                    Class<?> clazz = Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6));
                    if (Action.class.isAssignableFrom(clazz)) {
                        classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
                    }
                }
            }
        }
    }
    return classes;
}
Also used : JarURLConnection(java.net.JarURLConnection) ArrayList(java.util.ArrayList) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) URL(java.net.URL) JarFile(java.util.jar.JarFile) File(java.io.File)

Example 19 with JarURLConnection

use of java.net.JarURLConnection in project jdk8u_jdk by JetBrains.

the class URLClassPath method check.

/*
     * Check whether the resource URL should be returned.
     * Throw exception on failure.
     * Called internally within this file.
     */
static void check(URL url) throws IOException {
    SecurityManager security = System.getSecurityManager();
    if (security != null) {
        URLConnection urlConnection = url.openConnection();
        Permission perm = urlConnection.getPermission();
        if (perm != null) {
            try {
                security.checkPermission(perm);
            } catch (SecurityException se) {
                // security managers
                if ((perm instanceof java.io.FilePermission) && perm.getActions().indexOf("read") != -1) {
                    security.checkRead(perm.getName());
                } else if ((perm instanceof java.net.SocketPermission) && perm.getActions().indexOf("connect") != -1) {
                    URL locUrl = url;
                    if (urlConnection instanceof JarURLConnection) {
                        locUrl = ((JarURLConnection) urlConnection).getJarFileURL();
                    }
                    security.checkConnect(locUrl.getHost(), locUrl.getPort());
                } else {
                    throw se;
                }
            }
        }
    }
}
Also used : java.io(java.io) JarURLConnection(java.net.JarURLConnection) Permission(java.security.Permission) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) JarURLConnection(java.net.JarURLConnection) URL(java.net.URL)

Example 20 with JarURLConnection

use of java.net.JarURLConnection in project jdk8u_jdk by JetBrains.

the class LoaderHandler method addPermissionsForURLs.

/**
     * Adds to the specified permission collection the permissions
     * necessary to load classes from a loader with the specified URL
     * path; if "forLoader" is true, also adds URL-specific
     * permissions necessary for the security context that such a
     * loader operates within, such as permissions necessary for
     * granting automatic permissions to classes defined by the
     * loader.  A given permission is only added to the collection if
     * it is not already implied by the collection.
     */
private static void addPermissionsForURLs(URL[] urls, PermissionCollection perms, boolean forLoader) {
    for (int i = 0; i < urls.length; i++) {
        URL url = urls[i];
        try {
            URLConnection urlConnection = url.openConnection();
            Permission p = urlConnection.getPermission();
            if (p != null) {
                if (p instanceof FilePermission) {
                    /*
                         * If the codebase is a file, the permission required
                         * to actually read classes from the codebase URL is
                         * the permission to read all files beneath the last
                         * directory in the file path, either because JAR
                         * files can refer to other JAR files in the same
                         * directory, or because permission to read a
                         * directory is not implied by permission to read the
                         * contents of a directory, which all that might be
                         * granted.
                         */
                    String path = p.getName();
                    int endIndex = path.lastIndexOf(File.separatorChar);
                    if (endIndex != -1) {
                        path = path.substring(0, endIndex + 1);
                        if (path.endsWith(File.separator)) {
                            path += "-";
                        }
                        Permission p2 = new FilePermission(path, "read");
                        if (!perms.implies(p2)) {
                            perms.add(p2);
                        }
                        perms.add(new FilePermission(path, "read"));
                    } else {
                        /*
                             * No directory separator: use permission to
                             * read the file.
                             */
                        if (!perms.implies(p)) {
                            perms.add(p);
                        }
                    }
                } else {
                    if (!perms.implies(p)) {
                        perms.add(p);
                    }
                    /*
                         * If the purpose of these permissions is to grant
                         * them to an instance of a URLClassLoader subclass,
                         * we must add permission to connect to and accept
                         * from the host of non-"file:" URLs, otherwise the
                         * getPermissions() method of URLClassLoader will
                         * throw a security exception.
                         */
                    if (forLoader) {
                        // get URL with meaningful host component
                        URL hostURL = url;
                        for (URLConnection conn = urlConnection; conn instanceof JarURLConnection; ) {
                            hostURL = ((JarURLConnection) conn).getJarFileURL();
                            conn = hostURL.openConnection();
                        }
                        String host = hostURL.getHost();
                        if (host != null && p.implies(new SocketPermission(host, "resolve"))) {
                            Permission p2 = new SocketPermission(host, "connect,accept");
                            if (!perms.implies(p2)) {
                                perms.add(p2);
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
        /*
                 * This shouldn't happen, although it is declared to be
                 * thrown by openConnection() and getPermission().  If it
                 * does, don't bother granting or requiring any permissions
                 * for this URL.
                 */
        }
    }
}
Also used : JarURLConnection(java.net.JarURLConnection) SocketPermission(java.net.SocketPermission) FilePermission(java.io.FilePermission) SocketPermission(java.net.SocketPermission) Permission(java.security.Permission) IOException(java.io.IOException) FilePermission(java.io.FilePermission) URL(java.net.URL) URLConnection(java.net.URLConnection) JarURLConnection(java.net.JarURLConnection)

Aggregations

JarURLConnection (java.net.JarURLConnection)222 URL (java.net.URL)160 JarFile (java.util.jar.JarFile)129 IOException (java.io.IOException)120 JarEntry (java.util.jar.JarEntry)105 File (java.io.File)92 URLConnection (java.net.URLConnection)89 ArrayList (java.util.ArrayList)32 InputStream (java.io.InputStream)27 MalformedURLException (java.net.MalformedURLException)25 URISyntaxException (java.net.URISyntaxException)21 Enumeration (java.util.Enumeration)17 Manifest (java.util.jar.Manifest)16 FileInputStream (java.io.FileInputStream)12 CodeSource (java.security.CodeSource)12 LinkedHashSet (java.util.LinkedHashSet)11 URI (java.net.URI)10 Attributes (java.util.jar.Attributes)10 ZipEntry (java.util.zip.ZipEntry)9 FileNotFoundException (java.io.FileNotFoundException)8