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:com.okidokiteam.gouken.kernel.CoreVault.java

/**
 * Dynamic proxy around a service that is being used from the outside.
 * Its usually being used to provide some kind of push functionality of the management agent.
 *
 * @return proxy for t. Will delegate to underlying osgi service registry upon each call.
 *///  w w  w . j  a  v  a 2 s .  co m
@SuppressWarnings("unchecked")
private PUSHTYPE createProxyService() {
    return (PUSHTYPE) Proxy.newProxyInstance(m_framework.getClass().getClassLoader(),
            new Class<?>[] { m_pushServiceType }, new ProtectedInvocationHandler(
                    new OSGiServicePushHandler(m_pushServiceType, m_framework.getBundleContext())));
}

From source file:com.brighttag.agathon.resources.ValidatingJacksonJsonProviderTest.java

/**
 * Necessary to "instantiate" an annotation, since mocking #annotationType() fails.
 * @see http://stackoverflow.com/questions/2786292
 *//*ww  w . ja  v a2 s.  co  m*/
private <T extends Annotation> Annotation createMockAnnotation(final Class<T> klass) {
    return (Annotation) Proxy.newProxyInstance(klass.getClassLoader(), new Class[] { Annotation.class },
            new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) {
                    return klass; // only getClass() or annotationType() should be called.
                }
            });
}

From source file:acromusashi.stream.component.rabbitmq.CachingConnectionFactory.java

private ChannelProxy getCachedChannelProxy(LinkedList<ChannelProxy> channelList, boolean transactional) {
    Channel targetChannel = createBareChannel(transactional);

    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Creating cached Rabbit Channel from " + targetChannel);
    }//from w  ww .ja v a 2s .  com
    getChannelListener().onCreate(targetChannel, transactional);
    Class<?>[] interfaces;
    if (this.publisherConfirms || this.publisherReturns) {
        interfaces = new Class[] { ChannelProxy.class, PublisherCallbackChannel.class };
    } else {
        interfaces = new Class[] { ChannelProxy.class };
    }
    return (ChannelProxy) Proxy.newProxyInstance(ChannelProxy.class.getClassLoader(), interfaces,
            new CachedChannelInvocationHandler(targetChannel, channelList, transactional));
}

From source file:gov.nih.nci.firebird.proxy.PoolingHandlerTest.java

@Test
public void testPoolUse() throws Exception {
    PoolableObjectFactory<Object> factory = makeMockFactory();
    ObjectPool<Object> pool = spy(new StackObjectPool<Object>(factory));
    InvocationHandler handler = new PoolingHandler(pool);
    ITestClient proxy = (ITestClient) Proxy.newProxyInstance(this.getClass().getClassLoader(),
            new Class<?>[] { ITestClient.class }, handler);
    proxy.doSomethingUseful(null);/*from  w ww . j  a va  2  s.co m*/
    verify(pool, times(1)).borrowObject();
    verify(pool, times(1)).returnObject(any());
}

From source file:com.amazonaws.hal.client.ConversionUtil.java

private static Object convertFromMap(Type type, Map value) {
    if (type instanceof Class && !Map.class.isAssignableFrom((Class) type)) {
        Class typeClass = (Class) type;

        return Proxy.newProxyInstance(typeClass.getClassLoader(), new Class<?>[] { typeClass },
                new MapBackedInvocationHandler(type, value));
    } else {/*  w  ww .j  a va2 s .  co  m*/
        return new ConvertingMap(getCollectionType(type, 1, Object.class), value);
    }
}

From source file:org.forgerock.openidm.servletregistration.impl.ServletRegistrationSingleton.java

/**
 * Registers a servlet filter configuration
 * @param config the filter configuration
 * @return the registered Filter//from   w w  w.j  av  a 2s . c  o m
 * @throws Exception
 */
private Filter registerFilterWithWebContainer(JsonValue config) throws Exception {
    // Get required info from config
    String filterClass = config.get(SERVLET_FILTER_CLASS).required().asString();
    logger.info("Using filter class: {}", filterClass);
    List<URL> urls = config.get(SERVLET_FILTER_CLASS_PATH_URLS)
            .asList(new Function<JsonValue, URL, JsonValueException>() {
                @Override
                public URL apply(JsonValue jsonValue) throws JsonValueException {
                    return jsonValue.asURL();
                }
            });
    logger.info("Added URLs { {} })) to filter classpath", StringUtils.join(urls, ", "));

    Map<String, Object> preInvokeReqAttributes = config.get(SERVLET_FILTER_PRE_INVOKE_ATTRIBUTES).asMap();

    // Servlet names this filter should apply to, e.g. one could also add "OpenIDM Web"
    List<String> servletNames = config.get(SERVLET_FILTER_SERVLET_NAMES)
            .defaultTo(Arrays.asList(DEFAULT_SERVLET_NAME)).asList(String.class);

    // URL patterns to apply the filter to, e.g. one could also add "/openidmui/*");
    List<String> urlPatterns = config.get(SERVLET_FILTER_URL_PATTERNS)
            .defaultTo(Arrays.asList(DEFAULT_SERVLET_URL_PATTERNS)).asList(String.class);

    // Filter init params, a string to string map
    JsonValue rawInitParams = config.get("initParams");
    Map<String, String> initParams = new HashMap<>();
    for (String initParamKey : rawInitParams.keys()) {
        initParams.put(initParamKey, rawInitParams.get(initParamKey).asString());
    }

    // Create a classloader and dynamically create the requested filter
    Filter filter = null;
    ClassLoader filterCL = null;
    ClassLoader origCL = Thread.currentThread().getContextClassLoader();
    try {
        filterCL = new URLClassLoader(urls.toArray(new URL[0]), this.getClass().getClassLoader());
        Thread.currentThread().setContextClassLoader(filterCL);
        filter = (Filter) (Class.forName(filterClass, true, filterCL).newInstance());
    } catch (Exception ex) {
        logger.warn("Configured class {} failed to load from configured class path URLs {}",
                new Object[] { filterClass, urls, ex });
        throw ex;
    } finally {
        Thread.currentThread().setContextClassLoader(origCL);
    }

    // Create filter
    Filter proxiedFilter = (Filter) Proxy.newProxyInstance(filter.getClass().getClassLoader(),
            new Class[] { Filter.class }, new FilterProxy(filter, filterCL, preInvokeReqAttributes));

    // Register filter
    webContainer.registerFilter(proxiedFilter, urlPatterns.toArray(new String[urlPatterns.size()]),
            servletNames.toArray(new String[servletNames.size()]), new Hashtable<String, Object>(initParams),
            webContainer.getDefaultSharedHttpContext());
    return proxiedFilter;
}

From source file:com.github.cherimojava.data.mongo.entity.EntityFactory.java

/**
 * Creates a new instance of the given Entity based Class, allowing to provide a custom EntityInvocationHandler
 *
 * @param clazz entity class to instantiate from
 * @param handler which is used to provide the functionality of this proxy
 * @return new instance of this class/* w  ww  . ja  va 2 s .c o m*/
 */
@SuppressWarnings("unchecked")
static <T extends Entity> T instantiate(Class<T> clazz, EntityInvocationHandler handler) {
    T proxy = (T) Proxy.newProxyInstance(EntityInvocationHandler.class.getClassLoader(),
            new Class<?>[] { clazz }, handler);
    handler.setProxy(proxy);
    return proxy;
}

From source file:com.medallia.spider.api.StRenderer.java

private Object createInput(Class<?> x, final DynamicInputImpl dynamicInput) {
    return Proxy.newProxyInstance(x.getClassLoader(), new Class<?>[] { x }, new InvocationHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return dynamicInput.getInput(method.getName(), method.getReturnType(), method);
        }/*from ww  w  .j  a v  a2  s .c o m*/
    });
}

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

/**
 * @param  model  the data model object. Its class implemets the modelInterface
 * @return a proxy object for model object. v4 app is responsible to cast it to the 
 *         interface @model class implements. when v4 app invoks its method, the returned
 *         object will be traced./*w  w  w . ja v  a 2s .  c o m*/
 * 
 * sample v4 application:
 * public interface IFooModel {
 *    ...
 * }
 * 
 * public classs FooModelImpl implements IFooModel {
 * }
 * 
 * void bar() {
 *    FooModelImpl model = new FooModelImpl();  
 *    IFooModel proxy = (IFooModel)TraceHelper.getInstance().getProxy(model);
 *    .....
 * }
 * 
 */
public Object getProxy(final Object model) {
    ClassLoader classLoader = model.getClass().getClassLoader();
    Class[] interfaces = model.getClass().getInterfaces();

    InvocationHandler handler = new JavaBeanInvocationHandler(model);

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

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

/** Construct a client-side proxy object that implements the named protocol,
 * talking to a server at the named address.
 * @param <T>*///from  w w w.  j ava 2 s .c  o  m
@Override
@SuppressWarnings("unchecked")
public <T> ProtocolProxy<T> getProxy(Class<T> protocol, long clientVersion, InetSocketAddress addr, Option conf,
        SocketFactory factory, int rpcTimeout, RetryPolicy connectionRetryPolicy) throws IOException {

    if (connectionRetryPolicy != null) {
        throw new UnsupportedOperationException(
                "Not supported: connectionRetryPolicy=" + connectionRetryPolicy);
    }

    T proxy = (T) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol },
            new Invoker(protocol, addr, conf, factory, rpcTimeout));
    return new ProtocolProxy<T>(protocol, proxy);
}