Example usage for java.lang.reflect Proxy newProxyInstance

List of usage examples for java.lang.reflect Proxy newProxyInstance

Introduction

In this page you can find the example usage for java.lang.reflect Proxy newProxyInstance.

Prototype

private static Object newProxyInstance(Class<?> caller, 
            Constructor<?> cons, InvocationHandler h) 

Source Link

Usage

From source file:com.almende.eve.agent.AgentProxyFactory.java

/**
 * Gen proxy.//  w  ww  . j  a  v a 2  s .  co m
 * 
 * @param <T>
 *            the generic type
 * @param sender
 *            the sender
 * @param receiverUrl
 *            the receiver url
 * @param proxyInterface
 *            the interface this proxy implements
 * @return the t
 */
@SuppressWarnings("unchecked")
public static <T> T genProxy(final Agent sender, final URI receiverUrl, final Class<T> proxyInterface) {
    // http://docs.oracle.com/javase/1.4.2/docs/guide/reflection/proxy.html
    final T proxy = (T) Proxy.newProxyInstance(proxyInterface.getClassLoader(), new Class[] { proxyInterface },
            new InvocationHandler() {

                private Map<Method, Boolean> cache = new HashMap<Method, Boolean>();

                @Override
                public Object invoke(final Object proxy, final Method method, final Object[] args) {
                    boolean doSync = true;
                    if (cache.containsKey(method)) {
                        doSync = cache.get(method);
                    } else {
                        AnnotatedClass clazz = AnnotationUtil.get(proxyInterface);
                        if (clazz != null) {
                            List<AnnotatedMethod> list = clazz.getMethods(method.getName());
                            for (AnnotatedMethod m : list) {
                                if (m.getAnnotation(NoReply.class) != null) {
                                    doSync = false;
                                }
                            }
                            if (doSync && method.getReturnType().equals(void.class)
                                    && clazz.getAnnotation(NoReply.class) != null) {
                                doSync = false;
                            }
                        }
                        cache.put(method, doSync);
                    }
                    SyncCallback<JsonNode> callback = null;
                    if (doSync) {
                        callback = new SyncCallback<JsonNode>() {
                        };
                    }
                    try {
                        sender.call(receiverUrl, method, args, callback);
                    } catch (final IOException e) {
                        throw new JSONRPCException(CODE.REMOTE_EXCEPTION, e.getLocalizedMessage(), e);
                    }
                    if (callback != null) {
                        try {
                            return TypeUtil.inject(callback.get(), method.getGenericReturnType());
                        } catch (final Exception e) {
                            throw new JSONRPCException(CODE.REMOTE_EXCEPTION, e.getLocalizedMessage(), e);
                        }
                    }
                    return null;
                }
            });
    return proxy;
}

From source file:org.apache.nifi.authorization.AccessPolicyProviderFactory.java

public static AccessPolicyProvider withNarLoader(final AccessPolicyProvider baseAccessPolicyProvider,
        final ClassLoader classLoader) {
    final AccessPolicyProviderInvocationHandler invocationHandler = new AccessPolicyProviderInvocationHandler(
            baseAccessPolicyProvider, classLoader);

    // extract all interfaces... baseAccessPolicyProvider is non null so getAllInterfaces is non null
    final List<Class<?>> interfaceList = ClassUtils.getAllInterfaces(baseAccessPolicyProvider.getClass());
    final Class<?>[] interfaces = interfaceList.toArray(new Class<?>[interfaceList.size()]);

    return (AccessPolicyProvider) Proxy.newProxyInstance(classLoader, interfaces, invocationHandler);
}

From source file:com.amazonaws.http.conn.ClientConnectionRequestFactory.java

/**
 * Returns a wrapped instance of {@link ClientConnectionRequest}
 * to capture the necessary performance metrics.
 * @param orig the target instance to be wrapped
 *//*ww  w .j  a  v a2  s. co  m*/
static ClientConnectionRequest wrap(ClientConnectionRequest orig) {
    if (orig instanceof Wrapped)
        throw new IllegalArgumentException();
    return (ClientConnectionRequest) Proxy.newProxyInstance(
            // https://github.com/aws/aws-sdk-java/pull/48#issuecomment-29454423
            ClientConnectionRequestFactory.class.getClassLoader(), interfaces, new Handler(orig));
}

From source file:org.eclipse.ecr.core.storage.sql.net.MapperClient.java

public static Mapper getMapper(RepositoryImpl repository, Credentials credentials) throws StorageException {
    MapperClient handler = new MapperClient(repository, credentials);
    Mapper mapper = (Mapper) Proxy.newProxyInstance(MapperClient.class.getClassLoader(),
            new Class<?>[] { Mapper.class }, handler);
    synchronized (repository) {
        handler.repositoryId = repository.repositoryId;
        Identification id = mapper.getIdentification();
        handler.identification = id;//  w  w  w.ja v  a  2s.co m
        repository.repositoryId = id.repositoryId;
    }
    return mapper;
}

From source file:io.lavagna.common.QueryFactory.java

@SuppressWarnings("unchecked")
private static <T> T from(final Class<T> clazz, final String activeDb, final NamedParameterJdbcTemplate jdbc) {
    return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, new InvocationHandler() {
        @Override//from  w  w w . java 2s  .  com
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            QueryTypeAndQuery qs = extractQueryAnnotation(clazz, activeDb, method);
            return qs.type.apply(qs.query, jdbc, method, args);
        }
    });
}

From source file:org.apache.hadoop.hbase.thrift.HbaseHandlerMetricsProxy.java

public static Hbase.Iface newInstance(Hbase.Iface handler, ThriftMetrics metrics, Configuration conf) {
    return (Hbase.Iface) Proxy.newProxyInstance(handler.getClass().getClassLoader(),
            new Class[] { Hbase.Iface.class }, new HbaseHandlerMetricsProxy(handler, metrics, conf));
}

From source file:org.cloudata.core.common.testhelper.FaultInjectionProxy.java

@SuppressWarnings("unchecked")
public static <T> T wrap(Object body, Class<? extends T> c) {
    synchronized (fmLock) {
        if (fm == null) {
            try {
                fm = FaultManager.create(new CloudataConf());
            } catch (IOException e) {
                LOG.warn("Fail to create fault manager", e);
            }/*from   www. j ava  2  s  . c  o m*/
        }
    }
    return (T) Proxy.newProxyInstance(c.getClassLoader(), new Class<?>[] { c },
            new FaultInjectionHandler(body));
}

From source file:com.amazonaws.http.conn.ClientConnectionManagerFactory.java

/**
 * Returns a wrapped instance of {@link ClientConnectionManager}
 * to capture the necessary performance metrics.
 * @param orig the target instance to be wrapped
 */// w w w. j  av a  2s .co  m
public static ClientConnectionManager wrap(ClientConnectionManager orig) {
    if (orig instanceof Wrapped)
        throw new IllegalArgumentException();
    final Class<?>[] interfaces;
    if (orig instanceof ConnPoolControl) {
        interfaces = new Class<?>[] { ClientConnectionManager.class, ConnPoolControl.class, Wrapped.class };
    } else {
        interfaces = new Class<?>[] { ClientConnectionManager.class, Wrapped.class };
    }
    return (ClientConnectionManager) Proxy.newProxyInstance(
            // https://github.com/aws/aws-sdk-java/pull/48#issuecomment-29454423
            ClientConnectionManagerFactory.class.getClassLoader(), interfaces, new Handler(orig));
}

From source file:com.ksc.http.conn.ClientConnectionManagerFactory.java

/**
 * Returns a wrapped instance of {@link HttpClientConnectionManager}
 * to capture the necessary performance metrics.
 *
 * @param orig the target instance to be wrapped
 *//*from  w ww . ja  va2  s  . co m*/
public static HttpClientConnectionManager wrap(HttpClientConnectionManager orig) {
    if (orig instanceof Wrapped)
        throw new IllegalArgumentException();
    final Class<?>[] interfaces;
    if (orig instanceof ConnPoolControl) {
        interfaces = new Class<?>[] { HttpClientConnectionManager.class, ConnPoolControl.class, Wrapped.class };
    } else {
        interfaces = new Class<?>[] { HttpClientConnectionManager.class, Wrapped.class };
    }
    return (HttpClientConnectionManager) Proxy.newProxyInstance(
            // https://github.com/aws/aws-sdk-java/pull/48#issuecomment-29454423
            ClientConnectionManagerFactory.class.getClassLoader(), interfaces, new Handler(orig));
}

From source file:com.baidu.api.client.core.JsonProxy.java

/**
 * Create the proxy instance of api client stub. Proxied by JsonProxy.
 *
 * @param <T>        The proxy instannce type.
 * @param interfaces The proxy instannce type class.
 * @param service    The original object.
 * @return The proxied object./* ww  w.j  a v a2s.  co m*/
 */
@SuppressWarnings("unchecked")
public static <T> T createProxy(Class<T> interfaces, VersionService service) {
    JsonProxy<T> proxy = new JsonProxy<T>(interfaces, service);
    return (T) Proxy.newProxyInstance(JsonProxy.class.getClassLoader(), new Class<?>[] { interfaces }, proxy);
}