Example usage for java.lang ClassLoader getClass

List of usage examples for java.lang ClassLoader getClass

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:com.samples.platform.service.common.GetServiceStatusOperation.java

/**
 * @param message/*w w  w.ja  v  a  2s.c o m*/
 *            the {@link JAXBElement} containing a
 *            {@link GetServiceStatusRequestType}.
 * @return the {@link JAXBElement} with a
 *         {@link GetServiceStatusResponseType}.
 */
@InsightEndPoint
@ServiceActivator
public final JAXBElement<GetServiceStatusResponseType> getServiceStatus(
        final JAXBElement<GetServiceStatusRequestType> message) {
    this.logger.debug("+getServiceStatus");
    GetServiceStatusResponseType response = this.of.createGetServiceStatusResponseType();
    try {
        PropertyType p;
        ClassLoader cl;
        URL[] urls;
        ClassLoader sysCl = ClassLoader.getSystemClassLoader();

        response.setStatus("Service is available");

        /* System properties */
        p = new PropertyType();
        p.setName("System Properties");
        response.getDetails().add(p);
        TreeSet<String> propertyNames = new TreeSet<String>();
        propertyNames.addAll(System.getProperties().stringPropertyNames());
        for (String propertyName : propertyNames) {
            p.getValue().add(new StringBuffer(64).append(propertyName).append("=")
                    .append(System.getProperty(propertyName)).toString());
        }

        /* Application properties. */
        p = new PropertyType();
        p.setName("Application loaded properties");
        response.getDetails().add(p);
        propertyNames.clear();
        propertyNames.addAll(this.properties.stringPropertyNames());
        for (String propertyName : propertyNames) {
            p.getValue().add(new StringBuffer(64).append(propertyName).append("=")
                    .append(this.properties.getProperty(propertyName)).toString());
        }

        /* Current lass loader */
        cl = this.getClass().getClassLoader();
        p = new PropertyType();
        p.setName("This ClassLoader");
        response.getDetails().add(p);
        p.getValue().add(cl.getClass().getName());
        if (URLClassLoader.class.isInstance(cl)) {
            urls = ((URLClassLoader) cl).getURLs();
            p.getValue().add(new StringBuffer("Url: ").append(urls.length).toString());
            for (URL url : urls) {
                p.getValue().add(url.toString());
            }
        }
        cl = cl.getParent();
        while (cl != sysCl) {
            p = new PropertyType();
            p.setName("Parent Classloader");
            response.getDetails().add(p);
            p.getValue().add(cl.getClass().getName());
            if (URLClassLoader.class.isInstance(cl)) {
                urls = ((URLClassLoader) cl).getURLs();
                p.getValue().add(new StringBuffer("Url: ").append(urls.length).toString());
                for (URL url : urls) {
                    p.getValue().add(url.toString());
                }
            }
            cl = cl.getParent();
        }

        /* System class loader */
        cl = sysCl;
        p = new PropertyType();
        p.setName("SystemClassLoader");
        response.getDetails().add(p);
        p.getValue().add(cl.getClass().getName());
        if (URLClassLoader.class.isInstance(cl)) {
            urls = ((URLClassLoader) cl).getURLs();
            p.getValue().add(new StringBuffer("Url: ").append(urls.length).toString());
            for (URL url : urls) {
                p.getValue().add(url.toString());
            }
        }
    } catch (Throwable e) {
        this.logger.error(e.getMessage(), e);
    } finally {
        this.logger.debug("-getServiceStatus #{}, #f{}", response/* .get() */ != null ? 1 : 0,
                response.getFailure().size());
    }
    return this.of.createGetServiceStatusResponse(response);
}

From source file:info.magnolia.freemarker.FreemarkerServletContextWrapper.java

@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Set getResourcePaths(String path) {
    if (StringUtils.equals(path, "/WEB-INF/lib")) {
        log.debug("returning resources from classpath");
        // Just when asking libraries, pass the classpath ones.
        final Set<String> resources = new HashSet<String>();
        final ClassLoader cl = Thread.currentThread().getContextClassLoader();
        // if the classloader is an URLClassloader we have a better method for discovering resources
        // whis will also fetch files from jars outside WEB-INF/lib, useful during development
        if (cl instanceof URLClassLoader) {
            final URLClassLoader urlClassLoader = (URLClassLoader) cl;
            final URL[] urls = urlClassLoader.getURLs();
            for (int j = 0; j < urls.length; j++) {
                final File tofile = sanitizeToFile(urls[j]);
                if (tofile.isDirectory()) {
                    for (File file : ((List<File>) FileUtils.listFiles(tofile, null, true))) {
                        resources.add(file.getAbsolutePath());
                    }/*ww  w.j a v a  2 s . com*/
                } else {
                    resources.add(tofile.getAbsolutePath());
                }
            }

            return resources;
        }
        try {
            // be friendly to WAS developers too...
            // in development mode under RAD 7.5 here we have an instance of com.ibm.ws.classloader.WsClassLoader
            // and jars are NOT deployed to WEB-INF/lib by default, so they can't be found without this explicit
            // check
            //
            // but since we don't want to depend on WAS stuff we just check if the cl exposes a "classPath" property
            PropertyDescriptor pd = new PropertyDescriptor("classPath", cl.getClass());
            if (pd != null && pd.getReadMethod() != null) {
                String classpath = (String) pd.getReadMethod().invoke(cl, new Object[] {});
                if (StringUtils.isNotBlank(classpath)) {
                    String[] paths = StringUtils.split(classpath, File.pathSeparator);
                    for (int j = 0; j < paths.length; j++) {
                        final File tofile = new File(paths[j]);
                        // there can be several missing (optional?) paths here...
                        if (tofile.exists()) {
                            if (tofile.isDirectory()) {
                                for (File file : ((List<File>) FileUtils.listFiles(tofile, null, true))) {
                                    resources.add(file.getAbsolutePath());
                                }
                            } else {
                                resources.add(tofile.getAbsolutePath());
                            }
                        }
                    }
                    return resources;
                }
            }
        } catch (Throwable e) {
            // no, it's not a classloader we can handle in a special way
        }
        // no way, we have to assume a standard war structure and look in the WEB-INF/lib and WEB-INF/classes dirs
        // read the jars in the lib dir
    }
    return parentContext.getResourcePaths(path);
}

From source file:net.sf.jabref.gui.openoffice.OOBibBase.java

private XDesktop simpleBootstrap(String pathToExecutable) throws Exception {

    ClassLoader loader = ClassLoader.getSystemClassLoader();
    if (loader instanceof URLClassLoader) {
        URLClassLoader cl = (URLClassLoader) loader;
        Class<URLClassLoader> sysclass = URLClassLoader.class;
        try {//  w  w  w.jav a 2s. c o  m
            Method method = sysclass.getDeclaredMethod("addURL", URL.class);
            method.setAccessible(true);
            method.invoke(cl, new File(pathToExecutable).toURI().toURL());
        } catch (SecurityException | NoSuchMethodException | MalformedURLException t) {
            LOGGER.error("Error, could not add URL to system classloader", t);
            cl.close();
            throw new IOException("Error, could not add URL to system classloader", t);
        }
    } else {
        LOGGER.error("Error occured, URLClassLoader expected but " + loader.getClass()
                + " received. Could not continue.");
    }

    //Get the office component context:
    XComponentContext xContext = Bootstrap.bootstrap();
    //Get the office service manager:
    XMultiComponentFactory xServiceManager = xContext.getServiceManager();
    //Create the desktop, which is the root frame of the
    //hierarchy of frames that contain viewable components:
    Object desktop = xServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", xContext);
    XDesktop xD = UnoRuntime.queryInterface(XDesktop.class, desktop);

    UnoRuntime.queryInterface(XComponentLoader.class, desktop);

    return xD;

}

From source file:org.allcolor.yahp.converter.CClassLoader.java

/**
 * calculate the loader path/*  w  ww . ja v  a  2 s  . co  m*/
 * 
 * @return the calculated path
 */
private final String nGetLoaderPath() {
    ClassLoader currentLoader = this;
    final StringBuffer buffer = new StringBuffer();
    buffer.append(this.name);

    while ((currentLoader = currentLoader.getParent()) != null) {
        if (currentLoader.getClass() == CClassLoader.class) {
            buffer.insert(0, "/");
            buffer.insert(0, ((CClassLoader) currentLoader).name);
        } else {
            break;
        }
    }

    return buffer.toString();
}

From source file:org.apache.accumulo.minicluster.impl.MiniAccumuloClusterImpl.java

private String getClasspath() throws IOException {

    try {//  w  w w.ja  v a2s. c  o  m
        ArrayList<ClassLoader> classloaders = new ArrayList<ClassLoader>();

        ClassLoader cl = this.getClass().getClassLoader();

        while (cl != null) {
            classloaders.add(cl);
            cl = cl.getParent();
        }

        Collections.reverse(classloaders);

        StringBuilder classpathBuilder = new StringBuilder();
        classpathBuilder.append(config.getConfDir().getAbsolutePath());

        if (config.getHadoopConfDir() != null)
            classpathBuilder.append(File.pathSeparator).append(config.getHadoopConfDir().getAbsolutePath());

        if (config.getClasspathItems() == null) {

            // assume 0 is the system classloader and skip it
            for (int i = 1; i < classloaders.size(); i++) {
                ClassLoader classLoader = classloaders.get(i);

                if (classLoader instanceof URLClassLoader) {

                    for (URL u : ((URLClassLoader) classLoader).getURLs()) {
                        append(classpathBuilder, u);
                    }

                } else if (classLoader instanceof VFSClassLoader) {

                    VFSClassLoader vcl = (VFSClassLoader) classLoader;
                    for (FileObject f : vcl.getFileObjects()) {
                        append(classpathBuilder, f.getURL());
                    }
                } else {
                    throw new IllegalArgumentException(
                            "Unknown classloader type : " + classLoader.getClass().getName());
                }
            }
        } else {
            for (String s : config.getClasspathItems())
                classpathBuilder.append(File.pathSeparator).append(s);
        }

        return classpathBuilder.toString();

    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
}

From source file:org.apache.accumulo.minicluster.MiniAccumuloCluster.java

private String getClasspath() throws IOException {

    try {/* ww  w  .  j  a  v  a  2 s  .  co  m*/
        ArrayList<ClassLoader> classloaders = new ArrayList<ClassLoader>();

        ClassLoader cl = this.getClass().getClassLoader();

        while (cl != null) {
            classloaders.add(cl);
            cl = cl.getParent();
        }

        Collections.reverse(classloaders);

        StringBuilder classpathBuilder = new StringBuilder();
        classpathBuilder.append(config.getConfDir().getAbsolutePath());

        if (config.getClasspathItems() == null) {

            // assume 0 is the system classloader and skip it
            for (int i = 1; i < classloaders.size(); i++) {
                ClassLoader classLoader = classloaders.get(i);

                if (classLoader instanceof URLClassLoader) {

                    URLClassLoader ucl = (URLClassLoader) classLoader;

                    for (URL u : ucl.getURLs()) {
                        append(classpathBuilder, u);
                    }

                } else if (classLoader instanceof VFSClassLoader) {

                    VFSClassLoader vcl = (VFSClassLoader) classLoader;
                    for (FileObject f : vcl.getFileObjects()) {
                        append(classpathBuilder, f.getURL());
                    }
                } else {
                    throw new IllegalArgumentException(
                            "Unknown classloader type : " + classLoader.getClass().getName());
                }
            }
        } else {
            for (String s : config.getClasspathItems())
                classpathBuilder.append(File.pathSeparator).append(s);
        }

        return classpathBuilder.toString();

    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
}

From source file:org.apache.accumulo.start.classloader.vfs.AccumuloVFSClassLoader.java

public static void printClassPath(Printer out) {
    try {//from  w w  w .  j  av a2  s  .  co  m
        ClassLoader cl = getClassLoader();
        ArrayList<ClassLoader> classloaders = new ArrayList<ClassLoader>();

        while (cl != null) {
            classloaders.add(cl);
            cl = cl.getParent();
        }

        Collections.reverse(classloaders);

        int level = 0;

        for (ClassLoader classLoader : classloaders) {
            if (level > 0)
                out.print("");
            level++;

            String classLoaderDescription;

            switch (level) {
            case 1:
                classLoaderDescription = level + ": Java System Classloader (loads Java system resources)";
                break;
            case 2:
                classLoaderDescription = level
                        + ": Java Classloader (loads everything defined by java classpath)";
                break;
            case 3:
                classLoaderDescription = level
                        + ": Accumulo Classloader (loads everything defined by general.classpaths)";
                break;
            case 4:
                classLoaderDescription = level
                        + ": Accumulo Dynamic Classloader (loads everything defined by general.dynamic.classpaths)";
                break;
            default:
                classLoaderDescription = level
                        + ": Mystery Classloader (someone probably added a classloader and didn't update the switch statement in "
                        + AccumuloVFSClassLoader.class.getName() + ")";
                break;
            }

            if (classLoader instanceof URLClassLoader) {
                // If VFS class loader enabled, but no contexts defined.
                out.print("Level " + classLoaderDescription + " URL classpath items are:");

                for (URL u : ((URLClassLoader) classLoader).getURLs()) {
                    out.print("\t" + u.toExternalForm());
                }

            } else if (classLoader instanceof VFSClassLoader) {
                out.print("Level " + classLoaderDescription + " VFS classpaths items are:");
                VFSClassLoader vcl = (VFSClassLoader) classLoader;
                for (FileObject f : vcl.getFileObjects()) {
                    out.print("\t" + f.getURL().toExternalForm());
                }
            } else {
                out.print("Unknown classloader configuration " + classLoader.getClass());
            }
        }

    } catch (Throwable t) {
        throw new RuntimeException(t);
    }
}

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

/**
 * Check for a valid relationship between unmarshalling classloader and
 * Application's current context classloader
 * @param cl//from   w  ww  . j  av  a 2 s. c  om
 * @param contextCL
 */
private void checkClassLoader(final ClassLoader cl, final ClassLoader contextCL) {
    // Ensure that the classloader (cl) used for unmarshalling is the same
    // or a parent of the current context classloader.  Otherwise 
    // ClassCastExceptions can occur
    if (log.isDebugEnabled()) {
        log.debug("AsyncResponse ClassLoader is:");
        log.debug(cl.toString());
    }
    if (cl.equals(contextCL)) {
        if (log.isDebugEnabled()) {
            log.debug("AsyncResponse ClassLoader matches Context ClassLoader");
        }
        return;
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Context ClassLoader is:");
            log.debug(contextCL.toString());
        }
        ClassLoader parent = getParentClassLoader(contextCL);
        while (parent != null) {
            if (parent.equals(cl)) {
                return;
            }
            if (log.isDebugEnabled()) {
                log.debug("AsyncResponse ClassLoader is an ancestor of the Context ClassLoader");
            }
            parent = getParentClassLoader(parent);
        }
    }
    throw ExceptionFactory.makeWebServiceException(Messages.getMessage("threadClsLoaderErr",
            contextCL.getClass().toString(), cl.getClass().toString()));
}

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  ava  2  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.camel.impl.DefaultPackageScanClassResolver.java

protected void find(PackageScanFilter test, String packageName, ClassLoader loader, Set<Class<?>> classes) {
    if (log.isTraceEnabled()) {
        log.trace("Searching for: " + test + " in package: " + packageName + " using classloader: "
                + loader.getClass().getName());
    }/*from  w  w w.j av a2s  . c  o m*/

    Enumeration<URL> urls;
    try {
        urls = getResources(loader, packageName);
        if (!urls.hasMoreElements()) {
            log.trace("No URLs returned by classloader");
        }
    } catch (IOException ioe) {
        log.warn("Cannot read package: " + packageName, ioe);
        return;
    }

    while (urls.hasMoreElements()) {
        URL url = null;
        try {
            url = urls.nextElement();
            if (log.isTraceEnabled()) {
                log.trace("URL from classloader: " + url);
            }

            url = customResourceLocator(url);

            String urlPath = url.getFile();
            urlPath = URLDecoder.decode(urlPath, "UTF-8");
            if (log.isTraceEnabled()) {
                log.trace("Decoded urlPath: " + urlPath + " with protocol: " + url.getProtocol());
            }

            // If it's a file in a directory, trim the stupid file: spec
            if (urlPath.startsWith("file:")) {
                // file path can be temporary folder which uses characters that the URLDecoder decodes wrong
                // for example + being decoded to something else (+ can be used in temp folders on Mac OS)
                // to remedy this then create new path without using the URLDecoder
                try {
                    urlPath = new URI(url.getFile()).getPath();
                } catch (URISyntaxException e) {
                    // fallback to use as it was given from the URLDecoder
                    // this allows us to work on Windows if users have spaces in paths
                }

                if (urlPath.startsWith("file:")) {
                    urlPath = urlPath.substring(5);
                }
            }

            // osgi bundles should be skipped
            if (url.toString().startsWith("bundle:") || urlPath.startsWith("bundle:")) {
                log.trace("It's a virtual osgi bundle, skipping");
                continue;
            }

            // Else it's in a JAR, grab the path to the jar
            if (urlPath.indexOf('!') > 0) {
                urlPath = urlPath.substring(0, urlPath.indexOf('!'));
            }

            if (log.isTraceEnabled()) {
                log.trace("Scanning for classes in [" + urlPath + "] matching criteria: " + test);
            }

            File file = new File(urlPath);
            if (file.isDirectory()) {
                if (log.isTraceEnabled()) {
                    log.trace("Loading from directory using file: " + file);
                }
                loadImplementationsInDirectory(test, packageName, file, classes);
            } else {
                InputStream stream;
                if (urlPath.startsWith("http:") || urlPath.startsWith("https:")
                        || urlPath.startsWith("sonicfs:") || isAcceptableScheme(urlPath)) {
                    // load resources using http/https, sonicfs and other acceptable scheme
                    // sonic ESB requires to be loaded using a regular URLConnection
                    if (log.isTraceEnabled()) {
                        log.trace("Loading from jar using url: " + urlPath);
                    }
                    URL urlStream = new URL(urlPath);
                    URLConnection con = urlStream.openConnection();
                    // disable cache mainly to avoid jar file locking on Windows
                    con.setUseCaches(false);
                    stream = con.getInputStream();
                } else {
                    if (log.isTraceEnabled()) {
                        log.trace("Loading from jar using file: " + file);
                    }
                    stream = new FileInputStream(file);
                }

                loadImplementationsInJar(test, packageName, stream, urlPath, classes);
            }
        } catch (IOException e) {
            // use debug logging to avoid being to noisy in logs
            log.debug("Cannot read entries in url: " + url, e);
        }
    }
}