Example usage for java.lang Class getClassLoader

List of usage examples for java.lang Class getClassLoader

Introduction

In this page you can find the example usage for java.lang Class getClassLoader.

Prototype

@CallerSensitive
@ForceInline 
public ClassLoader getClassLoader() 

Source Link

Document

Returns the class loader for the class.

Usage

From source file:com.googlecode.arit.websphere.bug.JavaReflectionAdapterResourceScanner.java

public void scanForResources(ResourceListener resourceEventListener) {
    Map<Object, Object> cache = rbean.getAdapters();
    for (Entry<Object, Object> entry : cache.entrySet()) {
        Object key = entry.getKey();
        Object adapter = entry.getValue();
        Class<?> clazz;
        ClassLoaderReference clRef;//w  w  w .j  a v  a2 s. c o  m
        // In the original JavaReflectionAdapter code, the key was a Class object
        // (causing the class loader leak). The interim fix changes this to a String.
        if (key instanceof String) {
            clazz = rbf.createRBean(JavaReflectionAdapterRBean.class, adapter).getClazz();
            clRef = new SimpleClassLoaderReference(clazz.getClassLoader(), "JavaReflectionAdapter instance");
        } else if (key instanceof Class<?>) {
            clazz = (Class<?>) key;
            clRef = new SimpleClassLoaderReference(clazz.getClassLoader(), "Cache key");
        } else {
            LOG.error(
                    "Unknown JavaReflectionAdapter cache key type encountered in JavaReflectionAdapter cache: "
                            + key.getClass().getName());
            break;
        }

        String description = "Cached JavaReflectionAdapter for class " + clazz.getName();
        SimpleResource<Object> resource = new SimpleResource<Object>(resourceType, adapter, description);
        resource.addClassloaderReference(clRef);
        resourceEventListener.onResourceFound(resource);
    }
}

From source file:com.cloudbees.sdk.CommandServiceImpl.java

protected Injector createChildModule(Injector parent, final ClassLoader cl)
        throws InstantiationException, IOException {
    final List<Module> childModules = new ArrayList<Module>();
    childModules.add(new ExtensionFinder(cl) {
        @Override/*from  ww w.  j  av a2s . com*/
        protected <T> void bind(Class<? extends T> impl, Class<T> extensionPoint) {
            if (impl.getClassLoader() != cl)
                return; // only add newly discovered stuff

            // install CLIModules
            if (extensionPoint == CLIModule.class) {
                try {
                    install((Module) impl.newInstance());
                } catch (InstantiationException e) {
                    throw (Error) new InstantiationError().initCause(e);
                } catch (IllegalAccessException e) {
                    throw (Error) new IllegalAccessError().initCause(e);
                }
                return;
            }
            super.bind(impl, extensionPoint);
        }
    });

    return parent.createChildInjector(childModules);
}

From source file:com.netflix.iep.config.Configuration.java

@SuppressWarnings("unchecked")
public static <T> T newProxy(final Class<T> ctype, final String prefix) {
    InvocationHandler handler = new InvocationHandler() {
        @Override/* ww  w . j  av  a 2s  .c o  m*/
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (method.getName().equals("get")) {
                return iConfiguration.get((args[0] == null) ? null : args[0].toString());
            } else {
                Class rt = method.getReturnType();
                String key = (prefix == null) ? method.getName() : prefix + "." + method.getName();
                if (IConfiguration.class.isAssignableFrom(rt)) {
                    return newProxy(rt, key);
                } else {
                    String value = iConfiguration.get(key);
                    if (value == null) {
                        DefaultValue anno = method.getAnnotation(DefaultValue.class);
                        value = (anno == null) ? null : anno.value();
                    }
                    if (value == null) {
                        if (rt.isPrimitive())
                            throw new IllegalStateException("no value for property " + method.getName());
                        return null;
                    }
                    return Strings.cast(rt, value);
                }
            }
        }
    };
    return (T) Proxy.newProxyInstance(ctype.getClassLoader(), new Class[] { ctype }, handler);
}

From source file:ipc.WritableRpcEngine.java

/** Construct a client-side proxy object that implements the named protocol,
 * talking to a server at the named address. */
public Object getProxy(Class protocol, long clientVersion, InetSocketAddress addr, Configuration conf,
        SocketFactory factory) throws IOException {

    Object proxy = Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol },
            new Invoker(protocol, addr, conf, factory));

    //    Object proxy = Proxy.newProxyInstance
    //            (protocol.getClassLoader(), new Class[] { protocol },
    //             new InvocationHandler() {
    ////from   w  w w . j  a  va 2 s. c  o m
    //                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    //                    return null;
    //                }
    //                
    //            });
    return proxy;
}

From source file:eu.esdihumboldt.hale.common.align.model.impl.AbstractCellExplanation.java

/**
 * Get a message for a specific locale.//  w w  w . j av a  2  s  .co m
 * 
 * @param key the message key
 * @param locale the locale
 * @param messageClass the class the messages to retrieve are associated to
 * @return the message string
 */
protected String getMessage(String key, Locale locale, Class<?> messageClass) {
    return ResourceBundle
            .getBundle(messageClass.getName(), locale, messageClass.getClassLoader(),
                    ResourceBundle.Control.getNoFallbackControl(ResourceBundle.Control.FORMAT_PROPERTIES))
            .getString(key);
}

From source file:org.apache.brooklyn.rest.client.BrooklynApi.java

@SuppressWarnings("unchecked")
private <T> T proxy(Class<T> clazz) {
    final T result0 = ProxyFactory.create(clazz, target, clientExecutor);
    return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[] { clazz },
            new InvocationHandler() {
                @Override/*from  w  w w  . ja v a  2 s.c o  m*/
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    try {
                        Object result1 = method.invoke(result0, args);
                        Class<?> type = String.class;
                        if (result1 instanceof Response) {
                            Response resp = (Response) result1;
                            if (isStatusCodeHealthy(resp.getStatus())
                                    && method.isAnnotationPresent(ApiOperation.class)) {
                                type = getClassFromMethodAnnotationOrDefault(method, type);
                            }
                            // wrap the original response so it self-closes
                            result1 = BuiltResponsePreservingError.copyResponseAndClose(resp, type);
                        }
                        return result1;
                    } catch (Throwable e) {
                        if (e instanceof InvocationTargetException) {
                            // throw the original exception
                            e = ((InvocationTargetException) e).getTargetException();
                        }
                        throw Exceptions.propagate(e);
                    }
                }

                private boolean isStatusCodeHealthy(int code) {
                    return (code >= 200 && code <= 299);
                }

                private Class<?> getClassFromMethodAnnotationOrDefault(Method method, Class<?> def) {
                    Class<?> type;
                    try {
                        type = method.getAnnotation(ApiOperation.class).response();
                    } catch (Exception e) {
                        type = def;
                        LOG.debug("Unable to get class from annotation: {}.  Defaulting to {}", e.getMessage(),
                                def.getName());
                        Exceptions.propagateIfFatal(e);
                    }
                    return type;
                }
            });
}

From source file:com.medallia.spider.api.StRenderer.java

private Object createInput(Class<?> x, final DynamicInputImpl dynamicInput) {
    return Proxy.newProxyInstance(x.getClassLoader(), new Class<?>[] { x }, new InvocationHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return dynamicInput.getInput(method.getName(), method.getReturnType(), method);
        }//from ww w .ja v  a2 s  .  com
    });
}

From source file:com.liferay.portal.search.elasticsearch.internal.connection.EmbeddedElasticsearchConnection.java

protected Node createNode(Settings settings) {
    Thread thread = Thread.currentThread();

    ClassLoader contextClassLoader = thread.getContextClassLoader();

    Class<?> clazz = getClass();

    thread.setContextClassLoader(clazz.getClassLoader());

    String jnaTmpDir = System.getProperty("jna.tmpdir");

    System.setProperty("jna.tmpdir", _jnaTmpDirName);

    try {//w  w  w.  jav a2  s .  c  om
        NodeBuilder nodeBuilder = new NodeBuilder();

        nodeBuilder.settings(settings);

        nodeBuilder.local(true);

        Node node = nodeBuilder.build();

        if (elasticsearchConfiguration.syncSearch()) {
            Injector injector = node.injector();

            _replaceTransportRequestHandler(injector.getInstance(TransportService.class),
                    injector.getInstance(SearchService.class));
        }

        return node;
    } finally {
        thread.setContextClassLoader(contextClassLoader);

        if (jnaTmpDir == null) {
            System.clearProperty("jna.tmpdir");
        } else {
            System.setProperty("jna.tmpdir", jnaTmpDir);
        }
    }
}

From source file:org.eclipse.gyrex.http.jetty.internal.JettyEngineApplication.java

private ServerConnector createJettyConnector(final Server server, final SslContextFactory sslFactory,
        final HttpConfiguration httpConfig) {
    try {//from  w  w  w .ja  v  a2  s  .  com
        // use SPDY if NPN is available
        final Class<?> npnClass = HttpJettyActivator.getInstance().getBundle()
                .loadClass("org.eclipse.jetty.npn.NextProtoNego");
        if (npnClass.getClassLoader() == null) {
            // NPN is available; try loading the SPDY connector
            // note, we still use reflection because SPDY is optional
            final Class<?> spdyConnectorClass = HttpJettyActivator.getInstance().getBundle()
                    .loadClass("org.eclipse.jetty.spdy.server.http.HTTPSPDYServerConnector");
            // HTTPSPDYServerConnector(Server server, HttpConfiguration config, SslContextFactory sslContextFactory, Map<Short, PushStrategy> pushStrategies)
            final Constructor<?> constructor = spdyConnectorClass.getConstructor(Server.class,
                    HttpConfiguration.class, SslContextFactory.class, Map.class);
            return (ServerConnector) constructor.newInstance(server, httpConfig, sslFactory, null);
        } else {
            // log error and fall through; will force standard connector belog
            LOG.error(
                    "Jetty NPN not loaded via boot class loader. Falling back to non-SPDY setup. Please check your server setup (see http://wiki.eclipse.org/Jetty/Feature/NPN for details)! ({})",
                    npnClass.getClassLoader());
        }
    } catch (AssertionError | LinkageError | ClassNotFoundException e) {
        if (JettyDebug.engine) {
            LOG.debug("Jetty SPDY environment not available: {}", ExceptionUtils.getRootCauseMessage(e), e);
        }
    } catch (final Exception e) {
        LOG.error("Error loading the Jetty SPDY implementation. {}", ExceptionUtils.getRootCauseMessage(e), e);
    }
    LOG.info("Jetty SPDY environment not available. Using non SPDY implementation.");
    return new ServerConnector(server, sslFactory, new HttpConnectionFactory(httpConfig));
}

From source file:org.impalaframework.classloader.FileSystemClassLoader.java

/**
 * Attempts to load class from one of the locations supplied via a
 * constructor. Designed to be used by subclasses.
 * @param className name of class to load
 * @return a <code>Class</code> instance, if the class could be loaded,
 * otherwise null.//from  w  ww . j ava 2 s .com
 */
protected Class<?> loadCustomClass(String className) {

    byte[] classData = null;

    try {

        classData = findClassBytes(className);

        if (classData != null) {
            Class<?> result = defineClass(className, classData, 0, classData.length, null);

            if (logger.isDebugEnabled())
                debug("Returning class newly loaded from custom location: {}" + className);

            loadedClasses.put(className, result);

            logger.info("ModuleClassLoader: " + className + " loaded by " + result.getClassLoader());
        }

        return null;

    } catch (IOException e) {
        logger.error("IOException attempting to read class " + className + " from location(s) "
                + Arrays.toString(locations));
        return null;
    } catch (ClassFormatError e) {
        logger.error(
                "Invalid format for class " + className + " from location(s) " + Arrays.toString(locations));
        return null;
    }
}