Example usage for java.lang ClassLoader getParent

List of usage examples for java.lang ClassLoader getParent

Introduction

In this page you can find the example usage for java.lang ClassLoader getParent.

Prototype

@CallerSensitive
public final ClassLoader getParent() 

Source Link

Document

Returns the parent class loader for delegation.

Usage

From source file:org.apache.axis2.classloader.MultiParentClassLoader.java

static ClassLoader copy(ClassLoader source) {
    if (source instanceof MultiParentClassLoader) {
        return new MultiParentClassLoader((MultiParentClassLoader) source);
    } else if (source instanceof URLClassLoader) {
        return new URLClassLoader(((URLClassLoader) source).getURLs(), source.getParent());
    } else {//from  ww w.j a  v  a 2  s  .  c  om
        return new URLClassLoader(new URL[0], source);
    }
}

From source file:org.apache.axis2.deployment.RepositoryListener.java

protected void loadClassPathModules() {
    ModuleDeployer deployer = deploymentEngine.getModuleDeployer();

    // Find Modules on the class path (i.e. if classpath includes "addressing.mar" then
    // addressing will be available for engaging)

    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    try {//from www  .  j  ava  2  s .c o  m
        Enumeration moduleURLs = loader.getResources("META-INF/module.xml");
        while (moduleURLs.hasMoreElements()) {
            try {
                URL url = (URL) moduleURLs.nextElement();
                URI moduleURI;
                if (url.getProtocol().equals("file")) {
                    String urlString = url.toString();
                    moduleURI = new URI(urlString.substring(0, urlString.lastIndexOf("/META-INF/module.xml")));
                } else {
                    // Check if the URL refers to an archive (such as
                    // jar:file:/dir/some.jar!/META-INF/module.xml) and extract the
                    // URL of the archive. In general the protocol will be "jar", but
                    // some containers may use other protocols, e.g. WebSphere uses
                    // "wsjar" (AXIS2-4258).
                    String path = url.getPath();
                    int idx = path.lastIndexOf("!/");
                    if (idx != -1 && path.substring(idx + 2).equals("META-INF/module.xml")) {
                        moduleURI = new URI(path.substring(0, idx).replaceAll(" ", "%20"));
                        if (!moduleURI.getScheme().equals("file")) {
                            continue;
                        }
                    } else {
                        continue;
                    }
                }

                log.debug("Deploying module from classpath at '" + moduleURI + "'");
                File f = new File(moduleURI);
                addFileToDeploy(f, deployer, WSInfo.TYPE_MODULE);

            } catch (URISyntaxException e) {
                log.info(e);
            }
        }
    } catch (Exception e) {
        // Oh well, log the problem
        log.error("Error occurred while loading modules from classpath", e);
    }

    String classPath = getLocation();

    if (classPath == null)
        return;

    int lstindex = classPath.lastIndexOf(File.separatorChar);
    if (lstindex > 0) {
        classPath = classPath.substring(0, lstindex);
    } else {
        classPath = ".";
    }
    File root = new File(classPath);
    File[] files = root.listFiles();
    if (files != null) {
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (!file.isDirectory()) {
                if (DeploymentFileData.isModuleArchiveFile(file.getName())) {
                    //adding modules in the class path
                    addFileToDeploy(file, deployer, WSInfo.TYPE_MODULE);
                }
            }
        }
    }

    ClassLoader cl = deploymentEngine.getAxisConfig().getModuleClassLoader();
    while (cl != null) {
        if (cl instanceof URLClassLoader) {
            URL[] urls = ((URLClassLoader) cl).getURLs();
            for (int i = 0; (urls != null) && i < urls.length; i++) {
                String path = urls[i].getPath();
                //If it is a drive letter, adjust accordingly.
                if (path.length() >= 3 && path.charAt(0) == '/' && path.charAt(2) == ':') {
                    path = path.substring(1);
                }
                try {
                    path = URLDecoder.decode(path, Utils.defaultEncoding);
                } catch (UnsupportedEncodingException e) {
                    // Log this?
                }
                File file = new File(path.replace('/', File.separatorChar).replace('|', ':'));
                // If there is a security manager, then it is highly probable that it will deny
                // read access to some files in the class loader hierarchy. Therefore we first
                // check if the name matches that of a module archive and only then check if we
                // can access it. If the security manager denies access, we log a warning.
                if (DeploymentFileData.isModuleArchiveFile(file.getName())) {
                    boolean isFile;
                    try {
                        isFile = file.isFile();
                    } catch (SecurityException ex) {
                        log.warn("Not deploying " + file.getName() + " because security manager denies access",
                                ex);
                        isFile = false;
                    }
                    if (isFile) {
                        //adding modules in the class path
                        addFileToDeploy(file, deployer, WSInfo.TYPE_MODULE);
                    }
                }
            }
        }
        cl = cl.getParent();
    }

    deploymentEngine.doDeploy();
}

From source file:org.apache.axis2.jaxws.client.async.AsyncResponse.java

ClassLoader getParentClassLoader(final ClassLoader cl) {
    return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return cl.getParent();
        }/*from ww w .j av a 2 s  . c om*/
    });
}

From source file:org.apache.axis2.jaxws.description.builder.JAXWSRIWSDLGenerator.java

/**
 * Walk the classloader hierarchy and add to the classpath
 *
 * @param cl/*  w  w w.  j a v a2s. c om*/
 * @param classpath
 */
private static void fillClassPath(ClassLoader cl, HashSet classpath) {
    while (cl != null) {
        if (cl instanceof URLClassLoader) {
            URL[] urls = ((URLClassLoader) cl).getURLs();
            for (int i = 0; (urls != null) && i < urls.length; i++) {
                String path = urls[i].getPath();
                //If it is a drive letter, adjust accordingly.
                if (path.length() >= 3 && path.charAt(0) == '/' && path.charAt(2) == ':')
                    path = path.substring(1);
                addPath(classpath, URLDecoder.decode(path));

                // if its a jar extract Class-Path entries from manifest
                File file = new File(urls[i].getFile());
                if (file.isFile()) {
                    FileInputStream fis = null;
                    try {
                        fis = new FileInputStream(file);
                        if (isJar(fis)) {
                            JarFile jar = new JarFile(file);
                            Manifest manifest = jar.getManifest();
                            if (manifest != null) {
                                Attributes attributes = manifest.getMainAttributes();
                                if (attributes != null) {
                                    String s = attributes.getValue(Attributes.Name.CLASS_PATH);
                                    String base = file.getParent();
                                    if (s != null) {
                                        StringTokenizer st = new StringTokenizer(s, " ");
                                        while (st.hasMoreTokens()) {
                                            String t = st.nextToken();
                                            addPath(classpath, base + File.separatorChar + t);
                                        }
                                    }
                                }
                            }
                        }
                    } catch (IOException ioe) {
                    } finally {
                        if (fis != null) {
                            try {
                                fis.close();
                            } catch (IOException ioe2) {
                            }
                        }
                    }
                }
            }
        }
        cl = cl.getParent();
    }
}

From source file:org.apache.axis2.jaxws.util.WSDL4JWrapper.java

private ClassLoader getNestedClassLoader(Class type, ClassLoader root) {
    if (log.isDebugEnabled()) {
        log.debug("Searching for nested URLClassLoader");
    }//from  w  w w . j  a  v  a2  s .  c o  m
    while (!(root instanceof URLClassLoader)) {
        if (root == null) {
            break;
        }

        final ClassLoader current = root;
        root = (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                return current.getParent();
            }
        });
        if (log.isDebugEnabled() && root != null) {
            log.debug("Checking parent ClassLoader: " + root.getClass().getName());
        }
    }

    return root;
}

From source file:org.apache.catalina.loader.WebappLoader.java

/**
 * Set the appropriate context attribute for our class path.  This
 * is required only because Jasper depends on it.
 *///from  w w  w.  ja v a2s .com
private void setClassPath() {

    // Validate our current state information
    if (!(container instanceof Context))
        return;
    ServletContext servletContext = ((Context) container).getServletContext();
    if (servletContext == null)
        return;

    if (container instanceof StandardContext) {
        String baseClasspath = ((StandardContext) container).getCompilerClasspath();
        if (baseClasspath != null) {
            servletContext.setAttribute(Globals.CLASS_PATH_ATTR, baseClasspath);
            return;
        }
    }

    StringBuffer classpath = new StringBuffer();

    // Assemble the class path information from our class loader chain
    ClassLoader loader = getClassLoader();
    int layers = 0;
    int n = 0;
    while (loader != null) {
        if (!(loader instanceof URLClassLoader)) {
            String cp = getClasspath(loader);
            if (cp == null) {
                log.info("Unknown loader " + loader + " " + loader.getClass());
                break;
            } else {
                if (n > 0)
                    classpath.append(File.pathSeparator);
                classpath.append(cp);
                n++;
            }
            break;
            //continue;
        }
        URL repositories[] = ((URLClassLoader) loader).getURLs();
        for (int i = 0; i < repositories.length; i++) {
            String repository = repositories[i].toString();
            if (repository.startsWith("file://"))
                repository = repository.substring(7);
            else if (repository.startsWith("file:"))
                repository = repository.substring(5);
            else if (repository.startsWith("jndi:"))
                repository = servletContext.getRealPath(repository.substring(5));
            else
                continue;
            if (repository == null)
                continue;
            if (n > 0)
                classpath.append(File.pathSeparator);
            classpath.append(repository);
            n++;
        }
        loader = loader.getParent();
        layers++;
    }

    this.classpath = classpath.toString();

    // Store the assembled class path as a servlet context attribute
    servletContext.setAttribute(Globals.CLASS_PATH_ATTR, classpath.toString());

}

From source file:org.apache.catalina.startup.TldConfig.java

/**
 * Returns a map of the paths to all JAR files that are accessible to the
 * webapp and will be scanned for TLDs.//from  w w w .  ja v  a  2  s.com
 *
 * The map always includes all the JARs under WEB-INF/lib, as well as
 * shared JARs in the classloader delegation chain of the webapp's
 * classloader.
 *
 * The latter constitutes a Tomcat-specific extension to the TLD search
 * order defined in the JSP spec. It allows tag libraries packaged as JAR
 * files to be shared by web applications by simply dropping them in a 
 * location that all web applications have access to (e.g.,
 * <CATALINA_HOME>/common/lib).
 *
 * The set of shared JARs to be scanned for TLDs is narrowed down by
 * the <tt>noTldJars</tt> class variable, which contains the names of JARs
 * that are known not to contain any TLDs.
 *
 * @return Map of JAR file paths
 */
private Map getJarPaths() {

    HashMap jarPathMap = null;

    ClassLoader webappLoader = Thread.currentThread().getContextClassLoader();
    ClassLoader loader = webappLoader;
    while (loader != null) {
        if (loader instanceof URLClassLoader) {
            URL[] urls = ((URLClassLoader) loader).getURLs();
            for (int i = 0; i < urls.length; i++) {
                // Expect file URLs
                // This is definitely not as clean as using JAR URLs either
                // over file or the custom jndi handler, but a lot less
                // buggy overall
                File file = new File(urls[i].getFile());
                try {
                    file = file.getCanonicalFile();
                } catch (IOException e) {
                    // Ignore
                }
                if (!file.exists()) {
                    continue;
                }
                String path = file.getAbsolutePath();
                if (!path.endsWith(".jar")) {
                    continue;
                }
                /*
                 * Scan all JARs from WEB-INF/lib, plus any shared JARs
                 * that are not known not to contain any TLDs
                 */
                if (loader == webappLoader || noTldJars == null || !noTldJars.contains(file.getName())) {
                    if (jarPathMap == null) {
                        jarPathMap = new HashMap();
                        jarPathMap.put(path, file);
                    } else if (!jarPathMap.containsKey(path)) {
                        jarPathMap.put(path, file);
                    }
                }
            }
        }
        loader = loader.getParent();
    }

    return jarPathMap;
}

From source file:org.apache.hadoop.hive.common.JavaUtils.java

public static boolean closeClassLoadersTo(ClassLoader current, ClassLoader stop) {
    if (!isValidHierarchy(current, stop)) {
        return false;
    }/*from   w w  w.  j a  v  a2  s. co  m*/
    for (; current != null && current != stop; current = current.getParent()) {
        try {
            closeClassLoader(current);
        } catch (IOException e) {
            LOG.info("Failed to close class loader " + current
                    + Arrays.toString(((URLClassLoader) current).getURLs()), e);
        }
    }
    return true;
}

From source file:org.apache.hadoop.hive.common.JavaUtils.java

private static boolean isValidHierarchy(ClassLoader current, ClassLoader stop) {
    if (current == null || stop == null || current == stop) {
        return false;
    }/*  w  w w  .  jav a2 s  .  com*/
    for (; current != null && current != stop; current = current.getParent()) {
    }
    return current == stop;
}

From source file:org.apache.jasper.compiler.TldLocationsCache.java

private void scanJars() throws Exception {

    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    while (loader != null) {
        if (loader instanceof URLClassLoader) {
            URL[] urls = ((URLClassLoader) loader).getURLs();
            for (int i = 0; i < urls.length; i++) {
                URLConnection conn = urls[i].openConnection();
                if (conn instanceof JarURLConnection) {
                    scanJar((JarURLConnection) conn, true);
                } else {
                    String urlStr = urls[i].toString();
                    if (urlStr.startsWith(FILE_PROTOCOL) && urlStr.endsWith(JAR_FILE_SUFFIX)) {
                        URL jarURL = new URL("jar:" + urlStr + "!/");
                        scanJar((JarURLConnection) jarURL.openConnection(), true);
                    }/*w  w  w . j a v a 2  s . c o m*/
                }
            }
        }
        loader = loader.getParent();
    }
}