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.bytesoft.bytetcc.supports.dubbo.CompensableDubboServiceFilter.java

public Result providerInvoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    RemoteCoordinatorRegistry remoteCoordinatorRegistry = RemoteCoordinatorRegistry.getInstance();
    CompensableBeanRegistry beanRegistry = CompensableBeanRegistry.getInstance();
    CompensableBeanFactory beanFactory = beanRegistry.getBeanFactory();
    RemoteCoordinator consumeCoordinator = beanRegistry.getConsumeCoordinator();
    TransactionInterceptor transactionInterceptor = beanFactory.getTransactionInterceptor();
    CompensableManager transactionManager = beanFactory.getCompensableManager();

    URL targetUrl = invoker.getUrl();
    String targetAddr = targetUrl.getIp();
    int targetPort = targetUrl.getPort();
    String address = String.format("%s:%s", targetAddr, targetPort);
    InvocationContext invocationContext = new InvocationContext();
    invocationContext.setServerHost(targetAddr);
    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);/* w  ww  .  j  a  va2  s  .com*/
        remoteCoordinatorRegistry.putTransactionManagerStub(address, remoteCoordinator);
    }

    Result result = null;

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

    TransactionResponseImpl response = new TransactionResponseImpl();
    response.setSourceTransactionCoordinator(remoteCoordinator);
    try {
        // String transactionContextContent = RpcContext.getContext()
        // .getAttachment(TransactionContext.class.getName());
        String transactionContextContent = invocation.getAttachment(TransactionContext.class.getName());
        if (StringUtils.isNotBlank(transactionContextContent)) {
            byte[] requestByteArray = ByteUtils.stringToByteArray(transactionContextContent);
            ByteArrayInputStream bais = new ByteArrayInputStream(requestByteArray);
            HessianInput input = new HessianInput(bais);
            TransactionContext remoteTransactionContext = (TransactionContext) input.readObject();
            request.setTransactionContext(remoteTransactionContext);
        }
        transactionInterceptor.afterReceiveRequest(request);

        result = invoker.invoke(invocation);

        Transaction transaction = transactionManager.getCompensableTransactionQuietly();
        TransactionContext nativeTransactionContext = transaction == null ? null
                : transaction.getTransactionContext();

        response.setTransactionContext(nativeTransactionContext);

        transactionInterceptor.beforeSendResponse(response);
        if (StringUtils.isNotBlank(transactionContextContent)) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            HessianOutput output = new HessianOutput(baos);
            output.writeObject(nativeTransactionContext);
            String nativeTansactionContextContent = ByteUtils.byteArrayToString(baos.toByteArray());
            // RpcContext.getContext().setAttachment(TransactionContext.class.getName(),
            // nativeTansactionContextContent);
            invocation.getAttachments().put(TransactionContext.class.getName(), nativeTansactionContextContent);
        }
    } catch (IOException ex) {
        // TODO
        ex.printStackTrace();
    } catch (RpcException rex) {
        // TODO
        rex.printStackTrace();
    } catch (RuntimeException rex) {
        // TODO
        rex.printStackTrace();
    }
    return result;
}

From source file:com.github.yongchristophertang.engine.web.request.TestRequestBuilders.java

/**
 * Create a {@code T} instance which is a proxy for the interface {@code clientIface}. Typically methods in
 * {@code clientIface} will return a {@link com.github.yongchristophertang.engine.web.request.RequestBuilder} or, more
 * concrete, {@link HttpRequestBuilders}.
 *
 * @param clientIface the API method definition interface
 * @param <T>         Inteface class
 * @return {@code T} instance// w  w w  .  j  a  v  a  2  s.  co m
 */
@SuppressWarnings("unchecked")
public static <T> T api(Class<T> clientIface) throws Exception {
    return (T) Proxy.newProxyInstance(TestRequestBuilders.class.getClassLoader(),
            new Class<?>[] { clientIface }, RequestProxy.getInstance());
}

From source file:com.mirth.connect.connectors.jms.xa.ConnectionFactoryWrapper.java

public QueueConnection createQueueConnection(String username, String password) throws JMSException {
    XAQueueConnection xaqc = ((XAQueueConnectionFactory) factory).createXAQueueConnection(username, password);
    QueueConnection proxy = (QueueConnection) Proxy.newProxyInstance(Connection.class.getClassLoader(),
            new Class[] { QueueConnection.class }, new ConnectionInvocationHandler(xaqc));
    return proxy;
}

From source file:org.apache.cocoon.servletservice.DispatcherServlet.java

protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    final Map mountableServlets = getBlockServletMap();
    String path = req.getPathInfo();
    if (path == null) {
        path = "";
    }/*from   w  w  w .  ja  v  a  2s  .c o m*/

    // find the servlet which mount path is the longest prefix of the path info
    int index = path.length();
    Servlet servlet = null;
    while (servlet == null && index != -1) {
        path = path.substring(0, index);
        servlet = (Servlet) mountableServlets.get(path);
        index = path.lastIndexOf('/');
    }
    //case when servlet is mounted at "/" must be handled separately
    servlet = servlet == null ? (Servlet) mountableServlets.get("/") : servlet;
    if (servlet == null) {
        String message = "No block for " + req.getPathInfo();
        res.sendError(HttpServletResponse.SC_NOT_FOUND, message);
        this.logger.info(message);
        return;
    }

    // Create a dynamic proxy class that overwrites the getServletPath and
    // getPathInfo methods to provide reasonable values in the called servlet
    // the dynamic proxy implements all interfaces of the original request
    HttpServletRequest request = (HttpServletRequest) Proxy.newProxyInstance(req.getClass().getClassLoader(),
            getInterfaces(req.getClass()), new DynamicProxyRequestHandler(req, path));

    if (this.logger.isDebugEnabled()) {
        this.logger.debug("DispatcherServlet: service servlet=" + servlet + " mountPath=" + path
                + " servletPath=" + request.getServletPath() + " pathInfo=" + request.getPathInfo());
    }

    servlet.service(request, res);
}

From source file:org.bytesoft.bytetcc.supports.dubbo.spi.CompensableServiceFilter.java

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

    URL targetUrl = invoker.getUrl();
    String targetAddr = targetUrl.getIp();
    int targetPort = targetUrl.getPort();
    String address = String.format("%s:%s", targetAddr, targetPort);
    InvocationContext invocationContext = new InvocationContext();
    invocationContext.setServerHost(targetAddr);
    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  w  w w . j a  va2 s. c o  m*/
        remoteCoordinatorRegistry.putTransactionManagerStub(address, remoteCoordinator);
    }

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

    TransactionResponseImpl response = new TransactionResponseImpl();
    response.setSourceTransactionCoordinator(remoteCoordinator);
    try {
        this.beforeProviderInvoke(invocation, request, response);
        return invoker.invoke(invocation);
    } catch (RemotingException rex) {
        throw rex;
    } catch (RuntimeException rex) {
        logger.error("Error occurred in remote call!", rex);
        throw new RemotingException(rex.getMessage());
    } finally {
        this.afterProviderInvoke(invocation, request, response);
    }

}

From source file:com.intelligentsia.dowsers.entity.serializer.EntityMapper.java

/**
 * Method that can be used to parse JSON to specified Java value, using
 * reader provided./*from  w w w  .ja v  a  2 s .co m*/
 * 
 * @param reader
 * @param valueType
 * @return
 * @throws DowsersException
 */
@SuppressWarnings("unchecked")
public <T> T readValue(final Reader reader, final Class<T> valueType) throws DowsersException {
    if (valueType.isInterface() || Modifier.isAbstract(valueType.getModifiers())) {
        try {
            final EntityProxy entityProxy = mapper.readValue(reader, EntityProxy.class);
            return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                    new Class[] { valueType, EntityProxyHandler.class }, entityProxy);
        } catch (final Throwable e) {
            throw new DowsersException(e);
        }
    }
    try {
        return mapper.readValue(reader, valueType);
    } catch (final Throwable e) {
        throw new DowsersException(e);
    }
}

From source file:com.github.hrpc.rpc.ProtobufRpcEngine.java

@Override
public ProtocolProxy<ProtocolMetaInfoPB> getProtocolMetaInfoProxy(ConnectionId connId, Option conf,
        SocketFactory factory) throws IOException {
    Class<ProtocolMetaInfoPB> protocol = ProtocolMetaInfoPB.class;
    return new ProtocolProxy<ProtocolMetaInfoPB>(protocol,
            (ProtocolMetaInfoPB) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol },
                    new Invoker(protocol, connId, conf, factory)));
}

From source file:org.bytesoft.bytetcc.supports.serialize.XAResourceDeserializerImpl.java

public XAResource deserialize(String identifier) {
    try {// ww w  .jav  a 2 s  .c  o m
        Object bean = this.applicationContext.getBean(identifier);
        XAResource cachedResource = this.cachedResourceMap.get(identifier);
        if (cachedResource == null) {
            cachedResource = this.deserializeResource(identifier, bean);
            if (cachedResource != null) {
                this.cachedResourceMap.put(identifier, cachedResource);
            }
        }
        return cachedResource;
    } catch (BeansException bex) {
        Matcher matcher = pattern.matcher(identifier);
        if (matcher.find()) {
            RemoteCoordinatorRegistry registry = RemoteCoordinatorRegistry.getInstance();
            RemoteCoordinator coordinator = registry.getTransactionManagerStub(identifier);
            if (coordinator == null) {
                String[] array = identifier.split("\\:");
                InvocationContext invocationContext = new InvocationContext();
                invocationContext.setServerHost(array[0]);
                invocationContext.setServerPort(Integer.valueOf(array[1]));

                CompensableBeanRegistry beanRegistry = CompensableBeanRegistry.getInstance();
                RemoteCoordinator consumeCoordinator = beanRegistry.getConsumeCoordinator();

                DubboRemoteCoordinator dubboCoordinator = new DubboRemoteCoordinator();
                dubboCoordinator.setInvocationContext(invocationContext);
                dubboCoordinator.setRemoteCoordinator(consumeCoordinator);

                coordinator = (RemoteCoordinator) Proxy.newProxyInstance(
                        DubboRemoteCoordinator.class.getClassLoader(), new Class[] { RemoteCoordinator.class },
                        dubboCoordinator);
                registry.putTransactionManagerStub(identifier, coordinator);
            }

            return registry.getTransactionManagerStub(identifier);
        } else {
            logger.error("can not find a matching xa-resource(identifier= {})!", identifier);
            return null;
        }
    } catch (Exception ex) {
        logger.error("can not find a matching xa-resource(identifier= {})!", identifier);
        return null;
    }

}

From source file:org.bytesoft.bytejta.supports.serialize.XAResourceDeserializerImpl.java

public XAResource deserialize(String identifier) {
    try {// w  w w.ja  v  a 2  s . c om
        Object bean = this.applicationContext.getBean(identifier);
        XAResource cachedResource = this.cachedResourceMap.get(identifier);
        if (cachedResource == null) {
            cachedResource = this.deserializeResource(identifier, bean);
            if (cachedResource != null) {
                this.cachedResourceMap.put(identifier, cachedResource);
            }
        }
        return cachedResource;
    } catch (BeansException bex) {
        Matcher matcher = pattern.matcher(identifier);
        if (matcher.find()) {
            RemoteCoordinatorRegistry registry = RemoteCoordinatorRegistry.getInstance();
            RemoteCoordinator coordinator = registry.getTransactionManagerStub(identifier);
            if (coordinator == null) {
                String[] array = identifier.split("\\:");
                InvocationContext invocationContext = new InvocationContext();
                invocationContext.setServerHost(array[0]);
                invocationContext.setServerPort(Integer.valueOf(array[1]));

                TransactionBeanRegistry beanRegistry = TransactionBeanRegistry.getInstance();
                RemoteCoordinator consumeCoordinator = beanRegistry.getConsumeCoordinator();

                DubboRemoteCoordinator dubboCoordinator = new DubboRemoteCoordinator();
                dubboCoordinator.setInvocationContext(invocationContext);
                dubboCoordinator.setRemoteCoordinator(consumeCoordinator);

                coordinator = (RemoteCoordinator) Proxy.newProxyInstance(
                        DubboRemoteCoordinator.class.getClassLoader(), new Class[] { RemoteCoordinator.class },
                        dubboCoordinator);
                registry.putTransactionManagerStub(identifier, coordinator);
            }

            return registry.getTransactionManagerStub(identifier);
        } else {
            logger.error("can not find a matching xa-resource(identifier= {})!", identifier);
            return null;
        }
    } catch (Exception ex) {
        logger.error("can not find a matching xa-resource(identifier= {})!", identifier);
        return null;
    }

}

From source file:com.jaliansystems.activeMQLite.impl.ObjectRepository.java

/**
 * Lookup a handle/*from ww  w .ja  v a2  s  . c  o m*/
 * 
 * Looks up a handle in the local repository. If it does not exist in the
 * local repository (it is a remote handle), creates a remote proxy to
 * handle the method invocations on the object.
 * 
 * @param handle
 *            the object handle to be looked up
 * @param client
 *            the repository client
 * @return the object
 * @throws Exception
 *             the exception
 */
public Object lookupHandle(ObjectHandle handle, RepositoryClient client) throws Exception {
    if (list.contains(handle)) {
        int index = list.indexOf(handle);
        return list.get(index).getObject();
    }
    RemoteInvocationHandler handler = new RemoteInvocationHandler(handle, client);
    return Proxy.newProxyInstance(handle.getIFace().getClassLoader(),
            new Class[] { handle.getIFace(), IProxy.class }, handler);
}