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.codehaus.grepo.query.jpa.repository.DefaultJpaRepository.java

/**
 * Create a close-suppressing proxy for the given JPA EntityManager.
 *
 * @param em The JPA EntityManager to create a proxy for.
 * @return The EntityManager proxy, implementing all interfaces implemented by the passed-in EntityManager object
 *         (that is, also implementing all provider-specific extension interfaces).
 */// ww  w .j  a  v a2s.co  m
protected EntityManager createEntityManagerProxy(EntityManager em) {
    Class<?>[] ifcs = null;
    EntityManagerFactory emf = getEntityManagerFactory();
    if (emf instanceof EntityManagerFactoryInfo) {
        Class<?> entityManagerInterface = ((EntityManagerFactoryInfo) emf).getEntityManagerInterface();
        if (entityManagerInterface != null) {
            ifcs = new Class[] { entityManagerInterface };
        }
    }
    if (ifcs == null) {
        ifcs = ClassUtils.getAllInterfacesForClass(em.getClass());
    }
    return (EntityManager) Proxy.newProxyInstance(em.getClass().getClassLoader(), ifcs,
            new CloseSuppressingInvocationHandler(em));
}

From source file:org.codehaus.grepo.query.hibernate.repository.DefaultHibernateRepository.java

/**
 * Create a close-suppressing proxy for the given Hibernate Session.
 *
 * @param session The Hibernate Session to create a proxy for.
 * @return The Session proxy//from   www  .  j  a v a2s  .c o m
 */
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:gov.nih.nci.firebird.proxy.PoolingHandlerTest.java

@Test
public void testExpectedSuperExceptionHandeling() throws Exception {
    PoolableObjectFactory<Object> factory = makeMockFactory();
    ObjectPool<Object> pool = spy(new StackObjectPool<Object>(factory));
    PoolingHandler handler = new PoolingHandler(pool);
    handler.getValidExceptions().add(RuntimeException.class);
    assertTrue(new IllegalArgumentException() instanceof RuntimeException);
    ITestClient proxy = (ITestClient) Proxy.newProxyInstance(this.getClass().getClassLoader(),
            new Class<?>[] { ITestClient.class }, handler);
    try {// w  w  w  .  j  a  v  a  2  s .  c o m
        proxy.doSomethingBad(0);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    verify(pool, times(1)).borrowObject();
    verify(pool, times(1)).returnObject(any());
    verify(factory, times(0)).destroyObject(any());
}

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

@SuppressWarnings("unchecked")
public <S extends T, SEC extends EntityCollection<S, ?, ?>> SEC fetchWholeEntitySet(final URIBuilder uriBuilder,
        final Class<S> typeRef, final Class<SEC> collTypeRef) {

    final List<S> res = new ArrayList<S>();
    final List<ClientAnnotation> anns = new ArrayList<ClientAnnotation>();

    URI nextURI = uriBuilder.build();
    while (nextURI != null) {
        final Triple<List<T>, URI, List<ClientAnnotation>> entitySet = fetchPartial(nextURI,
                (Class<T>) typeRef);
        res.addAll((List<S>) entitySet.getLeft());
        nextURI = entitySet.getMiddle();
        anns.addAll(entitySet.getRight());
    }/*ww w  . j a va 2 s .  c o  m*/

    final EntityCollectionInvocationHandler<S> entityCollectionHandler = new EntityCollectionInvocationHandler<S>(
            service, res, collTypeRef, targetEntitySetURI, uriBuilder);
    entityCollectionHandler.setAnnotations(anns);

    return (SEC) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
            new Class<?>[] { collTypeRef }, entityCollectionHandler);
}

From source file:org.apache.hadoop.metrics2.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   www.j a va2  s. c  om
                    return null;
                }
            }));
}

From source file:org.apache.cocoon.core.container.spring.avalon.PoolableFactoryBean.java

/**
 * @see org.springframework.beans.factory.FactoryBean#getObject()
 *//*from   www.j a va 2s.c  o  m*/
public Object getObject() throws Exception {
    return Proxy.newProxyInstance(this.getClass().getClassLoader(), this.interfaces,
            new PoolableProxyHandler(this));
}

From source file:org.apache.hadoop.hbase.fs.HFileSystem.java

private static ClientProtocol createReorderingProxy(final ClientProtocol cp, final ReorderBlocks lrb,
        final Configuration conf) {
    return (ClientProtocol) Proxy.newProxyInstance(cp.getClass().getClassLoader(),
            new Class[] { ClientProtocol.class, Closeable.class }, new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    try {
                        if ((args == null || args.length == 0) && "close".equals(method.getName())) {
                            RPC.stopProxy(cp);
                            return null;
                        } else {
                            Object res = method.invoke(cp, args);
                            if (res != null && args != null && args.length == 3
                                    && "getBlockLocations".equals(method.getName())
                                    && res instanceof LocatedBlocks && args[0] instanceof String
                                    && args[0] != null) {
                                lrb.reorderBlocks(conf, (LocatedBlocks) res, (String) args[0]);
                            }/*from   w  w w.  ja v a 2 s.c o m*/
                            return res;
                        }
                    } catch (InvocationTargetException ite) {
                        // We will have this for all the exception, checked on not, sent
                        //  by any layer, including the functional exception
                        Throwable cause = ite.getCause();
                        if (cause == null) {
                            throw new RuntimeException("Proxy invocation failed and getCause is null", ite);
                        }
                        if (cause instanceof UndeclaredThrowableException) {
                            Throwable causeCause = cause.getCause();
                            if (causeCause == null) {
                                throw new RuntimeException("UndeclaredThrowableException had null cause!");
                            }
                            cause = cause.getCause();
                        }
                        throw cause;
                    }
                }
            });
}

From source file:fr.xebia.management.ServletContextAwareMBeanServerFactory.java

public MBeanServer getObject() throws Exception {
    if (instance == null) {
        InvocationHandler invocationHandler = new InvocationHandler() {
            /**// ww  w . ja v  a  2s.co  m
             * <p>
             * Copy the given <code>objectName</code> adding the extra
             * attributes.
             * </p>
             */
            protected ObjectName addExtraAttributesToObjectName(ObjectName objectName)
                    throws MalformedObjectNameException {
                Hashtable<String, String> table = new Hashtable<String, String>(
                        objectName.getKeyPropertyList());
                table.putAll(objectNameExtraAttributes);

                ObjectName result = ObjectName.getInstance(objectName.getDomain(), table);
                logger.trace("addExtraAttributesToObjectName({}): {}", objectName, result);

                return result;
            }

            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object[] modifiedArgs = args.clone();
                for (int i = 0; i < modifiedArgs.length; i++) {
                    Object arg = modifiedArgs[i];
                    if (arg instanceof ObjectName) {
                        ObjectName objectName = (ObjectName) arg;
                        modifiedArgs[i] = addExtraAttributesToObjectName(objectName);
                    }
                }
                if (logger.isDebugEnabled()) {
                    logger.debug(method + " : " + Arrays.asList(modifiedArgs));
                }
                try {
                    return method.invoke(server, modifiedArgs);
                } catch (InvocationTargetException ite) {
                    throw ite.getCause();
                }
            }
        };
        instance = (MBeanServer) Proxy.newProxyInstance(ClassUtils.getDefaultClassLoader(),
                new Class[] { MBeanServer.class }, invocationHandler);

    }
    return instance;
}

From source file:com.gs.jrpip.client.FastServletProxyFactory.java

/**
 * Creates a new proxy with the specified URL.  The returned object
 * is a proxy with the interface specified by api.
 * <p/>//from ww  w .  j a va2s .  c  om
 * <pre>
 * String url = "http://localhost:7001/objectmanager/JrpipServlet");
 * RemoteObjectManager rom = (RemoteObjectManager) factory.create(RemoteObjectManager.class, url);
 * </pre>
 *
 * @param api           the interface the proxy class needs to implement
 * @param url           the URL where the client object is located.
 * @param timeoutMillis maximum timeoutMillis for remote method call to run, zero for no timeoutMillis
 * @return a proxy to the object with the specified interface.
 */
public <T> T create(Class<T> api, String url, int timeoutMillis, boolean disconnectedMode)
        throws MalformedURLException {
    T result = null;
    if (this.useLocalService) {
        result = JrpipServiceRegistry.getInstance().getLocalService(url, api);
    }
    if (result == null) {
        AuthenticatedUrl authenticatedUrl = new AuthenticatedUrl(url, this.credentials,
                this.authenticationCookies);
        boolean supportsChunking = disconnectedMode || serverSupportsChunking(authenticatedUrl);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("chunking support at {} :{} received client id: {}", url, supportsChunking,
                    getProxyId(authenticatedUrl));
        }
        if (this.useLocalService) {
            result = JrpipServiceRegistry.getInstance().getLocalService(url, api);
        }
        if (result == null) {
            InvocationHandler handler = this.invocationHandlerFunction.getInvocationHandler(authenticatedUrl,
                    api, timeoutMillis);
            result = (T) Proxy.newProxyInstance(api.getClassLoader(), new Class[] { api }, handler);
        }
    }
    return result;
}

From source file:com.link_intersystems.lang.ContextAware.java

/**
 * Creates a java proxy that executes every call to the target object within
 * the context that this {@link ContextAware} defines (defined by
 * subclasses)./*from  w  ww  .  jav  a  2 s. c o m*/
 * 
 * @param targetObject
 *            the target object to create a proxy for.
 * @return a java proxy that executes every call to the target object's
 *         interfaces in this {@link ClassLoaderContextAware}.
 */
@SuppressWarnings("unchecked")
public <T> T createContextProxy(T targetObject) {
    Assert.notNull("targetObject", targetObject);

    Class<T> targetObjectClass = (Class<T>) targetObject.getClass();
    List<Class<?>> allInterfaces = ClassUtils.getAllInterfaces(targetObjectClass);
    if (allInterfaces.isEmpty()) {
        throw new IllegalArgumentException("Unable to create java proxy, because target object's "
                + targetObjectClass + " does not implement any interface.");
    }
    Class<?>[] allInterfacesAsArray = (Class<?>[]) allInterfaces.toArray(new Class<?>[allInterfaces.size()]);

    ClassLoader classLoader = targetObject.getClass().getClassLoader();
    ContextAwareInvocationHandler classLoaderContextInvocationHandler = new ContextAwareInvocationHandler(this,
            targetObject);

    T classLoaderContextAwareProxy = (T) Proxy.newProxyInstance(classLoader, allInterfacesAsArray,
            classLoaderContextInvocationHandler);

    return classLoaderContextAwareProxy;
}