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.apache.xmlgraphics.image.loader.util.ImageUtil.java

/**
 * Decorates an ImageInputStream so the flush*() methods are ignored and have no effect.
 * The decoration is implemented using a dynamic proxy.
 * @param in the ImageInputStream//from www .j  a  v  a 2  s.  c  o m
 * @return the decorated ImageInputStream
 */
public static ImageInputStream ignoreFlushing(final ImageInputStream in) {
    return (ImageInputStream) Proxy.newProxyInstance(in.getClass().getClassLoader(),
            new Class[] { ImageInputStream.class }, new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    String methodName = method.getName();
                    //Ignore calls to flush*()
                    if (!methodName.startsWith("flush")) {
                        try {
                            return method.invoke(in, args);
                        } catch (InvocationTargetException ite) {
                            throw ite.getCause();
                        }
                    } else {
                        return null;
                    }
                }
            });
}

From source file:org.bytesoft.bytejta.supports.dubbo.spi.TransactionServiceFilter.java

public Result providerInvokeForSVC(Invoker<?> invoker, Invocation invocation) throws RpcException {
    RemoteCoordinatorRegistry remoteCoordinatorRegistry = RemoteCoordinatorRegistry.getInstance();
    TransactionBeanRegistry beanRegistry = TransactionBeanRegistry.getInstance();
    RemoteCoordinator consumeCoordinator = beanRegistry.getConsumeCoordinator();

    URL targetUrl = invoker.getUrl();
    String targetAddr = targetUrl.getIp();
    String targetName = targetUrl.getParameter("application");
    int targetPort = targetUrl.getPort();
    String address = String.format("%s:%s:%s", targetAddr, targetName, targetPort);
    InvocationContext invocationContext = new InvocationContext();
    invocationContext.setServerHost(targetAddr);
    invocationContext.setServiceKey(targetName);
    invocationContext.setServerPort(targetPort);

    RemoteCoordinator remoteCoordinator = remoteCoordinatorRegistry.getTransactionManagerStub(address);
    if (remoteCoordinator == null) {
        DubboRemoteCoordinator dubboCoordinator = new DubboRemoteCoordinator();
        dubboCoordinator.setInvocationContext(invocationContext);
        dubboCoordinator.setRemoteCoordinator(consumeCoordinator);

        remoteCoordinator = (RemoteCoordinator) Proxy.newProxyInstance(
                DubboRemoteCoordinator.class.getClassLoader(), new Class[] { RemoteCoordinator.class },
                dubboCoordinator);//from  www.  j  a va 2s . c  o m
        remoteCoordinatorRegistry.putTransactionManagerStub(address, remoteCoordinator);
    }

    TransactionRequestImpl request = new TransactionRequestImpl();
    request.setTargetTransactionCoordinator(remoteCoordinator);

    TransactionResponseImpl response = new TransactionResponseImpl();
    response.setSourceTransactionCoordinator(remoteCoordinator);

    boolean failure = false;
    try {
        this.beforeProviderInvokeForSVC(invocation, request, response);
        return this.wrapResultForProvider(invoker, invocation, true);
    } catch (RpcException rex) {
        failure = true;

        return this.createErrorResultForProvider(rex, true);
    } catch (Throwable rex) {
        failure = true;
        logger.error("Error occurred in remote call!", rex);

        return this.createErrorResultForProvider(rex, true);
    } finally {
        try {
            this.afterProviderInvokeForSVC(invocation, request, response);
        } catch (RpcException rex) {
            if (failure) {
                logger.error("Error occurred in remote call!", rex);
            } else {
                return this.createErrorResultForProvider(rex, true);
            }
        } catch (Throwable rex) {
            if (failure) {
                logger.error("Error occurred in remote call!", rex);
            } else {
                return this.createErrorResultForProvider(rex, true);
            }
        }
    }

}

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() {
    ////ww  w.j av  a2s.  co m
    //                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    //                    return null;
    //                }
    //                
    //            });
    return proxy;
}

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

public EdmStreamValue newEdmStreamValue(final String contentType, final InputStream stream) {

    return EdmStreamValue.class.cast(Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
            new Class<?>[] { EdmStreamValue.class },
            new EdmStreamValueHandler(contentType, stream, null, getService())));
}

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

/**
 * Creates a new proxy from the specified interface.
 * @param api the interface/*from w  w w .  ja va2 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:org.jasig.cas.ticket.registry.support.JpaLockingStrategyTests.java

private LockingStrategy newLockTxProxy(final String appId, final String uniqueId, final int ttl) {
    final JpaLockingStrategy lock = new JpaLockingStrategy();
    lock.entityManager = SharedEntityManagerCreator.createSharedEntityManager(factory);
    lock.setApplicationId(appId);/* www .  j a  v  a 2  s .c om*/
    lock.setUniqueId(uniqueId);
    lock.setLockTimeout(ttl);
    return (LockingStrategy) Proxy.newProxyInstance(JpaLockingStrategy.class.getClassLoader(),
            new Class[] { LockingStrategy.class }, new TransactionalLockInvocationHandler(lock));
}

From source file:com.qmetry.qaf.automation.ui.webdriver.ElementFactory.java

@SuppressWarnings("unchecked")
private Object initList(Field field, String loc, SearchContext context, Object clsObject) throws Exception {
    loc = ConfigurationManager.getBundle().getString(loc, loc);
    Class<? extends QAFExtendedWebElement> cls = (Class<? extends QAFExtendedWebElement>) getListType(field);
    InvocationHandler iHandler = QAFWebComponent.class.isAssignableFrom(cls)
            ? new ComponentListHandler(context, loc, cls, clsObject)
            : new ComponentListHandler(context, loc, QAFExtendedWebElement.class, clsObject);
    return Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] { List.class }, iHandler);
}

From source file:io.codis.nedis.util.NedisUtils.java

/**
 * Return a {@link NedisClient} which does acquire-execute-release automatically. You do not
 * need to call release when using the returned {@link NedisClient}.
 *//*from  w  ww.j  a  v a2  s .  com*/
public static NedisClient newPooledClient(NedisClientPool pool) {
    return (NedisClient) Proxy.newProxyInstance(NedisClient.class.getClassLoader(),
            new Class<?>[] { NedisClient.class }, new Invoker(pool));
}

From source file:com.lambdaworks.redis.support.ConnectionPoolSupport.java

@SuppressWarnings("unchecked")
private static <T> T wrapConnection(T connection, ObjectPool<T> pool) {

    ReturnObjectOnCloseInvocationHandler<T> handler = new ReturnObjectOnCloseInvocationHandler<>(connection,
            pool);/*  w ww.  j a v a 2  s. co  m*/

    Class<?>[] implementedInterfaces = connection.getClass().getInterfaces();
    Class[] interfaces = new Class[implementedInterfaces.length + 1];
    interfaces[0] = HasTargetConnection.class;
    System.arraycopy(implementedInterfaces, 0, interfaces, 1, implementedInterfaces.length);

    T proxiedConnection = (T) Proxy.newProxyInstance(connection.getClass().getClassLoader(), interfaces,
            handler);
    handler.setProxiedConnection(proxiedConnection);

    return proxiedConnection;
}

From source file:org.eclipse.vjet.dsf.common.utils.DataModelHelper.java

/**
 * @param  modelInterface  the interface class
 * @param  model  the data model object. Its class implemets the modelInterface
 * @return a proxy object for model object. when v4 app invoks its method, the returned
 *         object will be traced.//from w ww.j av a  2 s.  c  om
 * 
 * sample v4 application:
 * public interface IFooModel {
 *    ...
 * }
 * 
 * public classs FooModelImpl implements IFooModel {
 * }
 * 
 * void bar() {
 *    FooModelImpl model = new FooModelImpl();  
 *    IFooModel proxy = TraceHelper.getInstance().getProxy(IFooModel.class, model);
 *    .....
 * }
 * 
 */
public <T> T getProxy(final Class<T> modelInterface, final Object model) {
    ClassLoader classLoader = model.getClass().getClassLoader();
    Class[] interfaces = new Class[] { modelInterface };

    InvocationHandler handler = new JavaBeanInvocationHandler(model);

    Object proxy = Proxy.newProxyInstance(classLoader, interfaces, handler);
    return (T) proxy;
}