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.ow2.proactive.scheduler.rest.SchedulerClient.java

/**
 * Creates an ISchedulerClient instance.
 *
 * @return an ISchedulerClient instance//www.  j a  v a 2s  .  c  om
 */
public static ISchedulerClient createInstance() {
    SchedulerClient client = new SchedulerClient();
    return (ISchedulerClient) Proxy.newProxyInstance(ISchedulerClient.class.getClassLoader(),
            new Class[] { ISchedulerClient.class }, new SessionHandler(client));
}

From source file:org.jboss.dashboard.database.NonPooledDataSource.java

protected Statement createStatementProxy(Statement stmt) throws SQLException {
    return (Statement) Proxy.newProxyInstance(stmt.getClass().getClassLoader(),
            getClassInterfaces(stmt.getClass()), new StatementInvocationHandler(stmt));
}

From source file:org.dhatim.util.ClassUtil.java

public static Object newProxyInstance(Class[] classes, InvocationHandler handler) {
    final ClassLoader threadClassLoader = Thread.currentThread().getContextClassLoader();

    if (threadClassLoader != null) {
        return Proxy.newProxyInstance(threadClassLoader, classes, handler);
    } else {//from   w  ww.  j  av a 2s. c o  m
        return Proxy.newProxyInstance(ClassUtil.class.getClassLoader(), classes, handler);
    }
}

From source file:org.zenoss.zep.dao.impl.EventSummaryDaoImpl.java

public EventSummaryDaoImpl(DataSource dataSource) throws MetaDataAccessException {
    this.dataSource = dataSource;
    this.template = (SimpleJdbcOperations) Proxy.newProxyInstance(SimpleJdbcOperations.class.getClassLoader(),
            new Class<?>[] { SimpleJdbcOperations.class }, new SimpleJdbcTemplateProxy(dataSource));
    this.insert = new SimpleJdbcInsert(dataSource).withTableName(TABLE_EVENT_SUMMARY);
}

From source file:org.bytesoft.bytetcc.supports.dubbo.CompensableDubboServiceFilter.java

public Result consumerInvoke(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();
    Transaction transaction = transactionManager.getCompensableTransactionQuietly();
    TransactionContext nativeTransactionContext = transaction == null ? null
            : transaction.getTransactionContext();

    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);/*  ww  w  .j a v  a2 s.  c  om*/
        remoteCoordinatorRegistry.putTransactionManagerStub(address, remoteCoordinator);
    }

    Result result = null;

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

    TransactionResponseImpl response = new TransactionResponseImpl();
    response.setSourceTransactionCoordinator(remoteCoordinator);
    try {
        transactionInterceptor.beforeSendRequest(request);
        if (request.getTransactionContext() != null) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            HessianOutput output = new HessianOutput(baos);
            output.writeObject(request.getTransactionContext());
            String transactionContextContent = ByteUtils.byteArrayToString(baos.toByteArray());
            // RpcContext.getContext().setAttachment(TransactionContext.class.getName(),
            // transactionContextContent);
            invocation.getAttachments().put(TransactionContext.class.getName(), transactionContextContent);
        }

        result = invoker.invoke(invocation);

        if (request.getTransactionContext() != null) {
            // String transactionContextContent = RpcContext.getContext()
            // .getAttachment(TransactionContext.class.getName());
            String transactionContextContent = invocation.getAttachment(TransactionContext.class.getName());
            byte[] byteArray = ByteUtils.stringToByteArray(transactionContextContent);
            ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
            HessianInput input = new HessianInput(bais);
            TransactionContext remoteTransactionContext = (TransactionContext) input.readObject();
            response.setTransactionContext(remoteTransactionContext);
        }
        transactionInterceptor.afterReceiveResponse(response);
    } catch (IOException ex) {
        // TODO
        ex.printStackTrace();
    } catch (RpcException rex) {
        // TODO
        rex.printStackTrace();
    } catch (RuntimeException rex) {
        // TODO
        rex.printStackTrace();
    }
    return result;
}

From source file:org.yestech.lib.hibernate.search.YesHibernateSearchTemplate.java

/**
 * Create a close-suppressing proxy for the given Hibernate Session.
 * The proxy also prepares returned Query and Criteria objects.
 * @param session the Hibernate Session to create a proxy for
 * @return the Session proxy//  w w  w .j  a v  a2  s.  com
 * @see org.hibernate.Session#close()
 */
protected Session createSessionProxy(Session session) {
    Class[] sessionIfcs = null;
    Class mainIfc = (session instanceof org.hibernate.classic.Session ? org.hibernate.classic.Session.class
            : Session.class);
    if (session instanceof EventSource) {
        sessionIfcs = new Class[] { mainIfc, EventSource.class };
    } else if (session instanceof SessionImplementor) {
        sessionIfcs = new Class[] { mainIfc, SessionImplementor.class };
    } else {
        sessionIfcs = new Class[] { mainIfc };
    }
    return (Session) Proxy.newProxyInstance(session.getClass().getClassLoader(), sessionIfcs,
            new CloseSuppressingInvocationHandler(session));
}

From source file:com.vmware.upgrade.factory.CompositeUpgradeDefinitionFactory.java

/**
 * {@inheritDoc}/* w w  w. jav  a  2 s . c  o  m*/
 *
 * @return {@code true} iff all delegate {@link UpgradeDefinitionFactory}s return {@code true}
 */
@Override
public boolean isUpgradeSupported(final UpgradeContext context) throws IOException {
    int indexCount = 0;

    for (final UpgradeDefinitionFactoryRef factoryRef : definitionFactoryRefs) {
        final VersionFilter versionFilter;
        if (ordered) {
            versionFilter = new VersionFilter.IndexBasedVersionFilter(indexCount);
            indexCount++;
        } else {
            versionFilter = new VersionFilter.KeyBasedVersionFilter(factoryRef.getName());
        }

        final UpgradeContext filteredUpgradeContext = (UpgradeContext) Proxy.newProxyInstance(
                UpgradeContext.class.getClassLoader(), new Class[] { UpgradeContext.class },
                new ProxyUpgradeContext(context, versionFilter));

        if (!factoryRef.getFactory().isUpgradeSupported(filteredUpgradeContext)) {
            return false;
        }
    }

    return true;
}

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

@SuppressWarnings("unchecked")
public List<QAFWebElement> getElements(By by) {

    List<QAFWebElement> proxy;
    proxy = (List<QAFWebElement>) Proxy.newProxyInstance(this.getClass().getClassLoader(),
            new Class[] { List.class }, new QAFExtendedWebElementListHandler(this, by));
    return proxy;
}

From source file:io.coala.enterprise.Fact.java

/**
 * @param subtype the type of {@link Fact} to mimic
 * @param callObserver an {@link Observer} of method call, or {@code null}
 * @return the {@link Proxy} instance/*from  w  ww . j a  va2 s. c  o  m*/
 */
@SuppressWarnings("unchecked")
static <F extends Fact> F proxyAs(final Fact impl, final Class<F> subtype,
        final Observer<Method> callObserver) {
    final F proxy = (F) Proxy.newProxyInstance(subtype.getClassLoader(), new Class<?>[] { subtype },
            (self, method, args) -> {
                try {
                    final Object result = method.isDefault() && Proxy.isProxyClass(self.getClass())
                            ? ReflectUtil.invokeDefaultMethod(self, method, args)
                            : method.invoke(impl, args);
                    if (callObserver != null)
                        callObserver.onNext(method);
                    return result;
                } catch (Throwable e) {
                    if (e instanceof IllegalArgumentException)
                        try {
                            return ReflectUtil.invokeAsBean(impl.properties(), subtype, method, args);
                        } catch (final Exception ignore) {
                            LogUtil.getLogger(Fact.class).warn("{}method call failed: {}",
                                    method.isDefault() ? "default " : "", method, ignore);
                        }
                    if (e instanceof InvocationTargetException)
                        e = e.getCause();
                    if (callObserver != null)
                        callObserver.onError(e);
                    throw e;
                }
            });
    return proxy;
}

From source file:org.jboss.dashboard.database.NonPooledDataSource.java

protected Statement createPreparedStatementProxy(PreparedStatement stmt, String sql) throws SQLException {
    return (Statement) Proxy.newProxyInstance(stmt.getClass().getClassLoader(),
            getClassInterfaces(stmt.getClass()), new PreparedStatementInvocationHandler(stmt, sql));
}