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:org.cloudata.core.common.ipc.CRPC.java

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

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

    Long serverVersion = null;//  w  ww  . j av a 2s . c  o m
    try {
        synchronized (versionCheckMap) {
            if ((serverVersion = versionCheckMap.get(addr)) == null) {
                serverVersion = proxy.getProtocolVersion(protocol.getName(), clientVersion);
                versionCheckMap.put(addr, serverVersion);
            }
        }
    } catch (IOException e) {
        LOG.warn("Error proxy.getProtocolVersion:" + addr + "," + e.getMessage());
        throw e;
    } catch (Exception e) {
        IOException err = new IOException(e.getMessage());
        err.initCause(e);
        throw err;
    }

    if (serverVersion == clientVersion) {
        return proxy;
    } else {
        throw new VersionMismatch(protocol.getName(), clientVersion, serverVersion);
    }
}

From source file:org.apache.tapestry5.internal.spring.SpringModuleDef.java

private ContributionDef createContributionToMasterObjectProvider() {

    return new AbstractContributionDef() {
        @Override/*from www .ja v a 2 s.  com*/
        public String getServiceId() {
            return "MasterObjectProvider";
        }

        @Override
        public void contribute(ModuleBuilderSource moduleSource, ServiceResources resources,
                OrderedConfiguration configuration) {
            final OperationTracker tracker = resources.getTracker();

            final ApplicationContext context = resources.getService(SERVICE_ID, ApplicationContext.class);

            //region CUSTOMIZATION
            final ObjectProvider springBeanProvider = new ObjectProvider() {
                public <T> T provide(Class<T> objectType, AnnotationProvider annotationProvider,
                        ObjectLocator locator) {

                    try {
                        T bean = context.getBean(objectType);
                        if (!objectType.isInterface()) {
                            return bean;
                        }
                        // We proxify here because Tapestry calls toString method on proxy, which realizes the underlying service, with scope issues
                        return (T) Proxy.newProxyInstance(objectType.getClassLoader(),
                                new Class<?>[] { objectType }, new AbstractInvocationHandler() {
                                    @Override
                                    protected Object handleInvocation(Object proxy, Method method,
                                            Object[] args) throws Throwable {
                                        String methodName = method.getName();
                                        if (methodName.equals("equals")) {
                                            // Only consider equal when proxies are identical.
                                            return (proxy == args[0]);
                                        }
                                        if (methodName.equals("hashCode")) {
                                            // Use hashCode of proxy.
                                            return System.identityHashCode(proxy);
                                        }
                                        if (methodName.equals("toString")) {
                                            return "Current Spring " + objectType.getSimpleName();
                                        }
                                        try {
                                            return method.invoke(bean, args);
                                        } catch (InvocationTargetException e) {
                                            throw e.getCause();
                                        }
                                    }
                                });

                    } catch (NoUniqueBeanDefinitionException e) {
                        String message = String.format(
                                "Spring context contains %d beans assignable to type %s.",
                                e.getNumberOfBeansFound(), PlasticUtils.toTypeName(objectType));

                        throw new IllegalArgumentException(message, e);
                    } catch (NoSuchBeanDefinitionException e) {
                        return null;
                    }
                }
            };
            //endregion

            final ObjectProvider springBeanProviderInvoker = new ObjectProvider() {
                @Override
                public <T> T provide(final Class<T> objectType, final AnnotationProvider annotationProvider,
                        final ObjectLocator locator) {
                    return tracker.invoke("Resolving dependency by searching Spring ApplicationContext",
                            () -> springBeanProvider.provide(objectType, annotationProvider, locator));
                }
            };

            ObjectProvider outerCheck = new ObjectProvider() {
                @Override
                public <T> T provide(Class<T> objectType, AnnotationProvider annotationProvider,
                        ObjectLocator locator) {
                    // I think the following line is the only reason we put the
                    // SpringBeanProvider here,
                    // rather than in SpringModule.

                    if (!applicationContextCreated.get())
                        return null;

                    return springBeanProviderInvoker.provide(objectType, annotationProvider, locator);
                }
            };

            configuration.add("SpringBean", outerCheck, "after:AnnotationBasedContributions",
                    "after:ServiceOverride");
        }
    };
}

From source file:com.zavakid.mushroom.impl.MetricsSystemImpl.java

@Override
public synchronized void register(final Callback callback) {
    callbacks.add((Callback) Proxy.newProxyInstance(callback.getClass().getClassLoader(),
            new Class<?>[] { Callback.class }, new InvocationHandler() {

                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    try {
                        return method.invoke(callback, args);
                    } catch (Exception e) {
                        LOG.warn("Caught exception in callback " + method.getName(), e);
                    }//from w ww  .  j a  v  a2s. co  m
                    return null;
                }
            }));
}

From source file:org.kchine.r.server.http.RHttpProxy.java

public static Object getDynamicProxy(final String url, final String sessionId, final String servantName,
        Class<?>[] c, final HttpClient httpClient) {
    Object proxy = Proxy.newProxyInstance(RHttpProxy.class.getClassLoader(), c, new InvocationHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return RHttpProxy.invoke(url, sessionId, servantName, method.getName(), method.getParameterTypes(),
                    args, httpClient);//  ww w. j  a  v a  2  s  . com
        }
    });
    return proxy;
}

From source file:org.apache.olingo.ext.proxy.commons.InvokerInvocationHandler.java

@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if ("filter".equals(method.getName()) || "orderBy".equals(method.getName())
            || "top".equals(method.getName()) || "skip".equals(method.getName())
            || "expand".equals(method.getName()) || "select".equals(method.getName())) {
        invokeSelfMethod(method, args);/*from   ww  w. j a v  a2 s . c om*/
        return proxy;
    } else if ("operations".equals(method.getName()) && ArrayUtils.isEmpty(args)) {
        final EdmTypeInfo returnType = new EdmTypeInfo.Builder().setEdm(service.getClient().getCachedEdm())
                .setTypeExpression(operation.returnType()).build();

        final URI prefixURI = URIUtils.buildFunctionInvokeURI(this.baseURI, parameters);

        OperationInvocationHandler handler;

        if (returnType.isComplexType()) {
            if (returnType.isCollection()) {
                handler = OperationInvocationHandler.getInstance(new ComplexCollectionInvocationHandler(
                        targetRef, service, getClient().newURIBuilder(prefixURI.toASCIIString())));
            } else {
                handler = OperationInvocationHandler.getInstance(ComplexInvocationHandler.getInstance(targetRef,
                        service, getClient().newURIBuilder(prefixURI.toASCIIString())));
            }
        } else {
            if (returnType.isCollection()) {
                handler = OperationInvocationHandler.getInstance(new EntityCollectionInvocationHandler(service,
                        null, targetRef, null, getClient().newURIBuilder(prefixURI.toASCIIString())));
            } else {
                handler = OperationInvocationHandler
                        .getInstance(EntityInvocationHandler.getInstance(prefixURI, targetRef, service));
            }
        }

        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class<?>[] { operationRef }, handler);
    } else if (isSelfMethod(method)) {
        return invokeSelfMethod(method, args);
    } else {
        throw new NoSuchMethodException(method.getName());
    }
}

From source file:com.msopentech.odatajclient.proxy.api.impl.EntitySetInvocationHandler.java

@Override
@SuppressWarnings("unchecked")
public <S extends T> S get(final KEY key, final Class<S> typeRef) throws IllegalArgumentException {
    if (key == null) {
        throw new IllegalArgumentException("Null key");
    }/*from  ww  w .  j a va  2 s. co  m*/

    final EntityUUID uuid = new EntityUUID(ClassUtils.getNamespace(typeRef),
            containerHandler.getEntityContainerName(), entitySetName,
            ClassUtils.getNamespace(typeRef) + "." + ClassUtils.getEntityTypeName(typeRef), key);

    LOG.debug("Ask for '{}({})'", typeRef.getSimpleName(), key);

    EntityTypeInvocationHandler handler = EntityContainerFactory.getContext().entityContext().getEntity(uuid);

    if (handler == null) {
        // not yet attached: search against the service
        try {
            LOG.debug("Search for '{}({})' into the service", typeRef.getSimpleName(), key);
            final URIBuilder uriBuilder = client.getURIBuilder(this.uri.toASCIIString());

            if (key.getClass().getAnnotation(CompoundKey.class) == null) {
                LOG.debug("Append key segment '{}'", key);
                uriBuilder.appendKeySegment(key);
            } else {
                LOG.debug("Append compound key segment '{}'", key);
                uriBuilder.appendKeySegment(getCompoundKey(key));
            }

            LOG.debug("Execute query '{}'", uriBuilder.toString());

            final ODataRetrieveResponse<ODataEntity> res = client.getRetrieveRequestFactory()
                    .getEntityRequest(uriBuilder.build()).execute();

            handler = EntityTypeInvocationHandler.getInstance(res.getBody(), this, typeRef);
            handler.setETag(res.getEtag());
        } catch (Exception e) {
            LOG.info("Entity '" + uuid + "' not found", e);
        }
    } else if (isDeleted(handler)) {
        // object deleted
        LOG.debug("Object '{}({})' has been delete", typeRef.getSimpleName(), uuid);
        handler = null;
    }

    return handler == null ? null
            : (S) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                    new Class<?>[] { typeRef }, handler);
}

From source file:org.apache.hadoop.hdfs.NameNodeProxies.java

/**
 * Generate a dummy namenode proxy instance that utilizes our hacked
 * {@link LossyRetryInvocationHandler}. Proxy instance generated using this
 * method will proactively drop RPC responses. Currently this method only
 * support HA setup. null will be returned if the given configuration is not 
 * for HA.//from www . j  a v a2  s  .  c  o  m
 * 
 * @param config the configuration containing the required IPC
 *        properties, client failover configurations, etc.
 * @param nameNodeUri the URI pointing either to a specific NameNode
 *        or to a logical nameservice.
 * @param xface the IPC interface which should be created
 * @param numResponseToDrop The number of responses to drop for each RPC call
 * @param fallbackToSimpleAuth set to true or false during calls to indicate if
 *   a secure client falls back to simple auth
 * @return an object containing both the proxy and the associated
 *         delegation token service it corresponds to. Will return null of the
 *         given configuration does not support HA.
 * @throws IOException if there is an error creating the proxy
 */
@SuppressWarnings("unchecked")
public static <T> ProxyAndInfo<T> createProxyWithLossyRetryHandler(Configuration config, URI nameNodeUri,
        Class<T> xface, int numResponseToDrop, AtomicBoolean fallbackToSimpleAuth) throws IOException {
    Preconditions.checkArgument(numResponseToDrop > 0);
    Class<FailoverProxyProvider<T>> failoverProxyProviderClass = getFailoverProxyProviderClass(config,
            nameNodeUri, xface);
    if (failoverProxyProviderClass != null) { // HA case
        FailoverProxyProvider<T> failoverProxyProvider = createFailoverProxyProvider(config,
                failoverProxyProviderClass, xface, nameNodeUri, fallbackToSimpleAuth);
        int delay = config.getInt(DFS_CLIENT_FAILOVER_SLEEPTIME_BASE_KEY,
                DFS_CLIENT_FAILOVER_SLEEPTIME_BASE_DEFAULT);
        int maxCap = config.getInt(DFS_CLIENT_FAILOVER_SLEEPTIME_MAX_KEY,
                DFS_CLIENT_FAILOVER_SLEEPTIME_MAX_DEFAULT);
        int maxFailoverAttempts = config.getInt(DFS_CLIENT_FAILOVER_MAX_ATTEMPTS_KEY,
                DFS_CLIENT_FAILOVER_MAX_ATTEMPTS_DEFAULT);
        int maxRetryAttempts = config.getInt(HdfsClientConfigKeys.Retry.MAX_ATTEMPTS_KEY,
                HdfsClientConfigKeys.Retry.MAX_ATTEMPTS_DEFAULT);
        InvocationHandler dummyHandler = new LossyRetryInvocationHandler<T>(numResponseToDrop,
                failoverProxyProvider,
                RetryPolicies.failoverOnNetworkException(RetryPolicies.TRY_ONCE_THEN_FAIL, maxFailoverAttempts,
                        Math.max(numResponseToDrop + 1, maxRetryAttempts), delay, maxCap));

        T proxy = (T) Proxy.newProxyInstance(failoverProxyProvider.getInterface().getClassLoader(),
                new Class[] { xface }, dummyHandler);
        Text dtService = HAUtil.buildTokenServiceForLogicalUri(nameNodeUri);
        return new ProxyAndInfo<T>(proxy, dtService);
    } else {
        LOG.warn("Currently creating proxy using " + "LossyRetryInvocationHandler requires NN HA setup");
        return null;
    }
}

From source file:gov.nih.nci.firebird.proxy.PoolingHandlerTest.java

@Test
public void testPoolDepletion() throws InterruptedException {
    Provider<BaseClient> provider = new Provider<BaseClient>() {
        @Override/*from   w ww  .j av a  2s .  c  o  m*/
        public BaseClient get() {
            return new BaseClient();
        }
    };
    PoolingHandler handler = new PoolingHandler(provider, 3, 0);
    final ITestClient proxy = (ITestClient) Proxy.newProxyInstance(this.getClass().getClassLoader(),
            new Class<?>[] { ITestClient.class }, handler);

    for (int i = 0; i < 5; i++) {
        Thread t = new Thread() {
            @Override
            public void run() {
                proxy.block();
            }
        };
        t.start();
    }

    synchronized (threads) {
        while (threads.size() < 5) {
            threads.wait(500L);
        }
    }
    // all threads started
    assertEquals(0, handler.getPool().getNumIdle());
    assertEquals(5, handler.getPool().getNumActive());

    // let threads resume.
    synchronized (BaseClient.class) {
        BaseClient.class.notifyAll();
    }

    for (Thread t : threads) {
        t.join();
    }
    assertEquals(3, handler.getPool().getNumIdle());
}

From source file:eu.stratosphere.nephele.ipc.RPC.java

/**
 * Construct a client-side proxy object that implements the named protocol,
 * talking to a server at the named address.
 *//*from   ww  w  .j  av  a  2  s .c om*/
public static <V extends VersionedProtocol> V getProxy(Class<V> protocol, InetSocketAddress addr,
        SocketFactory factory) throws IOException {

    @SuppressWarnings("unchecked")
    V proxy = (V) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol },
            new Invoker(addr, factory));

    return proxy;
}

From source file:org.apache.openejb.resource.AutoConnectionTracker.java

private Object newProxy(final Object handle, final InvocationHandler invocationHandler) {
    ClassLoader loader = handle.getClass().getClassLoader();
    if (loader == null) {
        loader = ClassLoader.getSystemClassLoader();
    }/* w w w .j av  a  2 s. co  m*/
    if (!Proxy.isProxyClass(handle.getClass())) {
        final Object proxy = LocalBeanProxyFactory.Unsafe.allocateInstance(getProxy(handle.getClass(), loader));
        DynamicSubclass.setHandler(proxy, invocationHandler);
        return proxy;
    }

    return Proxy.newProxyInstance(loader, getAPi(handle.getClass()), invocationHandler);
}