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.utils.ProxyUtils.java

public static Object getEntityProxy(final AbstractService<?> service, final ClientEntity entity,
        final URI entitySetURI, final Class<?> type, final String eTag, final boolean checkInTheContext) {

    EntityInvocationHandler handler = EntityInvocationHandler.getInstance(entity, entitySetURI, type, service);

    if (StringUtils.isNotBlank(eTag)) {
        // override ETag into the wrapped object.
        handler.setETag(eTag);//  w  w  w. j  a va  2 s . co m
    }

    if (checkInTheContext && service.getContext().entityContext().isAttached(handler)) {
        handler = service.getContext().entityContext().getEntity(handler.getUUID());
        handler.setEntity(entity);
    }

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

From source file:org.apache.camel.component.gae.task.GTaskEndpoint.java

/**
 * Proxies the {@link HttpBinding} returned by {@link super#getBinding()}
 * with a dynamic proxy. The proxy's invocation handler further delegates to
 * {@link InboundBinding#readRequest(org.apache.camel.Endpoint, Exchange, Object)} .
 * /* w  ww  .  j  ava 2s .  com*/
 * @return proxied {@link HttpBinding}.
 */
@Override
public HttpBinding getBinding() {
    return (HttpBinding) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { HttpBinding.class },
            new HttpBindingInvocationHandler<GTaskEndpoint, HttpServletRequest, HttpServletResponse>(this,
                    super.getBinding(), getInboundBinding()));
}

From source file:org.apache.cocoon.components.source.impl.BlockContextSource.java

private static Source adjustName(final TraversableSource source, final String blockName) {
    TraversableSource adjustedSource = (TraversableSource) Proxy.newProxyInstance(
            source.getClass().getClassLoader(), ClassUtils.getAllInterfaces(source), new InvocationHandler() {

                /* (non-Javadoc)
                 * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
                 *//*w  w  w. j  a v a2s  .c  o m*/
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if (method.equals(TraversableSource.class.getMethod("getName", new Class[] {})))
                        return blockName;
                    else
                        return method.invoke(source, args);
                }
            });
    return adjustedSource;
}

From source file:net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst.java

public <E> List<E> getOrderedNodes(Class<E> clazz, String plsqlCode) {
    Collector<E> coll = new Collector<>(clazz, new ArrayList<E>());
    LanguageVersionHandler languageVersionHandler = LanguageRegistry.getLanguage(PLSQLLanguageModule.NAME)
            .getDefaultVersion().getLanguageVersionHandler();
    ASTInput cu = (ASTInput) languageVersionHandler.getParser(languageVersionHandler.getDefaultParserOptions())
            .parse(null, new StringReader(plsqlCode));
    PLSQLParserVisitor jpv = (PLSQLParserVisitor) Proxy.newProxyInstance(
            PLSQLParserVisitor.class.getClassLoader(), new Class[] { PLSQLParserVisitor.class }, coll);
    jpv.visit(cu, null);/* w w w . j a  v a  2s .c om*/
    SymbolFacade sf = new SymbolFacade();
    sf.initializeWith(cu);
    DataFlowFacade dff = new DataFlowFacade();
    dff.initializeWith(languageVersionHandler.getDataFlowHandler(), cu);
    return (List<E>) coll.getCollection();
}

From source file:grails.plugin.springsecurity.web.access.GrailsWebInvocationPrivilegeEvaluator.java

static HttpServletRequest createInstance(final String contextPath, final String httpMethod,
        final String requestURI) {
    final Map<String, Object> attributes = new HashMap<String, Object>();

    return (HttpServletRequest) Proxy.newProxyInstance(HttpServletRequest.class.getClassLoader(),
            new Class[] { HttpServletRequest.class }, new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) {

                    String methodName = method.getName();

                    if ("getContextPath".equals(methodName))
                        return contextPath;
                    if ("getMethod".equals(methodName))
                        return httpMethod;
                    if ("getRequestURI".equals(methodName))
                        return requestURI;
                    if ("setAttribute".equals(methodName)) {
                        attributes.put((String) args[0], args[1]);
                        return null;
                    }//from   www .  j a v a  2 s  . c  om
                    if ("getAttribute".equals(methodName)) {
                        return attributes.get(args[0]);
                    }

                    if ("getProtocol".equals(methodName) || "getScheme".equals(methodName))
                        return "http";
                    if ("getServerName".equals(methodName))
                        return "localhost";
                    if ("getServerPort".equals(methodName))
                        return 8080;

                    if (methodName.startsWith("is"))
                        return false;

                    if ("getParameterMap".equals(methodName))
                        return Collections.emptyMap();

                    if ("getAttributeNames".equals(methodName) || "getHeaderNames".equals(methodName)
                            || "getHeaders".equals(methodName) || "getLocales".equals(methodName)
                            || "getParameterNames".equals(methodName)) {
                        return Collections.enumeration(Collections.emptySet());
                    }

                    return null;
                }
            });
}

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

@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 {

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

From source file:org.broadleafcommerce.common.util.BLCCollectionUtils.java

/**
 * Create a collection proxy that will perform some piece of work whenever modification methods are called on the
 * proxy. This includes the add, allAll, remove, removeAll, clear methods. Additionally, calling remove on an iterator
 * created from this collection is also covered.
 *
 * @param work the work to perform on collection modification
 * @param original the original collection to make change aware
 * @param <T> the collection type (e.g. List, Set, etc...)
 * @return the proxied collection/*from   w ww.j  a  va  2 s.  c o  m*/
 */
public static <T extends Collection> T createChangeAwareCollection(final WorkOnChange work,
        final Collection original) {
    T proxy = (T) Proxy.newProxyInstance(BLCCollectionUtils.class.getClassLoader(),
            ClassUtils.getAllInterfacesForClass(original.getClass()), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if (method.getName().startsWith("add") || method.getName().startsWith("remove")
                            || method.getName().startsWith("clear")) {
                        work.doWork(original);
                    }
                    if (method.getName().equals("iterator")) {
                        final Iterator itr = (Iterator) method.invoke(original, args);
                        Iterator proxyItr = (Iterator) Proxy.newProxyInstance(getClass().getClassLoader(),
                                ClassUtils.getAllInterfacesForClass(itr.getClass()), new InvocationHandler() {
                                    @Override
                                    public Object invoke(Object proxy, Method method, Object[] args)
                                            throws Throwable {
                                        if (method.getName().equals("remove")) {
                                            work.doWork(original);
                                        }
                                        return method.invoke(itr, args);
                                    }
                                });
                        return proxyItr;
                    }
                    return method.invoke(original, args);
                }
            });
    return proxy;
}

From source file:org.apache.axis2.format.ManagedDataSourceFactory.java

/**
 * Create a {@link ManagedDataSource} proxy for an existing data source.
 * This will create a dynamic proxy implementing the same interfaces as
 * the original data source./* w  w  w .java2s.com*/
 * 
 * @param ds the original data source
 * @return a data source proxy implementing {@link ManagedDataSource}
 */
public static ManagedDataSource create(DataSource ds) {
    Class<?>[] orgIfaces = ds.getClass().getInterfaces();
    Class<?>[] ifaces = new Class[orgIfaces.length + 1];
    ifaces[0] = ManagedDataSource.class;
    System.arraycopy(orgIfaces, 0, ifaces, 1, orgIfaces.length);
    return (ManagedDataSource) Proxy.newProxyInstance(ManagedDataSourceFactory.class.getClassLoader(), ifaces,
            new DataSourceManager(ds));
}

From source file:com.github.dbutils.mybatis.extend.MybatisSqlSessionTemplate.java

public MybatisSqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType,
        PersistenceExceptionTranslator exceptionTranslator) {
    super(sqlSessionFactory, executorType, exceptionTranslator);
    this.sqlSessionProxy = (SqlSession) Proxy.newProxyInstance(SqlSessionFactory.class.getClassLoader(),
            new Class[] { SqlSession.class }, new SqlSessionInterceptor());
}

From source file:com.gzj.tulip.jade.context.application.JadeFactory.java

@SuppressWarnings("unchecked")
public <T> T create(Class<?> daoClass) {
    try {/*w ww .j  a  va2 s  . c om*/
        DAOConfig config = new DAOConfig(dataAccessFactory, rowMapperFactory, interpreterFactory, cacheProvider,
                statementWrapperProvider);
        DAOMetaData daoMetaData = new DAOMetaData(daoClass, config);
        JadeInvocationHandler handler = new JadeInvocationHandler(daoMetaData);
        ClassLoader classLoader = ClassUtils.getDefaultClassLoader();
        return (T) Proxy.newProxyInstance(classLoader, new Class[] { daoClass }, handler);
    } catch (RuntimeException e) {
        throw new IllegalStateException("failed to create bean for " + daoClass.getName(), e);
    }
}