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:org.apache.hadoop.hbase.ipc.WritableRpcEngine.java

/** Construct a client-side proxy object that implements the named protocol,
 * talking to a server at the named address. */
public VersionedProtocol getProxy(Class<? extends VersionedProtocol> protocol, long clientVersion,
        InetSocketAddress addr, User ticket, Configuration conf, SocketFactory factory, int rpcTimeout)
        throws IOException {

    VersionedProtocol proxy = (VersionedProtocol) Proxy.newProxyInstance(protocol.getClassLoader(),
            new Class[] { protocol }, new Invoker(protocol, addr, ticket, conf, factory, rpcTimeout));
    if (proxy instanceof VersionedProtocol) {
        long serverVersion = ((VersionedProtocol) proxy).getProtocolVersion(protocol.getName(), clientVersion);
        if (serverVersion != clientVersion) {
            throw new HBaseRPC.VersionMismatch(protocol.getName(), clientVersion, serverVersion);
        }//from   w ww.  jav  a2s  .  com
    }
    return proxy;
}

From source file:com.hortonworks.hbase.replication.bridge.WritableRpcEngine.java

/** Construct a client-side proxy object that implements the named protocol,
 * talking to a server at the named address. */
@Override// w w w .ja  v a  2 s .c o  m
public <T extends VersionedProtocol> T getProxy(Class<T> protocol, long clientVersion, InetSocketAddress addr,
        Configuration conf, int rpcTimeout) throws IOException {
    if (this.client == null) {
        throw new IOException("Client must be initialized by calling setConf(Configuration)");
    }

    T proxy = (T) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol },
            new Invoker(client, protocol, addr, User.getCurrent(), conf, HBaseRPC.getRpcTimeout(rpcTimeout)));

    /*
     * TODO: checking protocol version only needs to be done once when we setup a new
     * HBaseClient.Connection.  Doing it every time we retrieve a proxy instance is resulting
     * in unnecessary RPC traffic.
     */
    long serverVersion = ((VersionedProtocol) proxy).getProtocolVersion(protocol.getName(), clientVersion);
    if (serverVersion != clientVersion) {
        throw new HBaseRPC.VersionMismatch(protocol.getName(), clientVersion, serverVersion);
    }

    return proxy;
}

From source file:com.alibaba.wasp.ipc.ProtobufRpcEngine.java

@Override
public VersionedProtocol getProxy(Class<? extends VersionedProtocol> protocol, long clientVersion,
        InetSocketAddress addr, Configuration conf, SocketFactory factory, int rpcTimeout) throws IOException {
    final Invoker invoker = new Invoker(protocol, addr, conf, factory, rpcTimeout);
    return (VersionedProtocol) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol },
            invoker);/*from  w ww . j  av  a2 s.  co m*/
}

From source file:org.jahia.services.htmlvalidator.WAIValidatorTest.java

private String[] getResourceListing(Class clazz, String path) throws URISyntaxException, IOException {
    URL dirURL = clazz.getResource(path);
    if (dirURL != null && dirURL.getProtocol().equals("file")) {
        /* A file path: easy enough */
        return new File(dirURL.toURI()).list();
    }/*from  ww  w.  j a va2  s.co m*/

    if (dirURL == null) {
        /*
        * In case of a jar file, we can't actually find a directory.
        * Have to assume the same jar as clazz.
        */
        String me = clazz.getName().replace(".", "/") + ".class";
        dirURL = clazz.getClassLoader().getResource(me);
    }

    if (dirURL.getProtocol().equals("jar")) {
        /* A JAR path */
        String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); //strip out only the JAR file
        JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
        Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
        Set<String> result = new HashSet<String>(); //avoid duplicates in case it is a subdirectory
        while (entries.hasMoreElements()) {
            String name = entries.nextElement().getName();
            if (name.startsWith(path)) { //filter according to the path
                result.add(name);
            }
        }
        return result.toArray(new String[result.size()]);
    }

    throw new UnsupportedOperationException("Cannot list files for URL " + dirURL);
}

From source file:org.itest.impl.ITestRandomObjectGeneratorImpl.java

protected Object newDynamicProxy(Type type, final Map<String, Type> itestGenericMap,
        final ITestContext iTestContext) {
    final Class<?> clazz = ITestTypeUtil.getRawClass(type);
    final Map<String, Object> methodResults = new HashMap<String, Object>();

    Object res = Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[] { clazz },
            new InvocationHandler() {

                @Override//ww  w  . j av a2s.co m
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    String mSignature = ITestUtils.getMethodSingnature(method, true);
                    if (methodResults.containsKey(mSignature)) {
                        return methodResults.get(mSignature);
                    }
                    throw new ITestMethodExecutionException(
                            "Implementation of " + clazz.getName() + "." + mSignature + " not provided", null);
                }
            });

    Map<String, Type> map = ITestTypeUtil.getTypeMap(type, new HashMap<String, Type>());

    Class<?> t = clazz;
    do {
        for (Method m : t.getDeclaredMethods()) {
            if (!Modifier.isStatic(m.getModifiers())) {
                String signature = ITestUtils.getMethodSingnature(m, true);
                ITestParamState iTestState = iTestContext.getCurrentParam();
                ITestParamState mITestState = iTestState == null ? null : iTestState.getElement(signature);
                if (null == mITestState) {
                    mITestState = iTestState == null ? null
                            : iTestState.getElement(signature = ITestUtils.getMethodSingnature(m, false));
                }
                fillMethod(m, res, signature, map, iTestContext, methodResults);
            }
        }
        map = ITestTypeUtil.getTypeMap(clazz, map);
    } while ((t = t.getSuperclass()) != null);

    return res;
}

From source file:com.springframework.beans.BeanUtils.java

/**
 * Parse a method signature in the form {@code methodName[([arg_list])]},
 * where {@code arg_list} is an optional, comma-separated list of fully-qualified
 * type names, and attempts to resolve that signature against the supplied {@code Class}.
 * <p>When not supplying an argument list ({@code methodName}) the method whose name
 * matches and has the least number of parameters will be returned. When supplying an
 * argument type list, only the method whose name and argument types match will be returned.
 * <p>Note then that {@code methodName} and {@code methodName()} are <strong>not</strong>
 * resolved in the same way. The signature {@code methodName} means the method called
 * {@code methodName} with the least number of arguments, whereas {@code methodName()}
 * means the method called {@code methodName} with exactly 0 arguments.
 * <p>If no method can be found, then {@code null} is returned.
 * @param signature the method signature as String representation
 * @param clazz the class to resolve the method signature against
 * @return the resolved Method//from www  .ja v a2 s .  co  m
 * @see #findMethod
 * @see #findMethodWithMinimalParameters
 */
public static Method resolveSignature(String signature, Class<?> clazz) {
    Assert.hasText(signature, "'signature' must not be empty");
    Assert.notNull(clazz, "Class must not be null");
    int firstParen = signature.indexOf("(");
    int lastParen = signature.indexOf(")");
    if (firstParen > -1 && lastParen == -1) {
        throw new IllegalArgumentException(
                "Invalid method signature '" + signature + "': expected closing ')' for args list");
    } else if (lastParen > -1 && firstParen == -1) {
        throw new IllegalArgumentException(
                "Invalid method signature '" + signature + "': expected opening '(' for args list");
    } else if (firstParen == -1 && lastParen == -1) {
        return findMethodWithMinimalParameters(clazz, signature);
    } else {
        String methodName = signature.substring(0, firstParen);
        String[] parameterTypeNames = StringUtils
                .commaDelimitedListToStringArray(signature.substring(firstParen + 1, lastParen));
        Class<?>[] parameterTypes = new Class<?>[parameterTypeNames.length];
        for (int i = 0; i < parameterTypeNames.length; i++) {
            String parameterTypeName = parameterTypeNames[i].trim();
            try {
                parameterTypes[i] = ClassUtils.forName(parameterTypeName, clazz.getClassLoader());
            } catch (Throwable ex) {
                throw new IllegalArgumentException("Invalid method signature: unable to resolve type ["
                        + parameterTypeName + "] for argument " + i + ". Root cause: " + ex);
            }
        }
        return findMethod(clazz, methodName, parameterTypes);
    }
}

From source file:no.sesat.search.datamodel.DataModelFactoryImpl.java

@SuppressWarnings("unchecked")
public <T> T instantiate(final Class<T> cls, final DataModel datamodel, final Property... properties) {

    try {//from w  w w. ja  v a2s.  c o  m
        final InvocationHandler handler;

        if (null != cls.getAnnotation(DataNode.class)) {
            handler = BeanDataNodeInvocationHandler.instanceOf(cls, datamodel, properties);

        } else if (null != cls.getAnnotation(DataObject.class)) {
            handler = BeanDataObjectInvocationHandler.instanceOf(cls, properties);

        } else {
            throw new IllegalArgumentException(ERR_ONLY_DATA_NODE_OR_OBJECT);
        }

        return (T) ConcurrentProxy.newProxyInstance(cls.getClassLoader(), new Class[] { cls }, handler);

    } catch (IntrospectionException ie) {
        throw new IllegalArgumentException(ERR_ONLY_JAVA_BEAN_DATA_OBJECT);
    }
}

From source file:org.resthub.rpc.AMQPHessianProxyFactory.java

/**
 * Creates a new proxy from the specified interface.
 * @param api the interface/*from  ww  w  .j a  v  a2  s  .  c  om*/
 * @return the proxy to the object with the specified interface
 */
@SuppressWarnings("unchecked")
public <T> T create(Class<T> api) {
    if (null == api || !api.isInterface()) {
        throw new IllegalArgumentException("Parameter 'api' is required");
    }
    this.serviceInterface = api;
    this.afterPropertiesSet();
    AMQPHessianProxy handler = new AMQPHessianProxy(this);
    return (T) Proxy.newProxyInstance(api.getClassLoader(), new Class[] { api }, handler);
}

From source file:com.stratuscom.harvester.deployer.StarterServiceDeployer.java

private boolean hasMain(ClassLoader cl, String className) throws ClassNotFoundException {
    Class clazz = Class.forName(className, true, cl);
    log.log(Level.FINE, MessageNames.CLASSLOADER_IS,
            new Object[] { clazz.getName(), clazz.getClassLoader().toString() });

    // Get this through dynamic lookup becuase it won't be in the parent
    // classloader!
    try {//from   w w w .ja  va  2 s  .  c om
        Method main = clazz.getMethod(Strings.MAIN, new Class[] { String[].class });
        return true;
    } catch (NoSuchMethodException nsme) {
        return false;
    }
}