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.bsc.maven.plugin.confluence.PegdownTest.java

@Test
public void parseTest() throws IOException {

    InvocationHandler handler = new InvocationHandler() {

        int indent = 0;

        protected void visitChildren(Object proxy, Node node) {
            for (Node child : node.getChildren()) {
                child.accept((Visitor) proxy);
            }//from w w w.j a  va2s .co m
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

            for (int i = 0; i < indent; ++i)
                System.out.print('\t');
            final Object n = args[0];

            System.out.printf("[%s]", n);
            IfContext.iF(n, StrongEmphSuperNode.class, sesn).elseIf(n, ExpLinkNode.class, eln)
                    .elseIf(n, AnchorLinkNode.class, aln).elseIf(n, VerbatimNode.class, vln)
                    .elseIf(n, RefLinkNode.class, rln)

            ;
            System.out.println();

            if (n instanceof Node) {
                ++indent;
                visitChildren(proxy, (Node) args[0]);
                --indent;
            }
            return null;
        }

    };

    final ClassLoader cl = PegdownTest.class.getClassLoader();

    final Visitor proxy = (Visitor) Proxy.newProxyInstance(cl, new Class[] { Visitor.class }, handler);

    final PegDownProcessor p = new PegDownProcessor(ToConfluenceSerializer.extensions());

    final RootNode root = p.parseMarkdown(loadResource(FILES[1]));

    root.accept(proxy);
}

From source file:org.apache.hadoop.ipc.AvroRpcEngine.java

/** Construct a client-side proxy object that implements the named protocol,
 * talking to a server at the named address. */
public Object getProxy(Class<?> protocol, long clientVersion, InetSocketAddress addr,
        UserGroupInformation ticket, Configuration conf, SocketFactory factory, int rpcTimeout)
        throws IOException {
    return Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol },
            new Invoker(protocol, addr, ticket, conf, factory, rpcTimeout));
}

From source file:org.corfudb.runtime.protocols.AsyncPooledThriftClient.java

/**
 * Gets a client instance that implements the AsyncIface interface that
 * connects to the given connection string.
 *
 * @param <T>/*from w  w  w.  j  a v  a2s.  c  o  m*/
 * @param asyncIfaceClass
 *          the AsyncIface interface to pool.
 * @param connectionStr
 *          the connection string.
 * @return the client instance.
 */
@SuppressWarnings("unchecked")
public <T> T getClient(final Class<T> asyncIfaceClass) {
    return (T) Proxy.newProxyInstance(asyncIfaceClass.getClassLoader(), new Class[] { asyncIfaceClass },
            new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    return execute(new AsyncCall(asyncIfaceClass, method, args, _connection));
                }
            });
}

From source file:org.apache.fop.events.DefaultEventBroadcaster.java

/**
 * Creates a dynamic proxy for the given EventProducer interface that will handle the
 * conversion of the method call into the broadcasting of an event instance.
 * @param clazz a descendant interface of EventProducer
 * @return the EventProducer instance/* ww w  .j  a v  a  2  s. c o m*/
 */
protected EventProducer createProxyFor(Class clazz) {
    final EventProducerModel producerModel = getEventProducerModel(clazz);
    if (producerModel == null) {
        throw new IllegalStateException("Event model doesn't contain the definition for " + clazz.getName());
    }
    return (EventProducer) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz },
            new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    String methodName = method.getName();
                    EventMethodModel methodModel = producerModel.getMethod(methodName);
                    String eventID = producerModel.getInterfaceName() + "." + methodName;
                    if (methodModel == null) {
                        throw new IllegalStateException("Event model isn't consistent"
                                + " with the EventProducer interface. Please rebuild FOP!"
                                + " Affected method: " + eventID);
                    }
                    Map params = new java.util.HashMap();
                    int i = 1;
                    Iterator iter = methodModel.getParameters().iterator();
                    while (iter.hasNext()) {
                        EventMethodModel.Parameter param = (EventMethodModel.Parameter) iter.next();
                        params.put(param.getName(), args[i]);
                        i++;
                    }
                    Event ev = new Event(args[0], eventID, methodModel.getSeverity(), params);
                    broadcastEvent(ev);

                    if (ev.getSeverity() == EventSeverity.FATAL) {
                        EventExceptionManager.throwException(ev, methodModel.getExceptionClass());
                    }
                    return null;
                }
            });
}

From source file:com.taobao.common.tedis.group.ReliableAsynTedisGroup.java

public void init() {
    if (!inited) {
        try {/*from  ww w  .ja v a2  s.c o m*/
            if (this.cm == null) {
                this.cm = new DiamondConfigManager(appName, version);
            }
            this.ospreyManager = new OspreyManager("tedis-" + appName + "-" + version);
            this.ospreyManager.registerProcessor(new OspreyProcessor<ReliableAsynMessage>() {

                @Override
                public Class<ReliableAsynMessage> interest() {
                    return ReliableAsynMessage.class;
                }

                @Override
                public Result process(ReliableAsynMessage message) {
                    Result result = new Result();
                    long time = System.currentTimeMillis();

                    Single single = cm.getRouter().getAtomic(message.getSingleKey());
                    if (single == null) {
                        result.setSuccess(false);
                        result.setErrorMessage("Current atomic is null");
                        return result;
                    }

                    try {
                        message.getMethod().invoke(single.getTedis(), message.getArgs());
                    } catch (Throwable t) {
                        logger.warn("write exception:" + single.getProperties(), t);
                        try {
                            statLog(message.getMethod().getName(), false, time);
                            // 
                            InvocationTargetException ite = (InvocationTargetException) t;
                            UndeclaredThrowableException ute = (UndeclaredThrowableException) ite
                                    .getTargetException();
                            if (ute.getUndeclaredThrowable() instanceof TimeoutException) {
                                result.setSuccess(false);
                                result.setErrorMessage("TimeoutException");
                                result.setRuntimeException(ute);
                                return result;
                            } else {
                                ExecutionException ee = (ExecutionException) ute.getUndeclaredThrowable();
                                InvocationTargetException ite_1 = (InvocationTargetException) ee.getCause();
                                TedisException te = (TedisException) ite_1.getTargetException();
                                if (te.getCause() instanceof TedisConnectionException) {
                                    result.setSuccess(false);
                                    result.setErrorMessage("JedisConnectionException");
                                    result.setRuntimeException(te);
                                    return result;
                                }
                            }
                        } catch (Throwable tt) {
                            logger.warn(":", tt);
                        }
                    }
                    return result;
                }
            });
            this.ospreyManager.init();
            tedis = (RedisCommands) Proxy.newProxyInstance(RedisCommands.class.getClassLoader(),
                    new Class[] { RedisCommands.class }, new TedisGroupInvocationHandler());
        } catch (Exception e) {
            throw new TedisException("init failed", e);
        }
        inited = true;
    }
}

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

@SuppressWarnings("unchecked")
@Override//from w  w  w .ja v  a  2s . co m
public Triple<List<T>, URI, List<ClientAnnotation>> fetchPartial(final URI uri, final Class<T> typeRef) {

    final List<ClientEntity> entities = new ArrayList<ClientEntity>();
    final URI next;
    final List<ClientAnnotation> anns = new ArrayList<ClientAnnotation>();

    if (isSingleton) {
        final ODataRetrieveResponse<ClientSingleton> res = ((ODataClient) getClient())
                .getRetrieveRequestFactory().getSingletonRequest(uri).execute();

        entities.add(res.getBody());
        next = null;
    } else {
        final ODataEntitySetRequest<ClientEntitySet> req = getClient().getRetrieveRequestFactory()
                .getEntitySetRequest(uri);
        req.setPrefer(getClient().newPreferences().includeAnnotations("*"));

        final ODataRetrieveResponse<ClientEntitySet> res = req.execute();

        final ClientEntitySet entitySet = res.getBody();
        entities.addAll(entitySet.getEntities());
        next = entitySet.getNext();
        anns.addAll(entitySet.getAnnotations());
    }

    final List<T> res = new ArrayList<T>(entities.size());

    for (ClientEntity entity : entities) {
        Class<?> actualRef = null;
        if (entity.getTypeName() != null) {
            actualRef = service.getEntityTypeClass(entity.getTypeName().toString());
        }
        if (actualRef == null) {
            actualRef = typeRef;
        }

        final EntityInvocationHandler handler = this instanceof EntitySetInvocationHandler
                ? EntityInvocationHandler.getInstance(entity, EntitySetInvocationHandler.class.cast(this),
                        actualRef)
                : EntityInvocationHandler.getInstance(entity, targetEntitySetURI, actualRef, service);

        final EntityInvocationHandler handlerInTheContext = getContext().entityContext()
                .getEntity(handler.getUUID());

        res.add((T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class<?>[] { actualRef }, handlerInTheContext == null ? handler : handlerInTheContext));
    }

    return new ImmutableTriple<List<T>, URI, List<ClientAnnotation>>(res, next, anns);
}

From source file:com._4dconcept.springframework.data.marklogic.datasource.TransactionAwareContentSourceProxy.java

/**
 * Wraps the given Session with a proxy that delegates every method call to it
 * but delegates {@code close()} calls to ContentSourceUtils.
 *
 * @param targetContentSource ContentSource that the Session came from
 * @return the wrapped Session//from  ww w.  j  av  a2s .  co  m
 * @see Session#close()
 * @see ContentSourceUtils#doReleaseSession
 */
protected Session getTransactionAwareSessionProxy(ContentSource targetContentSource) {
    return (Session) Proxy.newProxyInstance(SessionProxy.class.getClassLoader(),
            new Class<?>[] { SessionProxy.class }, new TransactionAwareInvocationHandler(targetContentSource));
}

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

public Connection createConnectionProxy(Connection conn) throws SQLException {
    return (Connection) Proxy.newProxyInstance(conn.getClass().getClassLoader(),
            getClassInterfaces(conn.getClass()), new ConnectionInvocationHandler(conn));
}

From source file:org.hyperic.hq.agent.server.CollectorThread.java

/** proxy used to intercept in order to create stats */
private Runnable getProxy(final Collector collector) {
    InvocationHandler handler = new InvocationHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if ((null == args || args.length == 0) && method.getName().equals("run")) {
                final long start = now();
                Object rtn = method.invoke(collector, args);
                final long duration = now() - start;
                statsCollector.addStat(duration, COLLECTOR_THREAD_METRIC_COLLECTED_TIME);
                return rtn;
            } else {
                return method.invoke(collector, args);
            }/*from w  w w .  j a v  a2s .  c om*/
        }
    };
    return (Runnable) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
            new Class[] { Runnable.class }, handler);
}

From source file:com.msopentech.odatajclient.proxy.api.impl.AbstractInvocationHandler.java

@SuppressWarnings("unchecked")
protected <T> T getEntityProxy(final ODataEntity entity, final String entityContainerName,
        final String entitySetName, final Class<?> type, final String eTag, final boolean checkInTheContext) {

    EntityTypeInvocationHandler handler = EntityTypeInvocationHandler.getInstance(entity, entityContainerName,
            entitySetName, type, containerHandler);

    if (StringUtils.isNotBlank(eTag)) {
        // override ETag into the wrapped object.
        handler.setETag(eTag);/*from w  w w.  ja  v a 2  s  .  c  om*/
    }

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

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