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.hippoecm.frontend.service.restproxy.custom.json.deserializers.AnnotationJsonDeserializer.java

@SuppressWarnings("unchecked")
@Override//from   w  w  w .j  ava 2 s  . co m
public Annotation deserialize(JsonParser jsonParser, DeserializationContext deserContext)
        throws IOException, JsonProcessingException {

    Annotation annotation = null;
    String annotationTypeName = null;
    Class<? extends Annotation> annotationClass = null;
    Map<String, Object> annotationAttributes = null;

    while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
        // Read the '@class' field name
        jsonParser.nextToken();
        // Now read the '@class' field value
        annotationTypeName = jsonParser.getText();

        try {
            annotationClass = (Class<? extends Annotation>) Class.forName(annotationTypeName);
            annotationAttributes = new HashMap<String, Object>(annotationClass.getDeclaredMethods().length);
            while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
                final String fieldName = jsonParser.getCurrentName();
                final Method annotationAttribute = annotationClass.getDeclaredMethod(fieldName,
                        new Class<?>[] {});
                annotationAttributes.put(fieldName,
                        deserializeAnnotationAttribute(annotationClass, annotationAttribute, jsonParser));
            }
            // Annotation deserialization is done here
            break;
        } catch (ClassNotFoundException cnfe) {
            throw new AnnotationProcessingException("Error while processing annotation: " + annotationTypeName,
                    cnfe);
        } catch (SecurityException se) {
            throw new AnnotationProcessingException("Error while processing annotation: " + annotationTypeName,
                    se);
        } catch (NoSuchMethodException nsme) {
            if (log.isDebugEnabled()) {
                log.info("Error while processing annotation: " + annotationTypeName + ". " + nsme);
            } else {
                log.info("Error while processing annotation: {}. {}", annotationTypeName, nsme);
            }

        }
    }

    annotation = (Annotation) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
            new Class<?>[] { annotationClass },
            new AnnotationProxyInvocationHandler(annotationClass, annotationAttributes));

    return annotation;
}

From source file:com.nearinfinity.blur.thrift.AsyncClientPool.java

/**
 * Gets a client instance that implements the AsyncIface interface that
 * connects to the given connection string.
 * /*w ww. j a  v  a  2 s  . co m*/
 * @param <T>
 * @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, final String connectionStr) {
    List<Connection> connections = BlurClientManager.getConnections(connectionStr);
    Collections.shuffle(connections, random);
    //randomness ftw
    final Connection connection = connections.get(0);
    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:com.msopentech.odatajclient.proxy.api.impl.AbstractInvocationHandler.java

@SuppressWarnings({ "unchecked", "rawtypes" })
protected Object getEntityCollection(final Class<?> typeRef, final Class<?> typeCollectionRef,
        final String entityContainerName, final ODataEntitySet entitySet, final URI uri,
        final boolean checkInTheContext) {

    final List<Object> items = new ArrayList<Object>();

    for (ODataEntity entityFromSet : entitySet.getEntities()) {
        items.add(getEntityProxy(entityFromSet, entityContainerName, entitySet.getName(), typeRef,
                checkInTheContext));//from w  w  w  .  j av  a  2  s .c om
    }

    return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
            new Class<?>[] { typeCollectionRef },
            new EntityCollectionInvocationHandler(containerHandler, items, typeRef, entityContainerName, uri));
}

From source file:com.payu.ratel.register.ServiceRegisterPostProcessor.java

public Object decorateWithMonitoring(final Object object, final Class clazz) {
    return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] { clazz },
            new ServiceInvocationHandler(configurableListableBeanFactory, object, clazz));
}

From source file:EventTracerTest.java

/**
 * Add a listener to the given event set
 * @param c a component/*  w  w  w .jav a2 s  . c o  m*/
 * @param eventSet a descriptor of a listener interface
 */
public void addListener(Component c, EventSetDescriptor eventSet) {
    // make proxy object for this listener type and route all calls to the handler
    Object proxy = Proxy.newProxyInstance(null, new Class[] { eventSet.getListenerType() }, handler);

    // add the proxy as a listener to the component
    Method addListenerMethod = eventSet.getAddListenerMethod();
    try {
        addListenerMethod.invoke(c, proxy);
    } catch (InvocationTargetException e) {
    } catch (IllegalAccessException e) {
    }
    // ok not to add listener if exception is thrown
}

From source file:com.gzj.tulip.jade.context.spring.JadeFactoryBean.java

protected Object createDAO() {
    try {/*  ww  w .  ja v  a2s.  c o m*/
        DAOConfig config = new DAOConfig(dataAccessFactory, rowMapperFactory, interpreterFactory, cacheProvider,
                statementWrapperProvider);
        DAOMetaData daoMetaData = new DAOMetaData(objectType, config);
        JadeInvocationHandler handler = new JadeInvocationHandler(daoMetaData);
        return Proxy.newProxyInstance(ClassUtils.getDefaultClassLoader(), new Class[] { objectType }, handler);
    } catch (RuntimeException e) {
        throw new IllegalStateException("failed to create bean for " + this.objectType.getName(), e);
    }
}

From source file:com.mirth.connect.connectors.jms.xa.ConnectionFactoryWrapper.java

public TopicConnection createTopicConnection() throws JMSException {
    XATopicConnection xatc = ((XATopicConnectionFactory) factory).createXATopicConnection();
    TopicConnection proxy = (TopicConnection) Proxy.newProxyInstance(Connection.class.getClassLoader(),
            new Class[] { TopicConnection.class }, new ConnectionInvocationHandler(xatc));
    return proxy;
}

From source file:org.apache.shindig.protocol.conversion.BeanFilter.java

@SuppressWarnings("unchecked")
private Object createFilteredBean(Object data, Set<String> fields, String fieldName) {
    // For null, atomic object or for all fields just return original.
    if (data == null || fields == null || BeanDelegator.PRIMITIVE_TYPE_CLASSES.contains(data.getClass())
            || fields.contains(ALL_FIELDS)) {
        return data;
    }/*from  ww w .  jav a2 s . com*/

    // For map, generate a new map with filtered objects
    if (data instanceof Map<?, ?>) {
        Map<Object, Object> oldMap = (Map<Object, Object>) data;
        Map<Object, Object> newMap = Maps.newHashMapWithExpectedSize(oldMap.size());
        for (Map.Entry<Object, Object> entry : oldMap.entrySet()) {
            newMap.put(entry.getKey(), createFilteredBean(entry.getValue(), fields, fieldName));
        }
        return newMap;
    }

    // For list, generate a new list of filtered objects
    if (data instanceof List<?>) {
        List<Object> oldList = (List<Object>) data;
        List<Object> newList = Lists.newArrayListWithCapacity(oldList.size());
        for (Object entry : oldList) {
            newList.add(createFilteredBean(entry, fields, fieldName));
        }
        return newList;
    }

    // Create a new intercepted object:
    return Proxy.newProxyInstance(data.getClass().getClassLoader(), data.getClass().getInterfaces(),
            new FilterInvocationHandler(data, fields, fieldName));
}

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

@Override
@SuppressWarnings("unchecked")
public <T> ProtocolProxy<T> getProxy(Class<T> protocol, long clientVersion, InetSocketAddress addr,
        UserGroupInformation ticket, Configuration conf, SocketFactory factory, int rpcTimeout,
        RetryPolicy connectionRetryPolicy, AtomicBoolean fallbackToSimpleAuth) throws IOException {

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

From source file:com.facebook.GraphObjectWrapper.java

private static <T extends GraphObject> T createGraphObjectProxy(Class<T> graphObjectClass, JSONObject state) {
    verifyCanProxyClass(graphObjectClass);

    Class<?>[] interfaces = new Class[] { graphObjectClass };
    GraphObjectProxy graphObjectProxy = new GraphObjectProxy(state, graphObjectClass);

    @SuppressWarnings("unchecked")
    T graphObject = (T) Proxy.newProxyInstance(GraphObject.class.getClassLoader(), interfaces,
            graphObjectProxy);/* ww w  .  j av a 2s .co m*/

    return graphObject;
}