Search in sources :

Example 11 with AbstractReplyProducingMessageHandler

use of org.springframework.integration.handler.AbstractReplyProducingMessageHandler in project spring-integration by spring-projects.

the class AbstractMethodAnnotationPostProcessor method postProcess.

@Override
public Object postProcess(Object bean, String beanName, Method method, List<Annotation> annotations) {
    if (this.beanAnnotationAware() && AnnotatedElementUtils.isAnnotated(method, Bean.class.getName())) {
        try {
            resolveTargetBeanFromMethodWithBeanAnnotation(method);
        } catch (NoSuchBeanDefinitionException e) {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Skipping endpoint creation; " + e.getMessage() + "; perhaps due to some '@Conditional' annotation.");
            }
            return null;
        }
    }
    List<Advice> adviceChain = extractAdviceChain(beanName, annotations);
    MessageHandler handler = createHandler(bean, method, annotations);
    if (!CollectionUtils.isEmpty(adviceChain) && handler instanceof AbstractReplyProducingMessageHandler) {
        ((AbstractReplyProducingMessageHandler) handler).setAdviceChain(adviceChain);
    }
    if (handler instanceof Orderable) {
        Order orderAnnotation = AnnotationUtils.findAnnotation(method, Order.class);
        if (orderAnnotation != null) {
            ((Orderable) handler).setOrder(orderAnnotation.value());
        }
    }
    if (handler instanceof AbstractMessageProducingHandler || handler instanceof AbstractMessageRouter) {
        String sendTimeout = MessagingAnnotationUtils.resolveAttribute(annotations, "sendTimeout", String.class);
        if (sendTimeout != null) {
            Long value = Long.valueOf(this.beanFactory.resolveEmbeddedValue(sendTimeout));
            if (handler instanceof AbstractMessageProducingHandler) {
                ((AbstractMessageProducingHandler) handler).setSendTimeout(value);
            } else {
                ((AbstractMessageRouter) handler).setSendTimeout(value);
            }
        }
    }
    boolean handlerExists = false;
    if (this.beanAnnotationAware() && AnnotatedElementUtils.isAnnotated(method, Bean.class.getName())) {
        Object handlerBean = this.resolveTargetBeanFromMethodWithBeanAnnotation(method);
        handlerExists = handlerBean != null && handler == handlerBean;
    }
    if (!handlerExists) {
        String handlerBeanName = generateHandlerBeanName(beanName, method);
        if (handler instanceof ReplyProducingMessageHandlerWrapper && StringUtils.hasText(MessagingAnnotationUtils.endpointIdValue(method))) {
            handlerBeanName = handlerBeanName + ".wrapper";
        }
        this.beanFactory.registerSingleton(handlerBeanName, handler);
        handler = (MessageHandler) this.beanFactory.initializeBean(handler, handlerBeanName);
    }
    if (AnnotatedElementUtils.isAnnotated(method, IdempotentReceiver.class.getName()) && !AnnotatedElementUtils.isAnnotated(method, Bean.class.getName())) {
        String[] interceptors = AnnotationUtils.getAnnotation(method, IdempotentReceiver.class).value();
        for (String interceptor : interceptors) {
            DefaultBeanFactoryPointcutAdvisor advisor = new DefaultBeanFactoryPointcutAdvisor();
            advisor.setAdviceBeanName(interceptor);
            NameMatchMethodPointcut pointcut = new NameMatchMethodPointcut();
            pointcut.setMappedName("handleMessage");
            advisor.setPointcut(pointcut);
            advisor.setBeanFactory(this.beanFactory);
            if (handler instanceof Advised) {
                ((Advised) handler).addAdvisor(advisor);
            } else {
                ProxyFactory proxyFactory = new ProxyFactory(handler);
                proxyFactory.addAdvisor(advisor);
                handler = (MessageHandler) proxyFactory.getProxy(this.beanFactory.getBeanClassLoader());
            }
        }
    }
    if (!CollectionUtils.isEmpty(adviceChain)) {
        for (Advice advice : adviceChain) {
            if (advice instanceof HandleMessageAdvice) {
                NameMatchMethodPointcutAdvisor handlerAdvice = new NameMatchMethodPointcutAdvisor(advice);
                handlerAdvice.addMethodName("handleMessage");
                if (handler instanceof Advised) {
                    ((Advised) handler).addAdvisor(handlerAdvice);
                } else {
                    ProxyFactory proxyFactory = new ProxyFactory(handler);
                    proxyFactory.addAdvisor(handlerAdvice);
                    handler = (MessageHandler) proxyFactory.getProxy(this.beanFactory.getBeanClassLoader());
                }
            }
        }
    }
    AbstractEndpoint endpoint = createEndpoint(handler, method, annotations);
    if (endpoint != null) {
        return endpoint;
    }
    return handler;
}
Also used : Order(org.springframework.core.annotation.Order) AbstractEndpoint(org.springframework.integration.endpoint.AbstractEndpoint) HandleMessageAdvice(org.springframework.integration.handler.advice.HandleMessageAdvice) MessageHandler(org.springframework.messaging.MessageHandler) AbstractReplyProducingMessageHandler(org.springframework.integration.handler.AbstractReplyProducingMessageHandler) ProxyFactory(org.springframework.aop.framework.ProxyFactory) AbstractMessageRouter(org.springframework.integration.router.AbstractMessageRouter) Orderable(org.springframework.integration.context.Orderable) Bean(org.springframework.context.annotation.Bean) DefaultBeanFactoryPointcutAdvisor(org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor) Advised(org.springframework.aop.framework.Advised) NameMatchMethodPointcutAdvisor(org.springframework.aop.support.NameMatchMethodPointcutAdvisor) AbstractMessageProducingHandler(org.springframework.integration.handler.AbstractMessageProducingHandler) AbstractReplyProducingMessageHandler(org.springframework.integration.handler.AbstractReplyProducingMessageHandler) HandleMessageAdvice(org.springframework.integration.handler.advice.HandleMessageAdvice) Advice(org.aopalliance.aop.Advice) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) IdempotentReceiver(org.springframework.integration.annotation.IdempotentReceiver) ReplyProducingMessageHandlerWrapper(org.springframework.integration.handler.ReplyProducingMessageHandlerWrapper) NameMatchMethodPointcut(org.springframework.aop.support.NameMatchMethodPointcut)

Example 12 with AbstractReplyProducingMessageHandler

use of org.springframework.integration.handler.AbstractReplyProducingMessageHandler in project spring-integration by spring-projects.

the class ServiceActivatorAnnotationPostProcessor method createHandler.

@Override
protected MessageHandler createHandler(Object bean, Method method, List<Annotation> annotations) {
    AbstractReplyProducingMessageHandler serviceActivator;
    if (AnnotatedElementUtils.isAnnotated(method, Bean.class.getName())) {
        final Object target = this.resolveTargetBeanFromMethodWithBeanAnnotation(method);
        serviceActivator = this.extractTypeIfPossible(target, AbstractReplyProducingMessageHandler.class);
        if (serviceActivator == null) {
            if (target instanceof MessageHandler) {
                /*
					 * Return a reply-producing message handler so that we still get 'produced no reply' messages
					 * and the super class will inject the advice chain to advise the handler method if needed.
					 */
                return new ReplyProducingMessageHandlerWrapper((MessageHandler) target);
            } else {
                serviceActivator = new ServiceActivatingHandler(target);
            }
        } else {
            checkMessageHandlerAttributes(resolveTargetBeanName(method), annotations);
            return (MessageHandler) target;
        }
    } else {
        serviceActivator = new ServiceActivatingHandler(bean, method);
    }
    String requiresReply = MessagingAnnotationUtils.resolveAttribute(annotations, "requiresReply", String.class);
    if (StringUtils.hasText(requiresReply)) {
        serviceActivator.setRequiresReply(Boolean.parseBoolean(this.beanFactory.resolveEmbeddedValue(requiresReply)));
    }
    String isAsync = MessagingAnnotationUtils.resolveAttribute(annotations, "async", String.class);
    if (StringUtils.hasText(isAsync)) {
        serviceActivator.setAsync(Boolean.parseBoolean(this.beanFactory.resolveEmbeddedValue(isAsync)));
    }
    this.setOutputChannelIfPresent(annotations, serviceActivator);
    return serviceActivator;
}
Also used : AbstractReplyProducingMessageHandler(org.springframework.integration.handler.AbstractReplyProducingMessageHandler) MessageHandler(org.springframework.messaging.MessageHandler) AbstractReplyProducingMessageHandler(org.springframework.integration.handler.AbstractReplyProducingMessageHandler) ServiceActivatingHandler(org.springframework.integration.handler.ServiceActivatingHandler) Bean(org.springframework.context.annotation.Bean) ReplyProducingMessageHandlerWrapper(org.springframework.integration.handler.ReplyProducingMessageHandlerWrapper)

Example 13 with AbstractReplyProducingMessageHandler

use of org.springframework.integration.handler.AbstractReplyProducingMessageHandler in project spring-integration by spring-projects.

the class EnricherParserTests method integrationTest.

@Test
public void integrationTest() {
    QueueChannel output = context.getBean("output", QueueChannel.class);
    output.purge(null);
    SubscribableChannel requests = context.getBean("requests", SubscribableChannel.class);
    class Foo extends AbstractReplyProducingMessageHandler {

        @Override
        protected Object handleRequestMessage(Message<?> requestMessage) {
            return new Source("foo");
        }
    }
    Foo foo = new Foo();
    foo.setOutputChannel(context.getBean("replies", MessageChannel.class));
    requests.subscribe(foo);
    Target original = new Target();
    Message<?> request = MessageBuilder.withPayload(original).setHeader("sourceName", "test").setHeader("notOverwrite", "test").build();
    context.getBean("input", MessageChannel.class).send(request);
    Message<?> reply = output.receive(0);
    Target enriched = (Target) reply.getPayload();
    assertEquals("foo", enriched.getName());
    assertEquals(42, enriched.getAge());
    assertEquals(Gender.MALE, enriched.getGender());
    assertTrue(enriched.isMarried());
    assertNotSame(original, enriched);
    assertEquals(1, adviceCalled);
    MessageHeaders headers = reply.getHeaders();
    assertEquals("bar", headers.get("foo"));
    assertEquals(Gender.MALE, headers.get("testBean"));
    assertEquals("foo", headers.get("sourceName"));
    assertEquals("test", headers.get("notOverwrite"));
    requests.unsubscribe(foo);
    adviceCalled--;
}
Also used : QueueChannel(org.springframework.integration.channel.QueueChannel) Message(org.springframework.messaging.Message) GenericMessage(org.springframework.messaging.support.GenericMessage) MessageChannel(org.springframework.messaging.MessageChannel) AbstractReplyProducingMessageHandler(org.springframework.integration.handler.AbstractReplyProducingMessageHandler) MessageHeaders(org.springframework.messaging.MessageHeaders) SubscribableChannel(org.springframework.messaging.SubscribableChannel) Test(org.junit.Test)

Example 14 with AbstractReplyProducingMessageHandler

use of org.springframework.integration.handler.AbstractReplyProducingMessageHandler in project spring-integration by spring-projects.

the class AbstractSimpleMessageHandlerFactoryBean method createHandlerInternal.

protected final H createHandlerInternal() {
    synchronized (this.initializationMonitor) {
        if (this.initialized) {
            // There was a problem when this method was called already
            return null;
        }
        this.handler = createHandler();
        if (this.handler instanceof ApplicationContextAware && this.applicationContext != null) {
            ((ApplicationContextAware) this.handler).setApplicationContext(this.applicationContext);
        }
        if (this.handler instanceof BeanFactoryAware && getBeanFactory() != null) {
            ((BeanFactoryAware) this.handler).setBeanFactory(getBeanFactory());
        }
        if (this.handler instanceof BeanNameAware && this.beanName != null) {
            ((BeanNameAware) this.handler).setBeanName(this.beanName);
        }
        if (this.handler instanceof ApplicationEventPublisherAware && this.applicationEventPublisher != null) {
            ((ApplicationEventPublisherAware) this.handler).setApplicationEventPublisher(this.applicationEventPublisher);
        }
        if (this.handler instanceof MessageProducer && this.outputChannel != null) {
            ((MessageProducer) this.handler).setOutputChannel(this.outputChannel);
        }
        Object actualHandler = extractTarget(this.handler);
        if (actualHandler == null) {
            actualHandler = this.handler;
        }
        if (actualHandler instanceof IntegrationObjectSupport) {
            if (this.componentName != null) {
                ((IntegrationObjectSupport) actualHandler).setComponentName(this.componentName);
            }
            if (this.channelResolver != null) {
                ((IntegrationObjectSupport) actualHandler).setChannelResolver(this.channelResolver);
            }
        }
        if (!CollectionUtils.isEmpty(this.adviceChain)) {
            if (actualHandler instanceof AbstractReplyProducingMessageHandler) {
                ((AbstractReplyProducingMessageHandler) actualHandler).setAdviceChain(this.adviceChain);
            } else if (this.logger.isDebugEnabled()) {
                String name = this.componentName;
                if (name == null && actualHandler instanceof NamedComponent) {
                    name = ((NamedComponent) actualHandler).getComponentName();
                }
                this.logger.debug("adviceChain can only be set on an AbstractReplyProducingMessageHandler" + (name == null ? "" : (", " + name)) + ".");
            }
        }
        if (this.async != null) {
            if (actualHandler instanceof AbstractMessageProducingHandler) {
                ((AbstractMessageProducingHandler) actualHandler).setAsync(this.async);
            }
        }
        if (this.handler instanceof Orderable && this.order != null) {
            ((Orderable) this.handler).setOrder(this.order);
        }
        this.initialized = true;
    }
    if (this.handler instanceof InitializingBean) {
        try {
            ((InitializingBean) this.handler).afterPropertiesSet();
        } catch (Exception e) {
            throw new BeanInitializationException("failed to initialize MessageHandler", e);
        }
    }
    return this.handler;
}
Also used : BeanInitializationException(org.springframework.beans.factory.BeanInitializationException) ApplicationContextAware(org.springframework.context.ApplicationContextAware) IntegrationObjectSupport(org.springframework.integration.context.IntegrationObjectSupport) Orderable(org.springframework.integration.context.Orderable) ApplicationEventPublisherAware(org.springframework.context.ApplicationEventPublisherAware) NamedComponent(org.springframework.integration.support.context.NamedComponent) BeanInitializationException(org.springframework.beans.factory.BeanInitializationException) BeansException(org.springframework.beans.BeansException) BeanNameAware(org.springframework.beans.factory.BeanNameAware) BeanFactoryAware(org.springframework.beans.factory.BeanFactoryAware) AbstractMessageProducingHandler(org.springframework.integration.handler.AbstractMessageProducingHandler) AbstractReplyProducingMessageHandler(org.springframework.integration.handler.AbstractReplyProducingMessageHandler) MessageProducer(org.springframework.integration.core.MessageProducer) InitializingBean(org.springframework.beans.factory.InitializingBean)

Example 15 with AbstractReplyProducingMessageHandler

use of org.springframework.integration.handler.AbstractReplyProducingMessageHandler in project spring-integration by spring-projects.

the class ApplicationContextMessageBusTests method consumerSubscribedToErrorChannel.

@Test
public void consumerSubscribedToErrorChannel() throws InterruptedException {
    TestApplicationContext context = TestUtils.createTestApplicationContext();
    QueueChannel errorChannel = new QueueChannel();
    context.registerChannel(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME, errorChannel);
    final CountDownLatch latch = new CountDownLatch(1);
    AbstractReplyProducingMessageHandler handler = new AbstractReplyProducingMessageHandler() {

        @Override
        public Object handleRequestMessage(Message<?> message) {
            latch.countDown();
            return null;
        }
    };
    PollingConsumer endpoint = new PollingConsumer(errorChannel, handler);
    endpoint.setBeanFactory(mock(BeanFactory.class));
    context.registerEndpoint("testEndpoint", endpoint);
    context.refresh();
    errorChannel.send(new ErrorMessage(new RuntimeException("test-exception")));
    latch.await(1000, TimeUnit.MILLISECONDS);
    assertEquals("handler should have received error message", 0, latch.getCount());
    context.stop();
}
Also used : PollingConsumer(org.springframework.integration.endpoint.PollingConsumer) QueueChannel(org.springframework.integration.channel.QueueChannel) ErrorMessage(org.springframework.messaging.support.ErrorMessage) Message(org.springframework.messaging.Message) GenericMessage(org.springframework.messaging.support.GenericMessage) BeanFactory(org.springframework.beans.factory.BeanFactory) AbstractReplyProducingMessageHandler(org.springframework.integration.handler.AbstractReplyProducingMessageHandler) CountDownLatch(java.util.concurrent.CountDownLatch) ErrorMessage(org.springframework.messaging.support.ErrorMessage) TestApplicationContext(org.springframework.integration.test.util.TestUtils.TestApplicationContext) Test(org.junit.Test)

Aggregations

AbstractReplyProducingMessageHandler (org.springframework.integration.handler.AbstractReplyProducingMessageHandler)52 Test (org.junit.Test)46 BeanFactory (org.springframework.beans.factory.BeanFactory)37 QueueChannel (org.springframework.integration.channel.QueueChannel)29 Message (org.springframework.messaging.Message)28 DirectChannel (org.springframework.integration.channel.DirectChannel)23 GenericMessage (org.springframework.messaging.support.GenericMessage)20 Matchers.containsString (org.hamcrest.Matchers.containsString)19 ErrorMessage (org.springframework.messaging.support.ErrorMessage)18 ArrayList (java.util.ArrayList)14 AdviceMessage (org.springframework.integration.message.AdviceMessage)14 Advice (org.aopalliance.aop.Advice)13 HashMap (java.util.HashMap)12 MessageHandlingException (org.springframework.messaging.MessageHandlingException)12 Expression (org.springframework.expression.Expression)10 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)10 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)9 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)9 MessageHandlingExpressionEvaluatingAdviceException (org.springframework.integration.handler.advice.ExpressionEvaluatingRequestHandlerAdvice.MessageHandlingExpressionEvaluatingAdviceException)9 MessagingException (org.springframework.messaging.MessagingException)9