Example usage for java.lang.reflect Proxy isProxyClass

List of usage examples for java.lang.reflect Proxy isProxyClass

Introduction

In this page you can find the example usage for java.lang.reflect Proxy isProxyClass.

Prototype

public static boolean isProxyClass(Class<?> cl) 

Source Link

Document

Returns true if the given class is a proxy class.

Usage

From source file:com.paladin.sys.db.DBManager.java

public static final Connection getConnection() {
    Connection conn = conns.get();
    try {//from w w w.  j a va  2 s .  c  o m
        if (conn == null || conn.isClosed()) {
            conn = dataSource.getConnection();
            conns.set(conn);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return (show_sql && !Proxy.isProxyClass(conn.getClass())) ? new DebugConnection(conn).getConnection()
            : conn;
}

From source file:org.resthub.rpc.AMQPProxy.java

/**
 * Handles the object invocation.//from  w ww .ja  va2  s  .c  o  m
 *
 * @param proxy  the proxy object to invoke
 * @param method the method to call
 * @param args   the arguments to the proxy object
 */
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String methodName = method.getName();
    Class<?>[] params = method.getParameterTypes();

    // equals and hashCode are special cased
    if (methodName.equals("equals") && params.length == 1 && params[0].equals(Object.class)) {
        Object value = args[0];
        if (value == null || !Proxy.isProxyClass(value.getClass())) {
            return Boolean.FALSE;
        }

        AMQPProxy handler = (AMQPProxy) Proxy.getInvocationHandler(value);

        return _factory.equals(handler._factory);
    } else if (methodName.equals("hashCode") && params.length == 0) {
        return _factory.hashCode();
    } else if (methodName.equals("toString") && params.length == 0) {
        return "[HessianProxy " + proxy.getClass() + "]";
    }

    ConnectionFactory connectionFactory = _factory.getConnectionFactory();

    Message response = sendRequest(connectionFactory, method, args);

    if (response == null) {
        throw new TimeoutException();
    }

    MessageProperties props = response.getMessageProperties();
    boolean compressed = "deflate".equals(props.getContentEncoding());

    InputStream is = new ByteArrayInputStream(response.getBody());
    if (compressed) {
        is = new InflaterInputStream(is, new Inflater(true));
    }

    return _factory.getSerializationHandler().readObject(method.getReturnType(), is);
}

From source file:com.liferay.arkadiko.test.TestThree.java

public void testDeployBundleWithImplementation() throws Exception {
    InterfaceOne interfaceOne = null;/*ww w  . ja  va  2 s  .c  o  m*/

    HasDependencyOnInterfaceOne bean, beanTwo, beanThree = null;

    // Install the bundle with the alternative impl

    Bundle installedBundle = installAndStart(_context, "/bundles/bundle-one/bundle-one.jar");

    try {
        // Test that the alternative impl is used by the first bean

        bean = (HasDependencyOnInterfaceOne) _context.getBean(HasDependencyOnInterfaceOne.class.getName());

        interfaceOne = bean.getInterfaceOne();

        assertTrue("interfaceOne is not a proxy", Proxy.isProxyClass(interfaceOne.getClass()));

        InvocationHandler ih = Proxy.getInvocationHandler(interfaceOne);

        assertTrue("ih not instanceof AKServiceTrackerInvocationHandler",
                ih instanceof ServiceTrackerInvocationHandler);

        ServiceTrackerInvocationHandler akih = (ServiceTrackerInvocationHandler) ih;

        assertFalse("currentService is equal to originalService",
                akih.getCurrentService() == akih.getOriginalService());

        beanTwo = (HasDependencyOnInterfaceOne) _context
                .getBean(HasDependencyOnInterfaceOne.class.getName().concat("_TWO"));

        interfaceOne = beanTwo.getInterfaceOne();

        assertTrue("interfaceOne is not a proxy", Proxy.isProxyClass(interfaceOne.getClass()));

        ih = Proxy.getInvocationHandler(interfaceOne);

        assertTrue("ih not instanceof AKServiceTrackerInvocationHandler",
                ih instanceof ServiceTrackerInvocationHandler);

        akih = (ServiceTrackerInvocationHandler) ih;

        assertFalse("currentService is equal to originalService",
                akih.getCurrentService() == akih.getOriginalService());

        beanThree = (HasDependencyOnInterfaceOne) _context
                .getBean(HasDependencyOnInterfaceOne.class.getName().concat("_THREE"));

        interfaceOne = beanThree.getInterfaceOne();

        assertFalse("interfaceOne is a proxy", Proxy.isProxyClass(interfaceOne.getClass()));
    } finally {
        installedBundle.uninstall();
    }

    interfaceOne = bean.getInterfaceOne();

    assertTrue("interfaceOne is not a proxy", Proxy.isProxyClass(interfaceOne.getClass()));

    InvocationHandler ih = Proxy.getInvocationHandler(interfaceOne);

    assertTrue("ih not instanceof AKServiceTrackerInvocationHandler",
            ih instanceof ServiceTrackerInvocationHandler);

    ServiceTrackerInvocationHandler akih = (ServiceTrackerInvocationHandler) ih;

    assertTrue("currentService not equal to originalService",
            akih.getCurrentService() == akih.getOriginalService());

    interfaceOne = beanTwo.getInterfaceOne();

    assertTrue("interfaceOne is not a proxy", Proxy.isProxyClass(interfaceOne.getClass()));

    ih = Proxy.getInvocationHandler(interfaceOne);

    assertTrue("ih not instanceof AKServiceTrackerInvocationHandler",
            ih instanceof ServiceTrackerInvocationHandler);

    akih = (ServiceTrackerInvocationHandler) ih;

    assertTrue("currentService not equal to originalService",
            akih.getCurrentService() == akih.getOriginalService());

    interfaceOne = beanThree.getInterfaceOne();

    assertFalse("interfaceOne is a proxy", Proxy.isProxyClass(interfaceOne.getClass()));
}

From source file:com.sworddance.util.WeakProxy.java

/**
 *
 * @param <T>/*from   w  w w .java2s. c o  m*/
 * @param proxy
 * @return the actual object that is wrapped by {@link Reference} and {@link #newProxyInstance(Object, Class...)} created
 * objects.
 */
@SuppressWarnings("unchecked")
public static <T> T getActual(Object proxy) {
    Object actual = proxy;
    while (actual != null) {
        if (Proxy.isProxyClass(actual.getClass())) {
            InvocationHandler invocationHandler = Proxy.getInvocationHandler(actual);
            if (invocationHandler instanceof ProxyInvocationHandler<?>) {
                actual = ((ProxyInvocationHandler<?>) invocationHandler).getActual();
            } else {
                break;
            }
        } else if (actual instanceof Reference<?>) {
            actual = getActual(getReferent((Reference<T>) actual));
        } else {
            break;
        }
    }
    return (T) actual;
}

From source file:org.resthub.rpc.AMQPHessianProxy.java

/**
 * Handles the object invocation./*from   www  .ja  v a  2  s.c om*/
 *
 * @param proxy  the proxy object to invoke
 * @param method the method to call
 * @param args   the arguments to the proxy object
 */
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String methodName = method.getName();
    Class<?>[] params = method.getParameterTypes();

    // equals and hashCode are special cased
    if (methodName.equals("equals") && params.length == 1 && params[0].equals(Object.class)) {
        Object value = args[0];
        if (value == null || !Proxy.isProxyClass(value.getClass())) {
            return Boolean.FALSE;
        }

        AMQPHessianProxy handler = (AMQPHessianProxy) Proxy.getInvocationHandler(value);

        return _factory.equals(handler._factory);
    } else if (methodName.equals("hashCode") && params.length == 0) {
        return _factory.hashCode();
    } else if (methodName.equals("toString") && params.length == 0) {
        return "[HessianProxy " + proxy.getClass() + "]";
    }

    ConnectionFactory connectionFactory = _factory.getConnectionFactory();

    try {
        Message response = sendRequest(connectionFactory, method, args);

        if (response == null) {
            throw new TimeoutException();
        }

        MessageProperties props = response.getMessageProperties();
        boolean compressed = "deflate".equals(props.getContentEncoding());

        AbstractHessianInput in;

        InputStream is = new ByteArrayInputStream(response.getBody());
        if (compressed) {
            is = new InflaterInputStream(is, new Inflater(true));
        }

        int code = is.read();

        if (code == 'H') {
            int major = is.read();
            int minor = is.read();

            in = _factory.getHessian2Input(is);

            return in.readReply(method.getReturnType());
        } else if (code == 'r') {
            int major = is.read();
            int minor = is.read();

            in = _factory.getHessianInput(is);

            in.startReplyBody();

            Object value = in.readObject(method.getReturnType());

            in.completeReply();

            return value;
        } else {
            throw new HessianProtocolException("'" + (char) code + "' is an unknown code");
        }
    } catch (HessianProtocolException e) {
        throw new HessianRuntimeException(e);
    }
}

From source file:org.seedstack.spring.SeedFactoryBeanIT.java

@Test
public void proxy_attribute_is_applied() {
    Assertions.assertThat(Proxy.isProxyClass(context.getBean("service2").getClass())).isEqualTo(true);
    Assertions.assertThat(Proxy.isProxyClass(context.getBean("service3").getClass())).isEqualTo(false);
}

From source file:org.craftercms.commons.ebus.config.EBusBeanAutoConfiguration.java

private static Set<Method> findHandlerMethods(final Class<?> handlerType,
        final ReflectionUtils.MethodFilter listenerMethodFilter) {

    final Set<Method> handlerMethods = new LinkedHashSet<Method>();

    if (handlerType == null) {
        return handlerMethods;
    }//from  w  w w.j  a v  a 2  s .  c  o m

    Set<Class<?>> handlerTypes = new LinkedHashSet<Class<?>>();
    Class<?> specifiedHandlerType = null;
    if (!Proxy.isProxyClass(handlerType)) {
        handlerTypes.add(handlerType);
        specifiedHandlerType = handlerType;
    }
    handlerTypes.addAll(Arrays.asList(handlerType.getInterfaces()));
    for (Class<?> currentHandlerType : handlerTypes) {
        final Class<?> targetClass = (specifiedHandlerType != null ? specifiedHandlerType : currentHandlerType);
        ReflectionUtils.doWithMethods(currentHandlerType, new ReflectionUtils.MethodCallback() {
            @Override
            public void doWith(final Method method) throws IllegalArgumentException, IllegalAccessException {
                Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
                Method bridgeMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
                if (listenerMethodFilter.matches(specificMethod)
                        && (bridgeMethod == specificMethod || !listenerMethodFilter.matches(bridgeMethod))) {
                    handlerMethods.add(specificMethod);
                }
            }
        }, ReflectionUtils.USER_DECLARED_METHODS);
    }

    return handlerMethods;
}

From source file:com.aw.support.beans.BeanUtils.java

public static Object copyProperties(Object source, Object target, String[] propertyNamesToIgnore,
        boolean ignoreProxy, boolean ignoreCollections) {
    List<String> propertyNamesToIgnoreList = propertyNamesToIgnore == null ? Collections.EMPTY_LIST
            : Arrays.asList(propertyNamesToIgnore);
    BeanWrapper sourceWrap = new BeanWrapperImpl(source);
    BeanWrapper targetWrap = new BeanWrapperImpl(target);
    for (PropertyDescriptor propDescriptor : sourceWrap.getPropertyDescriptors()) {
        String propName = propDescriptor.getName();
        //chequear que no esta en la lista a ignorar
        if (propertyNamesToIgnoreList.contains(propName))
            continue;
        //chequear que se puede leer
        if (!sourceWrap.isReadableProperty(propName))
            continue;
        //chequear que se puede escribir
        if (!targetWrap.isWritableProperty(propName))
            continue;

        Object sourceValue = sourceWrap.getPropertyValue(propName);

        //chequear que objeto no es un proxy
        if (ignoreProxy && sourceValue != null && Proxy.isProxyClass(sourceValue.getClass()))
            continue;

        //chequear que objeto no una collection
        if (ignoreCollections && sourceValue instanceof Collection)
            continue;

        targetWrap.setPropertyValue(propName, sourceValue);
    }//from w w w .  ja  v a2  s.co m
    return target;
}

From source file:org.mybatis.spring.asyncsynchronization.AsyncAfterCompletionHelper.java

/**
 * Creates proxy that performs afterCompletion call on a separate thread
 * /*from  ww  w.j  av  a 2s  . c  o  m*/
 * @param synchronization
 * @return
 */
public TransactionSynchronization createSynchronizationWithAsyncAfterComplete(
        TransactionSynchronization synchronization) {
    if (Proxy.isProxyClass(synchronization.getClass())
            && Proxy.getInvocationHandler(synchronization) instanceof AsynchAfterCompletionInvocationHandler) {
        // avoiding double wrapping just in case
        return synchronization;
    }
    Class<?>[] interfaces = { TransactionSynchronization.class };
    return (TransactionSynchronization) Proxy.newProxyInstance(synchronization.getClass().getClassLoader(),
            interfaces, new AsynchAfterCompletionInvocationHandler(synchronization));

}

From source file:org.vbossica.springbox.annotation.AnnotatedMethodResolver.java

/**
 * Traverses the {@code bean} in search for annotated methods. Calls the
 * {@link #doWithAnnotatedMethod(String, Object, Method, Annotation)} for every method found.
 *
 * @param beanName the name of the Spring bean
 * @param bean the Spring bean itself/*from w  ww .jav a2s .c  o  m*/
 * @see #doWithAnnotatedMethod(String, Object, java.lang.reflect.Method, java.lang.annotation.Annotation)
 */
public void traverse(final String beanName, final Object bean) {
    logger.info("traversing bean " + beanName);

    Class<?> handlerType = bean.getClass();

    Class<?>[] handlerTypes = Proxy.isProxyClass(handlerType) ? handlerType.getInterfaces()
            : new Class<?>[] { handlerType };
    for (final Class<?> currentHandlerType : handlerTypes) {
        ReflectionUtils.doWithMethods(currentHandlerType, new ReflectionUtils.MethodCallback() {
            public void doWith(Method method) {
                Method specificMethod = ClassUtils.getMostSpecificMethod(method, currentHandlerType);
                A annotation = AnnotationUtils.findAnnotation(method, annotationClass);
                if (annotation != null) {
                    doWithAnnotatedMethod(beanName, bean, specificMethod, annotation);
                }
            }
        }, ReflectionUtils.NON_BRIDGED_METHODS);
    }
}