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.olingo.ext.proxy.commons.PrimitiveCollectionInvocationHandler.java

@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
    if ("filter".equals(method.getName()) || "top".equals(method.getName()) || "skip".equals(method.getName())
            || "execute".equals(method.getName()) || "executeAsync".equals(method.getName())) {

        invokeSelfMethod(method, args);//from  www.jav  a 2 s.com
        return proxy;
    } else if (isSelfMethod(method)) {
        return invokeSelfMethod(method, args);
    } else if ("operations".equals(method.getName()) && ArrayUtils.isEmpty(args)) {
        final Class<?> returnType = method.getReturnType();

        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class<?>[] { returnType }, OperationInvocationHandler.getInstance(this));
    } else {
        throw new NoSuchMethodException(method.getName());
    }
}

From source file:com.miranteinfo.seam.core.Init.java

@Observer("org.jboss.seam.postInitialization")
public void configure() throws Exception {

    boolean sessionFactoryConfigured = false;
    Object component = null;/*from  w  w  w .  j  a v  a 2  s .c o m*/

    for (String name : Contexts.getApplicationContext().getNames()) {
        component = Contexts.getApplicationContext().get(name);

        if (component instanceof EntityManagerFactory) {

            javax.persistence.EntityManagerFactory emf = ((EntityManagerFactory) component)
                    .getEntityManagerFactory();
            Field field = emf.getClass().getDeclaredField("sessionFactory");
            field.setAccessible(true);
            Object sf = field.get(emf);
            field.set(emf, Proxy.newProxyInstance(Init.class.getClassLoader(), sf.getClass().getInterfaces(),
                    new SessionFactoryProxy((SessionFactory) sf)));
            configure((SessionFactoryImpl) sf);
            sessionFactoryConfigured = true;

        } else if (component instanceof HibernateSessionFactory) {

            HibernateSessionFactory hsf = (HibernateSessionFactory) component;
            Field field = HibernateSessionFactory.class.getDeclaredField("sessionFactory");
            field.setAccessible(true);
            SessionFactory sf = hsf.getSessionFactory();
            field.set(hsf, Proxy.newProxyInstance(Init.class.getClassLoader(), sf.getClass().getInterfaces(),
                    new SessionFactoryProxy(sf)));
            configure((SessionFactoryImpl) sf);
            sessionFactoryConfigured = true;

        }

    }

    if (!sessionFactoryConfigured) {
        log.warn("No SessionFactory is configured...");
    }

}

From source file:cat.albirar.framework.proxy.ProxyFactory.java

/**
 * Create a proxy for the indicated type.
 * @param handler The handler//from w w w  .  ja  va2 s  .  c om
 * @param type The type, should to be a interface type
 * @return The proxy
 */
@SuppressWarnings("unchecked")
private <T> T newProxyForInterface(java.lang.reflect.InvocationHandler handler, Class<T> type) {
    Assert.isTrue(type.isInterface(), "The type should to be an interface");
    return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class[] { type }, handler);
}

From source file:org.apache.ftpserver.FtpLogFactory.java

/**
 * Create a proxy log object to redirect log message.
 *///www. ja  v a2 s  .  c om
private Log createProxyLog(final Log original) {
    InvocationHandler handler = new InvocationHandler() {
        public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
            Object retVal = m.invoke(original, args);
            for (int i = m_logs.size(); --i >= 0;) {
                Log log = (Log) m_logs.get(i);
                m.invoke(log, args);
            }
            return retVal;
        }
    };

    return (Log) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { Log.class }, handler);
}

From source file:org.eclipse.wb.internal.rcp.model.rcp.EditorPartInfo.java

private void setEditorSite() throws Exception {
    ClassLoader editorLoader = JavaInfoUtils.getClassLoader(this);
    Class<?> editorSiteClass = editorLoader.loadClass("org.eclipse.ui.IEditorSite");
    Class<?> editorInputClass = editorLoader.loadClass("org.eclipse.ui.IEditorInput");
    // create IEditorSite
    Object editorSite = Proxy.newProxyInstance(editorLoader, new Class<?>[] { editorSiteClass },
            new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    String signature = ReflectionUtils.getMethodSignature(method);
                    if (signature.equals("toString()")) {
                        return "IEditorSite_stub";
                    }//from   w  w w .ja  v a2 s  .c om
                    if (signature.equals("hashCode()")) {
                        return 0;
                    }
                    if (signature.equals("getId()")) {
                        return getID();
                    }
                    if (signature.equals("getWorkbenchWindow()")) {
                        return DesignerPlugin.getActiveWorkbenchWindow();
                    }
                    // IServiceLocator
                    if (signature.equals("hasService(java.lang.Class)")) {
                        IServiceLocator serviceLocator = DesignerPlugin.getActiveWorkbenchWindow();
                        return serviceLocator.hasService((Class<?>) args[0]);
                    }
                    if (signature.equals("getService(java.lang.Class)")) {
                        IServiceLocator serviceLocator = DesignerPlugin.getActiveWorkbenchWindow();
                        return serviceLocator.getService((Class<?>) args[0]);
                    }
                    // not implemented
                    throw new NotImplementedException(method.toString());
                }
            });
    // create org.eclipse.ui.IEditorInput
    Object editorInput = Proxy.newProxyInstance(editorLoader, new Class<?>[] { editorInputClass },
            new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    Class<?> returnType = method.getReturnType();
                    return ReflectionUtils.getDefaultValue(returnType);
                }
            });
    // call init(IEditorSite,IEditorInput)
    ReflectionUtils.invokeMethod(getObject(), "init(org.eclipse.ui.IEditorSite,org.eclipse.ui.IEditorInput)",
            editorSite, editorInput);
}

From source file:org.apache.jena.security.impl.ItemHolder.java

/**
 * Creates the proxy, saves it as the securedItem and returns it.
 * /* w ww  .jav a  2s  .c o  m*/
 * @param handler
 *            The SecuredItemInvoker to create the proxy with.
 * @return The proxy.
 */
@SuppressWarnings("unchecked")
public final Secured setSecuredItem(final SecuredItemInvoker handler) {
    final Set<Class<?>> ifac = new LinkedHashSet<Class<?>>();
    if (baseItem.getClass().isInterface()) {
        ifac.add(baseItem.getClass());
    }
    ifac.addAll(ClassUtils.getAllInterfaces(baseItem.getClass()));
    if (handler.securedItem.getClass().isInterface()) {
        ifac.add(handler.securedItem.getClass());
    }
    ifac.addAll(ClassUtils.getAllInterfaces(handler.securedItem.getClass()));

    securedItem = (Secured) Proxy.newProxyInstance(SecuredItemImpl.class.getClassLoader(),
            ifac.toArray(new Class<?>[ifac.size()]), handler);
    return securedItem;
}

From source file:com.lambdaworks.redis.RedisConnectionPool.java

private PooledObjectFactory<T> createFactory(final RedisConnectionProvider<T> redisConnectionProvider) {
    return new BasePooledObjectFactory<T>() {

        @SuppressWarnings("unchecked")
        @Override// www.java  2 s  .c o  m
        public T create() throws Exception {

            T connection = redisConnectionProvider.createConnection();
            PooledConnectionInvocationHandler<T> h = new PooledConnectionInvocationHandler<>(connection,
                    RedisConnectionPool.this);

            Object proxy = Proxy.newProxyInstance(getClass().getClassLoader(),
                    new Class<?>[] { redisConnectionProvider.getComponentType() }, h);

            return (T) proxy;
        }

        @Override
        public PooledObject<T> wrap(T obj) {
            return new DefaultPooledObject<>(obj);
        }

        @Override
        public boolean validateObject(PooledObject<T> p) {
            return Connections.isOpen(p.getObject());
        }

        @Override
        @SuppressWarnings("unchecked")
        public void destroyObject(PooledObject<T> p) throws Exception {

            T object = p.getObject();
            if (Proxy.isProxyClass(object.getClass())) {
                PooledConnectionInvocationHandler<T> invocationHandler = (PooledConnectionInvocationHandler<T>) Proxy
                        .getInvocationHandler(object);

                object = invocationHandler.getConnection();
            }

            Connections.close(object);
        }
    };
}

From source file:org.apache.jena.permissions.impl.ItemHolder.java

/**
 * Creates the proxy, saves it as the securedItem and returns it.
 * //  ww w . j av  a2s. c o m
 * @param handler
 *            The SecuredItemInvoker to create the proxy with.
 * @return The proxy.
 */
@SuppressWarnings("unchecked")
public final Secured setSecuredItem(final SecuredItemInvoker handler) {
    final Set<Class<?>> ifac = new LinkedHashSet<>();
    if (baseItem.getClass().isInterface()) {
        ifac.add(baseItem.getClass());
    }
    ifac.addAll(ClassUtils.getAllInterfaces(baseItem.getClass()));
    if (handler.securedItem.getClass().isInterface()) {
        ifac.add(handler.securedItem.getClass());
    }
    ifac.addAll(ClassUtils.getAllInterfaces(handler.securedItem.getClass()));

    securedItem = (Secured) Proxy.newProxyInstance(SecuredItemImpl.class.getClassLoader(),
            ifac.toArray(new Class<?>[ifac.size()]), handler);
    return securedItem;
}

From source file:com.moss.jaxwslite.Service.java

public Service(HttpClient client, String url, ServiceType type) {

    if (url.endsWith("?wsdl")) {

        this.url = url.substring(0, url.length() - 5);

        if (log.isDebugEnabled()) {
            log.debug("Excluding ?wsdl parameter from url: " + url + " -> " + this.url);
        }//from   w  ww.  j a v a 2s  .co  m
    } else {
        this.url = url;
    }

    this.client = client;
    this.type = type;

    ClassLoader cl = this.getClass().getClassLoader();
    Class[] interfaces = new Class[] { type.iface() };
    proxy = Proxy.newProxyInstance(cl, interfaces, this);
}