Search in sources :

Example 6 with DirectChannel

use of org.springframework.integration.channel.DirectChannel in project spring-integration by spring-projects.

the class ServiceActivatorDefaultFrameworkMethodTests method testAsyncWithDirectReply.

@Test
public void testAsyncWithDirectReply() {
    DirectChannel replyChannel = new DirectChannel();
    final AtomicReference<Message<?>> reply = new AtomicReference<Message<?>>();
    replyChannel.subscribe(reply::set);
    Message<?> message = MessageBuilder.withPayload("testing").setReplyChannel(replyChannel).build();
    this.asyncIn.send(message);
    assertNull(reply.get());
    this.asyncService.future.set(this.asyncService.payload.toUpperCase());
    assertNotNull(reply.get());
    assertEquals("TESTING", reply.get().getPayload());
}
Also used : ErrorMessage(org.springframework.messaging.support.ErrorMessage) Message(org.springframework.messaging.Message) DirectChannel(org.springframework.integration.channel.DirectChannel) AtomicReference(java.util.concurrent.atomic.AtomicReference) Test(org.junit.Test)

Example 7 with DirectChannel

use of org.springframework.integration.channel.DirectChannel in project spring-integration by spring-projects.

the class NestedGatewayTests method nestedWithinHandler.

@Test
public void nestedWithinHandler() {
    DirectChannel innerChannel = new DirectChannel();
    DirectChannel outerChannel = new DirectChannel();
    innerChannel.subscribe(new AbstractReplyProducingMessageHandler() {

        @Override
        protected Object handleRequestMessage(Message<?> requestMessage) {
            return requestMessage.getPayload() + "-reply";
        }
    });
    final MessagingGatewaySupport innerGateway = new MessagingGatewaySupport() {
    };
    innerGateway.setRequestChannel(innerChannel);
    innerGateway.setBeanFactory(mock(BeanFactory.class));
    innerGateway.afterPropertiesSet();
    outerChannel.subscribe(new AbstractReplyProducingMessageHandler() {

        @Override
        protected Object handleRequestMessage(Message<?> requestMessage) {
            return innerGateway.sendAndReceiveMessage("pre-" + requestMessage.getPayload()).getPayload() + "-post";
        }
    });
    MessagingGatewaySupport outerGateway = new MessagingGatewaySupport() {
    };
    outerGateway.setRequestChannel(outerChannel);
    outerGateway.setBeanFactory(mock(BeanFactory.class));
    outerGateway.afterPropertiesSet();
    Message<?> reply = outerGateway.sendAndReceiveMessage("test");
    assertEquals("pre-test-reply-post", reply.getPayload());
}
Also used : DirectChannel(org.springframework.integration.channel.DirectChannel) BeanFactory(org.springframework.beans.factory.BeanFactory) AbstractReplyProducingMessageHandler(org.springframework.integration.handler.AbstractReplyProducingMessageHandler) Test(org.junit.Test)

Example 8 with DirectChannel

use of org.springframework.integration.channel.DirectChannel in project spring-integration by spring-projects.

the class InboundEndpointTests method testRetryWithinOnMessageGateway.

@Test
public void testRetryWithinOnMessageGateway() throws Exception {
    ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
    AbstractMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
    AmqpInboundGateway adapter = new AmqpInboundGateway(container);
    adapter.setRequestChannel(new DirectChannel());
    adapter.setRetryTemplate(new RetryTemplate());
    QueueChannel errors = new QueueChannel();
    ErrorMessageSendingRecoverer recoveryCallback = new ErrorMessageSendingRecoverer(errors);
    recoveryCallback.setErrorMessageStrategy(new AmqpMessageHeaderErrorMessageStrategy());
    adapter.setRecoveryCallback(recoveryCallback);
    adapter.afterPropertiesSet();
    ChannelAwareMessageListener listener = (ChannelAwareMessageListener) container.getMessageListener();
    listener.onMessage(org.springframework.amqp.core.MessageBuilder.withBody("foo".getBytes()).andProperties(new MessageProperties()).build(), null);
    Message<?> errorMessage = errors.receive(0);
    assertNotNull(errorMessage);
    assertThat(errorMessage.getPayload(), instanceOf(MessagingException.class));
    MessagingException payload = (MessagingException) errorMessage.getPayload();
    assertThat(payload.getMessage(), containsString("Dispatcher has no"));
    assertThat(StaticMessageHeaderAccessor.getDeliveryAttempt(payload.getFailedMessage()).get(), equalTo(3));
    org.springframework.amqp.core.Message amqpMessage = errorMessage.getHeaders().get(AmqpMessageHeaderErrorMessageStrategy.AMQP_RAW_MESSAGE, org.springframework.amqp.core.Message.class);
    assertThat(amqpMessage, notNullValue());
    assertNull(errors.receive(0));
}
Also used : QueueChannel(org.springframework.integration.channel.QueueChannel) DirectChannel(org.springframework.integration.channel.DirectChannel) MessagingException(org.springframework.messaging.MessagingException) SimpleMessageListenerContainer(org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer) ChannelAwareMessageListener(org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener) ConnectionFactory(org.springframework.amqp.rabbit.connection.ConnectionFactory) RetryTemplate(org.springframework.retry.support.RetryTemplate) MessageProperties(org.springframework.amqp.core.MessageProperties) ErrorMessageSendingRecoverer(org.springframework.integration.handler.advice.ErrorMessageSendingRecoverer) AmqpMessageHeaderErrorMessageStrategy(org.springframework.integration.amqp.support.AmqpMessageHeaderErrorMessageStrategy) AbstractMessageListenerContainer(org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer) Test(org.junit.Test)

Example 9 with DirectChannel

use of org.springframework.integration.channel.DirectChannel in project spring-integration by spring-projects.

the class InboundEndpointTests method testRetryWithinOnMessageAdapter.

@Test
public void testRetryWithinOnMessageAdapter() throws Exception {
    ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
    AbstractMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
    AmqpInboundChannelAdapter adapter = new AmqpInboundChannelAdapter(container);
    adapter.setOutputChannel(new DirectChannel());
    adapter.setRetryTemplate(new RetryTemplate());
    QueueChannel errors = new QueueChannel();
    ErrorMessageSendingRecoverer recoveryCallback = new ErrorMessageSendingRecoverer(errors);
    recoveryCallback.setErrorMessageStrategy(new AmqpMessageHeaderErrorMessageStrategy());
    adapter.setRecoveryCallback(recoveryCallback);
    adapter.afterPropertiesSet();
    ChannelAwareMessageListener listener = (ChannelAwareMessageListener) container.getMessageListener();
    listener.onMessage(org.springframework.amqp.core.MessageBuilder.withBody("foo".getBytes()).andProperties(new MessageProperties()).build(), null);
    Message<?> errorMessage = errors.receive(0);
    assertNotNull(errorMessage);
    assertThat(errorMessage.getPayload(), instanceOf(MessagingException.class));
    MessagingException payload = (MessagingException) errorMessage.getPayload();
    assertThat(payload.getMessage(), containsString("Dispatcher has no"));
    assertThat(StaticMessageHeaderAccessor.getDeliveryAttempt(payload.getFailedMessage()).get(), equalTo(3));
    org.springframework.amqp.core.Message amqpMessage = errorMessage.getHeaders().get(AmqpMessageHeaderErrorMessageStrategy.AMQP_RAW_MESSAGE, org.springframework.amqp.core.Message.class);
    assertThat(amqpMessage, notNullValue());
    assertNull(errors.receive(0));
}
Also used : QueueChannel(org.springframework.integration.channel.QueueChannel) DirectChannel(org.springframework.integration.channel.DirectChannel) MessagingException(org.springframework.messaging.MessagingException) SimpleMessageListenerContainer(org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer) ChannelAwareMessageListener(org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener) ConnectionFactory(org.springframework.amqp.rabbit.connection.ConnectionFactory) RetryTemplate(org.springframework.retry.support.RetryTemplate) MessageProperties(org.springframework.amqp.core.MessageProperties) ErrorMessageSendingRecoverer(org.springframework.integration.handler.advice.ErrorMessageSendingRecoverer) AmqpMessageHeaderErrorMessageStrategy(org.springframework.integration.amqp.support.AmqpMessageHeaderErrorMessageStrategy) AbstractMessageListenerContainer(org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer) Test(org.junit.Test)

Example 10 with DirectChannel

use of org.springframework.integration.channel.DirectChannel in project spring-integration by spring-projects.

the class PointToPointChannelParser method buildBeanDefinition.

@Override
protected BeanDefinitionBuilder buildBeanDefinition(Element element, ParserContext parserContext) {
    BeanDefinitionBuilder builder = null;
    Element queueElement = null;
    String fixedSubscriberChannel = element.getAttribute("fixed-subscriber");
    boolean isFixedSubscriber = "true".equals(fixedSubscriberChannel.trim().toLowerCase());
    // configure a queue-based channel if any queue sub-element is defined
    String channel = element.getAttribute(ID_ATTRIBUTE);
    if ((queueElement = DomUtils.getChildElementByTagName(element, "queue")) != null) {
        builder = BeanDefinitionBuilder.genericBeanDefinition(QueueChannel.class);
        boolean hasStoreRef = this.parseStoreRef(builder, queueElement, channel, false);
        boolean hasQueueRef = this.parseQueueRef(builder, queueElement);
        if (!hasStoreRef || !hasQueueRef) {
            boolean hasCapacity = this.parseQueueCapacity(builder, queueElement);
            if (hasCapacity && hasQueueRef) {
                parserContext.getReaderContext().error("The 'capacity' attribute is not allowed when providing a 'ref' to a custom queue.", element);
            }
            if (hasCapacity && hasStoreRef) {
                parserContext.getReaderContext().error("The 'capacity' attribute is not allowed" + " when providing a 'message-store' to a custom MessageGroupStore.", element);
            }
        }
        if (hasStoreRef && hasQueueRef) {
            parserContext.getReaderContext().error("The 'message-store' attribute is not allowed when providing a 'ref' to a custom queue.", element);
        }
    } else if ((queueElement = DomUtils.getChildElementByTagName(element, "priority-queue")) != null) {
        builder = BeanDefinitionBuilder.genericBeanDefinition(PriorityChannel.class);
        boolean hasCapacity = this.parseQueueCapacity(builder, queueElement);
        String comparatorRef = queueElement.getAttribute("comparator");
        if (StringUtils.hasText(comparatorRef)) {
            builder.addConstructorArgReference(comparatorRef);
        }
        if (parseStoreRef(builder, queueElement, channel, true)) {
            if (StringUtils.hasText(comparatorRef)) {
                parserContext.getReaderContext().error("The 'message-store' attribute is not allowed" + " when providing a 'comparator' to a priority queue.", element);
            }
            if (hasCapacity) {
                parserContext.getReaderContext().error("The 'capacity' attribute is not allowed" + " when providing a 'message-store' to a custom MessageGroupStore.", element);
            }
        }
    } else if ((queueElement = DomUtils.getChildElementByTagName(element, "rendezvous-queue")) != null) {
        builder = BeanDefinitionBuilder.genericBeanDefinition(RendezvousChannel.class);
    }
    Element dispatcherElement = DomUtils.getChildElementByTagName(element, "dispatcher");
    // verify that a dispatcher is not provided if a queue sub-element exists
    if (queueElement != null && dispatcherElement != null) {
        parserContext.getReaderContext().error("The 'dispatcher' sub-element and any queue sub-element are mutually exclusive.", element);
        return null;
    }
    if (queueElement != null) {
        if (isFixedSubscriber) {
            parserContext.getReaderContext().error("The 'fixed-subscriber' attribute is not allowed when a <queue/> child element is present.", element);
        }
        return builder;
    }
    if (dispatcherElement == null) {
        // configure the default DirectChannel with a RoundRobinLoadBalancingStrategy
        builder = BeanDefinitionBuilder.genericBeanDefinition(isFixedSubscriber ? FixedSubscriberChannel.class : DirectChannel.class);
    } else {
        if (isFixedSubscriber) {
            parserContext.getReaderContext().error("The 'fixed-subscriber' attribute is not allowed" + " when a <dispatcher/> child element is present.", element);
        }
        // configure either an ExecutorChannel or DirectChannel based on existence of 'task-executor'
        String taskExecutor = dispatcherElement.getAttribute("task-executor");
        if (StringUtils.hasText(taskExecutor)) {
            builder = BeanDefinitionBuilder.genericBeanDefinition(ExecutorChannel.class);
            builder.addConstructorArgReference(taskExecutor);
        } else {
            builder = BeanDefinitionBuilder.genericBeanDefinition(DirectChannel.class);
        }
        // unless the 'load-balancer' attribute is explicitly set to 'none'
        // or 'load-balancer-ref' is explicitly configured,
        // configure the default RoundRobinLoadBalancingStrategy
        String loadBalancer = dispatcherElement.getAttribute("load-balancer");
        String loadBalancerRef = dispatcherElement.getAttribute("load-balancer-ref");
        if (StringUtils.hasText(loadBalancer) && StringUtils.hasText(loadBalancerRef)) {
            parserContext.getReaderContext().error("'load-balancer' and 'load-balancer-ref' are mutually exclusive", element);
        }
        if (StringUtils.hasText(loadBalancerRef)) {
            builder.addConstructorArgReference(loadBalancerRef);
        } else {
            if ("none".equals(loadBalancer)) {
                builder.addConstructorArgValue(null);
            }
        }
        IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, dispatcherElement, "failover");
        IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, dispatcherElement, "max-subscribers");
    }
    return builder;
}
Also used : RendezvousChannel(org.springframework.integration.channel.RendezvousChannel) ExecutorChannel(org.springframework.integration.channel.ExecutorChannel) BeanDefinitionBuilder(org.springframework.beans.factory.support.BeanDefinitionBuilder) QueueChannel(org.springframework.integration.channel.QueueChannel) DirectChannel(org.springframework.integration.channel.DirectChannel) Element(org.w3c.dom.Element)

Aggregations

DirectChannel (org.springframework.integration.channel.DirectChannel)207 Test (org.junit.Test)179 Message (org.springframework.messaging.Message)62 MessageChannel (org.springframework.messaging.MessageChannel)60 QueueChannel (org.springframework.integration.channel.QueueChannel)58 BeanFactory (org.springframework.beans.factory.BeanFactory)45 GenericMessage (org.springframework.messaging.support.GenericMessage)37 MessageHandler (org.springframework.messaging.MessageHandler)32 ClassPathXmlApplicationContext (org.springframework.context.support.ClassPathXmlApplicationContext)28 ConfigurableApplicationContext (org.springframework.context.ConfigurableApplicationContext)26 CountDownLatch (java.util.concurrent.CountDownLatch)25 AbstractReplyProducingMessageHandler (org.springframework.integration.handler.AbstractReplyProducingMessageHandler)23 EventDrivenConsumer (org.springframework.integration.endpoint.EventDrivenConsumer)22 HashMap (java.util.HashMap)20 BindingProperties (org.springframework.cloud.stream.config.BindingProperties)19 MessagingException (org.springframework.messaging.MessagingException)18 SubscribableChannel (org.springframework.messaging.SubscribableChannel)16 Properties (java.util.Properties)15 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)15 Expression (org.springframework.expression.Expression)14