Example usage for org.springframework.aop.support AopUtils isAopProxy

List of usage examples for org.springframework.aop.support AopUtils isAopProxy

Introduction

In this page you can find the example usage for org.springframework.aop.support AopUtils isAopProxy.

Prototype

public static boolean isAopProxy(@Nullable Object object) 

Source Link

Document

Check whether the given object is a JDK dynamic proxy or a CGLIB proxy.

Usage

From source file:org.springframework.beans.factory.xml.XmlBeanFactoryTests.java

@Test
public void testCircularReferencesWithWrappingAndRawInjectionAllowed() {
    DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
    xbf.setAllowRawInjectionDespiteWrapping(true);
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
    reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
    reader.loadBeanDefinitions(REFTYPES_CONTEXT);
    xbf.addBeanPostProcessor(new WrappingPostProcessor());

    ITestBean jenny = (ITestBean) xbf.getBean("jenny");
    ITestBean david = (ITestBean) xbf.getBean("david");
    assertTrue(AopUtils.isAopProxy(jenny));
    assertTrue(AopUtils.isAopProxy(david));
    assertSame(david, jenny.getSpouse());
    assertNotSame(jenny, david.getSpouse());
    assertEquals("Jenny", david.getSpouse().getName());
    assertSame(david, david.getSpouse().getSpouse());
    assertTrue(AopUtils.isAopProxy(jenny.getSpouse()));
    assertTrue(!AopUtils.isAopProxy(david.getSpouse()));
}

From source file:org.springframework.integration.channel.interceptor.GlobalChannelInterceptorBeanPostProcessor.java

@SuppressWarnings("unchecked")
private List<ChannelInterceptor> getExistingInterceptors(MessageChannel channel) {
    try {//from  w w w  . j  ava2 s  . c  om
        MessageChannel targetChannel = channel;
        if (AopUtils.isAopProxy(channel)) {
            Object target = ((Advised) channel).getTargetSource().getTarget();
            if (target instanceof MessageChannel) {
                targetChannel = (MessageChannel) target;
            }
        }
        DirectFieldAccessor channelAccessor = new DirectFieldAccessor(targetChannel);
        Object interceptorListWrapper = channelAccessor.getPropertyValue("interceptors");
        if (interceptorListWrapper != null) {
            return (List<ChannelInterceptor>) new DirectFieldAccessor(interceptorListWrapper)
                    .getPropertyValue("interceptors");
        }
    } catch (NotReadablePropertyException e) {
        // Channel doesn't support interceptors - null return logged by caller
    } catch (Exception e) {
        // interceptors not supported, will return null
        if (logger.isDebugEnabled() && channel != null) {
            logger.debug("interceptors not supported by channel '" + channel + "'", e);
        }
    }
    return null;
}

From source file:org.springframework.integration.config.ConsumerEndpointFactoryBean.java

public void afterPropertiesSet() throws Exception {
    try {/* w  ww .j ava2s  .  c o  m*/
        if (!this.beanName.startsWith("org.springframework")) {
            MessageHandler targetHandler = this.handler;
            if (AopUtils.isAopProxy(targetHandler)) {
                Object target = ((Advised) targetHandler).getTargetSource().getTarget();
                if (target instanceof MessageHandler) {
                    targetHandler = (MessageHandler) target;
                }
            }
            if (targetHandler instanceof IntegrationObjectSupport) {
                ((IntegrationObjectSupport) targetHandler).setComponentName(this.beanName);
            }
        }
    } catch (Exception e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Could not set component name for handler " + this.handler + " for " + this.beanName
                    + " :" + e.getMessage());
        }
    }
    if (!CollectionUtils.isEmpty(this.adviceChain)) {
        /*
         *  ARPMHs advise the handleRequesMessage method internally and already have the advice chain injected.
         *  So we only advise handlers that are not reply-producing. If the handler is already advised,
         *  add the configured advices to its chain, otherwise create a proxy.
         */
        if (!(this.handler instanceof AbstractReplyProducingMessageHandler)) {
            if (AopUtils.isAopProxy(this.handler) && this.handler instanceof Advised) {
                Class<?> targetClass = AopUtils.getTargetClass(this.handler);
                for (Advice advice : this.adviceChain) {
                    NameMatchMethodPointcutAdvisor handlerAdvice = new NameMatchMethodPointcutAdvisor(advice);
                    handlerAdvice.addMethodName("handleMessage");
                    if (AopUtils.canApply(handlerAdvice.getPointcut(), targetClass)) {
                        ((Advised) this.handler).addAdvice(advice);
                    }
                }
            } else {
                ProxyFactory proxyFactory = new ProxyFactory(this.handler);
                for (Advice advice : this.adviceChain) {
                    proxyFactory.addAdvice(advice);
                }
                this.handler = (MessageHandler) proxyFactory.getProxy(this.beanClassLoader);
            }
        }
    }
    this.initializeEndpoint();
}

From source file:org.springframework.integration.handler.advice.AdvisedMessageHandlerTests.java

@Test
public void testInappropriateAdvice() throws Exception {
    final AtomicBoolean called = new AtomicBoolean(false);
    Advice advice = new AbstractRequestHandlerAdvice() {
        @Override/*from  w ww .  j av  a 2 s.  c om*/
        protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message)
                throws Exception {
            called.set(true);
            return callback.execute();
        }
    };
    PollableChannel inputChannel = new QueueChannel();
    PollingConsumer consumer = new PollingConsumer(inputChannel, new MessageHandler() {
        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
        }
    });
    consumer.setAdviceChain(Collections.singletonList(advice));
    consumer.setTaskExecutor(
            new ErrorHandlingTaskExecutor(Executors.newSingleThreadExecutor(), new ErrorHandler() {
                @Override
                public void handleError(Throwable t) {
                }
            }));
    consumer.afterPropertiesSet();

    Callable<?> pollingTask = TestUtils.getPropertyValue(consumer, "poller.pollingTask", Callable.class);
    assertTrue(AopUtils.isAopProxy(pollingTask));
    Log logger = TestUtils.getPropertyValue(advice, "logger", Log.class);
    logger = spy(logger);
    when(logger.isWarnEnabled()).thenReturn(Boolean.TRUE);
    final AtomicReference<String> logMessage = new AtomicReference<String>();
    doAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            logMessage.set((String) invocation.getArguments()[0]);
            return null;
        }
    }).when(logger).warn(Mockito.anyString());
    DirectFieldAccessor accessor = new DirectFieldAccessor(advice);
    accessor.setPropertyValue("logger", logger);

    pollingTask.call();
    assertFalse(called.get());
    assertNotNull(logMessage.get());
    assertTrue(logMessage.get()
            .endsWith("can only be used for MessageHandlers; " + "an attempt to advise method 'call' in "
                    + "'org.springframework.integration.endpoint.AbstractPollingEndpoint$1' is ignored"));
}

From source file:org.springframework.integration.handler.support.MessagingMethodInvokerHelper.java

private void findSingleSpecifMethodOnInterfacesIfProxy(final Object targetObject, final String methodName,
        Map<Class<?>, HandlerMethod> candidateMessageMethods, Map<Class<?>, HandlerMethod> candidateMethods) {
    if (AopUtils.isAopProxy(targetObject)) {
        final AtomicReference<Method> targetMethod = new AtomicReference<>();
        final AtomicReference<Class<?>> targetClass = new AtomicReference<>();
        Class<?>[] interfaces = ((Advised) targetObject).getProxiedInterfaces();
        for (Class<?> clazz : interfaces) {
            ReflectionUtils.doWithMethods(clazz, method1 -> {
                if (targetMethod.get() != null) {
                    throw new IllegalStateException("Ambiguous method " + methodName + " on " + targetObject);
                } else {
                    targetMethod.set(method1);
                    targetClass.set(clazz);
                }/* w  ww  . j  a  va 2  s .c o m*/
            }, method12 -> method12.getName().equals(methodName));
        }
        Method theMethod = targetMethod.get();
        if (theMethod != null) {
            theMethod = org.springframework.util.ClassUtils.getMostSpecificMethod(theMethod,
                    targetObject.getClass());
            InvocableHandlerMethod invocableHandlerMethod = this.messageHandlerMethodFactory
                    .createInvocableHandlerMethod(targetObject, theMethod);
            HandlerMethod handlerMethod = new HandlerMethod(invocableHandlerMethod, this.canProcessMessageList);
            checkSpelInvokerRequired(targetClass.get(), theMethod, handlerMethod);
            Class<?> targetParameterType = handlerMethod.getTargetParameterType();
            if (handlerMethod.isMessageMethod()) {
                if (candidateMessageMethods.containsKey(targetParameterType)) {
                    throw new IllegalArgumentException("Found more than one method match for type "
                            + "[Message<" + targetParameterType + ">]");
                }
                candidateMessageMethods.put(targetParameterType, handlerMethod);
            } else {
                if (candidateMethods.containsKey(targetParameterType)) {
                    String exceptionMessage = "Found more than one method match for ";
                    if (Void.class.equals(targetParameterType)) {
                        exceptionMessage += "empty parameter for 'payload'";
                    } else {
                        exceptionMessage += "type [" + targetParameterType + "]";
                    }
                    throw new IllegalArgumentException(exceptionMessage);
                }
                candidateMethods.put(targetParameterType, handlerMethod);
            }
        }
    }
}

From source file:org.springframework.integration.handler.support.MessagingMethodInvokerHelper.java

private Class<?> getTargetClass(Object targetObject) {
    Class<?> targetClass = targetObject.getClass();
    if (AopUtils.isAopProxy(targetObject)) {
        targetClass = AopUtils.getTargetClass(targetObject);
        if (targetClass == targetObject.getClass()) {
            try {
                // Maybe a proxy with no target - e.g. gateway
                Class<?>[] interfaces = ((Advised) targetObject).getProxiedInterfaces();
                if (interfaces != null && interfaces.length == 1) {
                    targetClass = interfaces[0];
                }//from w ww . j a va2s  .  com
            } catch (Exception e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Exception trying to extract interface", e);
                }
            }
        }
    } else if (org.springframework.util.ClassUtils.isCglibProxyClass(targetClass)
            || targetClass.getSimpleName().contains("$MockitoMock$")) {
        Class<?> superClass = targetObject.getClass().getSuperclass();
        if (!Object.class.equals(superClass)) {
            targetClass = superClass;
        }
    }
    return targetClass;
}

From source file:org.springframework.integration.util.MessagingMethodInvokerHelper.java

private Class<?> getTargetClass(Object targetObject) {
    Class<?> targetClass = targetObject.getClass();
    if (AopUtils.isAopProxy(targetObject)) {
        targetClass = AopUtils.getTargetClass(targetObject);
        if (targetClass == targetObject.getClass()) {
            try {
                // Maybe a proxy with no target - e.g. gateway
                Class<?>[] interfaces = ((Advised) targetObject).getProxiedInterfaces();
                if (interfaces != null && interfaces.length == 1) {
                    targetClass = interfaces[0];
                }/*w w w.j a va 2s.  co m*/
            } catch (Exception e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Exception trying to extract interface", e);
                }
            }
        }
    } else if (org.springframework.util.ClassUtils.isCglibProxyClass(targetClass)) {
        Class<?> superClass = targetObject.getClass().getSuperclass();
        if (!Object.class.equals(superClass)) {
            targetClass = superClass;
        }
    }
    return targetClass;
}

From source file:org.thingsboard.server.dao.service.BaseDeviceCredentialsCacheTest.java

private DeviceCredentialsService unwrapDeviceCredentialsService() throws Exception {
    if (AopUtils.isAopProxy(deviceCredentialsService) && deviceCredentialsService instanceof Advised) {
        Object target = ((Advised) deviceCredentialsService).getTargetSource().getTarget();
        return (DeviceCredentialsService) target;
    }// www .jav a 2  s.c om
    return null;
}