Example usage for org.springframework.integration.channel DirectChannel DirectChannel

List of usage examples for org.springframework.integration.channel DirectChannel DirectChannel

Introduction

In this page you can find the example usage for org.springframework.integration.channel DirectChannel DirectChannel.

Prototype

public DirectChannel() 

Source Link

Document

Create a channel with default RoundRobinLoadBalancingStrategy

Usage

From source file:org.springframework.integration.mail.ImapMailReceiverTests.java

@Test
public void testIdleChannelAdapterException() throws Exception {
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
            "ImapIdleChannelAdapterParserTests-context.xml", ImapIdleChannelAdapterParserTests.class);
    ImapIdleChannelAdapter adapter = context.getBean("simpleAdapter", ImapIdleChannelAdapter.class);

    //ImapMailReceiver receiver = (ImapMailReceiver) TestUtils.getPropertyValue(adapter, "mailReceiver");

    DirectChannel channel = new DirectChannel();
    channel.subscribe(new AbstractReplyProducingMessageHandler() {

        @Override//from   w ww. j  a  v a  2  s  .c  o m
        protected Object handleRequestMessage(org.springframework.messaging.Message<?> requestMessage) {
            throw new RuntimeException("Failed");
        }
    });
    adapter.setOutputChannel(channel);
    QueueChannel errorChannel = new QueueChannel();
    adapter.setErrorChannel(errorChannel);

    AbstractMailReceiver receiver = new ImapMailReceiver();
    receiver = spy(receiver);
    receiver.setBeanFactory(mock(BeanFactory.class));
    receiver.afterPropertiesSet();

    Field folderField = AbstractMailReceiver.class.getDeclaredField("folder");
    folderField.setAccessible(true);
    Folder folder = mock(IMAPFolder.class);
    given(folder.getPermanentFlags()).willReturn(new Flags(Flags.Flag.USER));
    folderField.set(receiver, folder);

    willAnswer(invocation -> true).given(folder).isOpen();

    willAnswer(invocation -> null).given(receiver).openFolder();

    DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter);
    adapterAccessor.setPropertyValue("mailReceiver", receiver);

    MimeMessage mailMessage = mock(MimeMessage.class);
    Flags flags = mock(Flags.class);
    given(mailMessage.getFlags()).willReturn(flags);
    final Message[] messages = new Message[] { mailMessage };

    willAnswer(invocation -> messages).given(receiver).searchForNewMessages();

    willAnswer(invocation -> null).given(receiver).fetchMessages(messages);

    adapter.start();
    org.springframework.messaging.Message<?> replMessage = errorChannel.receive(10000);
    assertNotNull(replMessage);
    assertEquals("Failed", ((Exception) replMessage.getPayload()).getCause().getMessage());
    adapter.stop();
    context.close();
}

From source file:org.springframework.integration.x.bus.MessageBusAwareChannelResolver.java

@Override
public MessageChannel resolveDestination(String name) {
    MessageChannel channel = null;//from  ww  w  .  j  a  v  a2  s  .c o m
    if (name.indexOf(":") != -1) {
        String channelName = name;
        channel = channels.get(channelName);
        if (channel == null && messageBus != null) {
            channel = new DirectChannel();
            messageBus.bindProducer(channelName, channel, true);
            channels.put(channelName, channel);
        }
    }
    if (channel == null) {
        channel = super.resolveDestination(name);
    }
    return channel;
}

From source file:org.springframework.integration.x.gemfire.GemFireMessageBus.java

private void doRegisterConsumer(String name, MessageChannel moduleInputChannel,
        final Collection<MediaType> acceptedMediaTypes, MessageProducerSupport adapter) {
    DirectChannel bridgeToModuleChannel = new DirectChannel();
    bridgeToModuleChannel.setBeanName(name + ".bridge");
    adapter.setOutputChannel(bridgeToModuleChannel);
    adapter.setBeanName("inbound." + name);
    adapter.afterPropertiesSet();/*from w w  w.j ava  2 s. c  o m*/
    addBinding(Binding.forConsumer(adapter, moduleInputChannel));
    GemFireRPCListener convertingBridge = new GemFireRPCListener(acceptedMediaTypes);
    convertingBridge.setOutputChannel(moduleInputChannel);
    convertingBridge.setBeanName(name + ".convert.bridge");
    convertingBridge.afterPropertiesSet();
    bridgeToModuleChannel.subscribe(convertingBridge);
    adapter.start();
}

From source file:org.springframework.integration.x.rabbit.RabbitChannelRegistry.java

@Override
public void createInbound(final String name, MessageChannel moduleInputChannel,
        final Collection<MediaType> acceptedMediaTypes, boolean aliasHint) {
    if (logger.isInfoEnabled()) {
        logger.info("declaring queue for inbound: " + name);
    }/*from  w w  w.j a  v  a 2 s.c  om*/
    this.rabbitAdmin.declareQueue(new Queue(name));
    SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer(
            this.connectionFactory);
    if (this.concurrentConsumers != null) {
        listenerContainer.setConcurrentConsumers(this.concurrentConsumers);
    }
    listenerContainer.setQueueNames(name);
    listenerContainer.afterPropertiesSet();
    AmqpInboundChannelAdapter adapter = new AmqpInboundChannelAdapter(listenerContainer);
    DirectChannel bridgeToModuleChannel = new DirectChannel();
    bridgeToModuleChannel.setBeanName(name + ".bridge");
    adapter.setOutputChannel(bridgeToModuleChannel);
    adapter.setHeaderMapper(this.mapper);
    adapter.setBeanName("inbound." + name);
    adapter.afterPropertiesSet();
    this.lifecycleBeans.add(adapter);
    ReceivingHandler convertingBridge = new ReceivingHandler(acceptedMediaTypes);
    convertingBridge.setOutputChannel(moduleInputChannel);
    convertingBridge.setBeanName(name + ".convert.bridge");
    convertingBridge.afterPropertiesSet();
    bridgeToModuleChannel.subscribe(convertingBridge);
    adapter.start();
}

From source file:org.springframework.integration.x.rabbit.RabbitChannelRegistry.java

@Override
public void tap(String tapModule, final String name, MessageChannel tapModuleInputChannel) {
    SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer(
            this.connectionFactory);
    if (this.concurrentConsumers != null) {
        listenerContainer.setConcurrentConsumers(this.concurrentConsumers);
    }//from  w  ww.  j  a  va 2s  .c o  m
    Queue queue = this.rabbitAdmin.declareQueue();
    Binding binding = BindingBuilder.bind(queue).to(new FanoutExchange("tap." + name));
    this.rabbitAdmin.declareBinding(binding);
    listenerContainer.setQueues(queue);
    listenerContainer.afterPropertiesSet();
    AmqpInboundChannelAdapter adapter = new AmqpInboundChannelAdapter(listenerContainer);
    DirectChannel bridgeToTapChannel = new DirectChannel();
    bridgeToTapChannel.setBeanName(tapModule + ".bridge");
    adapter.setOutputChannel(bridgeToTapChannel);
    adapter.setHeaderMapper(this.mapper);
    adapter.setBeanName("tap." + name);
    adapter.setComponentName(tapModule + "." + "tapAdapter");
    adapter.afterPropertiesSet();
    this.lifecycleBeans.add(adapter);
    // TODO: media types need to be passed in by Tap.
    Collection<MediaType> acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
    ReceivingHandler convertingBridge = new ReceivingHandler(acceptedMediaTypes);
    convertingBridge.setOutputChannel(tapModuleInputChannel);
    convertingBridge.setBeanName(name + ".convert.bridge");
    convertingBridge.afterPropertiesSet();
    bridgeToTapChannel.subscribe(convertingBridge);
    adapter.start();
}

From source file:org.springframework.integration.x.rabbit.RabbitMessageBus.java

private void doRegisterConsumer(String name, MessageChannel moduleInputChannel, Queue queue) {
    SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer(
            this.connectionFactory);
    if (this.concurrentConsumers != null) {
        listenerContainer.setConcurrentConsumers(this.concurrentConsumers);
    }//from   w w w  . j a  v a2  s .  co  m
    listenerContainer.setQueues(queue);
    Advice advice = new StatelessRetryOperationsInterceptorFactoryBean().getObject();
    listenerContainer.setAdviceChain(new Advice[] { advice });
    listenerContainer.afterPropertiesSet();
    AmqpInboundChannelAdapter adapter = new AmqpInboundChannelAdapter(listenerContainer);
    DirectChannel bridgeToModuleChannel = new DirectChannel();
    bridgeToModuleChannel.setBeanName(name + ".bridge");
    adapter.setOutputChannel(bridgeToModuleChannel);
    adapter.setHeaderMapper(this.mapper);
    adapter.setBeanName("inbound." + name);
    adapter.afterPropertiesSet();
    addBinding(Binding.forConsumer(adapter, moduleInputChannel));
    ReceivingHandler convertingBridge = new ReceivingHandler();
    convertingBridge.setOutputChannel(moduleInputChannel);
    convertingBridge.setBeanName(name + ".convert.bridge");
    convertingBridge.afterPropertiesSet();
    bridgeToModuleChannel.subscribe(convertingBridge);
    adapter.start();
}

From source file:org.springframework.integration.xmpp.inbound.ChatMessageListeningEndpointTests.java

@Test
public void testWithErrorChannel() throws NotConnectedException {
    DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
    XMPPConnection connection = mock(XMPPConnection.class);
    bf.registerSingleton(XmppContextUtils.XMPP_CONNECTION_BEAN_NAME, connection);

    ChatMessageListeningEndpoint endpoint = new ChatMessageListeningEndpoint();

    DirectChannel outChannel = new DirectChannel();
    outChannel.subscribe(message -> {
        throw new RuntimeException("ooops");
    });//w ww .j a v a 2s . c o m
    PollableChannel errorChannel = new QueueChannel();
    endpoint.setBeanFactory(bf);
    endpoint.setOutputChannel(outChannel);
    endpoint.setErrorChannel(errorChannel);
    endpoint.afterPropertiesSet();
    StanzaListener listener = (StanzaListener) TestUtils.getPropertyValue(endpoint, "stanzaListener");
    Message smackMessage = new Message("kermit@frog.com");
    smackMessage.setBody("hello");
    smackMessage.setThread("1234");
    listener.processPacket(smackMessage);

    ErrorMessage msg = (ErrorMessage) errorChannel.receive();
    assertEquals("hello", ((MessagingException) msg.getPayload()).getFailedMessage().getPayload());
}

From source file:org.springframework.xd.dirt.integration.bus.rabbit.RabbitMessageBusTests.java

@Test
public void testSendAndReceiveBad() throws Exception {
    MessageBus messageBus = getMessageBus();
    DirectChannel moduleOutputChannel = new DirectChannel();
    DirectChannel moduleInputChannel = new DirectChannel();
    messageBus.bindProducer("bad.0", moduleOutputChannel, null);
    messageBus.bindConsumer("bad.0", moduleInputChannel, null);
    Message<?> message = MessageBuilder.withPayload("bad").setHeader(MessageHeaders.CONTENT_TYPE, "foo/bar")
            .build();/*from w  w  w. j  a v  a 2 s . c  om*/
    final CountDownLatch latch = new CountDownLatch(3);
    moduleInputChannel.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            latch.countDown();
            throw new RuntimeException("bad");
        }
    });
    moduleOutputChannel.send(message);
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    messageBus.unbindConsumers("bad.0");
    messageBus.unbindProducers("bad.0");
}

From source file:org.springframework.xd.dirt.integration.bus.rabbit.RabbitMessageBusTests.java

@Test
public void testConsumerProperties() throws Exception {
    MessageBus bus = getMessageBus();/*from   w  w w.j  av  a2 s.  c om*/
    Properties properties = new Properties();
    properties.put("transacted", "true"); // test transacted with defaults; not allowed with ackmode NONE
    bus.bindConsumer("props.0", new DirectChannel(), properties);
    @SuppressWarnings("unchecked")
    List<Binding> bindings = TestUtils.getPropertyValue(bus, "messageBus.bindings", List.class);
    assertEquals(1, bindings.size());
    AbstractEndpoint endpoint = bindings.get(0).getEndpoint();
    SimpleMessageListenerContainer container = TestUtils.getPropertyValue(endpoint, "messageListenerContainer",
            SimpleMessageListenerContainer.class);
    assertEquals(AcknowledgeMode.AUTO, container.getAcknowledgeMode());
    assertEquals("xdbus.props.0", container.getQueueNames()[0]);
    assertTrue(TestUtils.getPropertyValue(container, "transactional", Boolean.class));
    assertEquals(1, TestUtils.getPropertyValue(container, "concurrentConsumers"));
    assertNull(TestUtils.getPropertyValue(container, "maxConcurrentConsumers"));
    assertTrue(TestUtils.getPropertyValue(container, "defaultRequeueRejected", Boolean.class));
    assertEquals(1, TestUtils.getPropertyValue(container, "prefetchCount"));
    assertEquals(1, TestUtils.getPropertyValue(container, "txSize"));
    Advice retry = TestUtils.getPropertyValue(container, "adviceChain", Advice[].class)[0];
    assertEquals(3, TestUtils.getPropertyValue(retry, "retryOperations.retryPolicy.maxAttempts"));
    assertEquals(1000L, TestUtils.getPropertyValue(retry, "retryOperations.backOffPolicy.initialInterval"));
    assertEquals(10000L, TestUtils.getPropertyValue(retry, "retryOperations.backOffPolicy.maxInterval"));
    assertEquals(2.0, TestUtils.getPropertyValue(retry, "retryOperations.backOffPolicy.multiplier"));
    bus.unbindConsumers("props.0");
    assertEquals(0, bindings.size());

    properties = new Properties();
    properties.put("ackMode", "NONE");
    properties.put("backOffInitialInterval", "2000");
    properties.put("backOffMaxInterval", "20000");
    properties.put("backOffMultiplier", "5.0");
    properties.put("concurrency", "2");
    properties.put("maxAttempts", "23");
    properties.put("maxConcurrency", "3");
    properties.put("prefix", "foo.");
    properties.put("prefetch", "20");
    properties.put("requestHeaderPatterns", "foo");
    properties.put("requeue", "false");
    properties.put("txSize", "10");
    properties.put("partitionIndex", 0);
    bus.bindConsumer("props.0", new DirectChannel(), properties);

    @SuppressWarnings("unchecked")
    List<Binding> bindingsNow = TestUtils.getPropertyValue(bus, "messageBus.bindings", List.class);
    assertEquals(1, bindingsNow.size());
    endpoint = bindingsNow.get(0).getEndpoint();
    container = verifyContainer(endpoint);

    assertEquals("foo.props.0", container.getQueueNames()[0]);

    try {
        bus.bindPubSubConsumer("dummy", null, properties);
        fail("Expected exception");
    } catch (IllegalArgumentException e) {
        assertThat(e.getMessage(),
                allOf(containsString("RabbitMessageBus does not support consumer properties: "),
                        containsString("partitionIndex"), containsString("concurrency"),
                        containsString(" for dummy.")));
    }
    try {
        bus.bindConsumer("queue:dummy", null, properties);
        fail("Expected exception");
    } catch (IllegalArgumentException e) {
        assertEquals("RabbitMessageBus does not support consumer property: partitionIndex for queue:dummy.",
                e.getMessage());
    }

    bus.unbindConsumers("props.0");
    assertEquals(0, bindingsNow.size());
}

From source file:org.springframework.xd.dirt.integration.bus.rabbit.RabbitMessageBusTests.java

@Test
public void testProducerProperties() throws Exception {
    MessageBus bus = getMessageBus();//from  w  w w. j  a v  a 2  s .co m
    bus.bindProducer("props.0", new DirectChannel(), null);
    @SuppressWarnings("unchecked")
    List<Binding> bindings = TestUtils.getPropertyValue(bus, "messageBus.bindings", List.class);
    assertEquals(1, bindings.size());
    AbstractEndpoint endpoint = bindings.get(0).getEndpoint();
    assertEquals("xdbus.props.0", TestUtils.getPropertyValue(endpoint, "handler.delegate.routingKey"));
    MessageDeliveryMode mode = TestUtils.getPropertyValue(endpoint, "handler.delegate.defaultDeliveryMode",
            MessageDeliveryMode.class);
    assertEquals(MessageDeliveryMode.PERSISTENT, mode);
    List<?> requestHeaders = TestUtils.getPropertyValue(endpoint,
            "handler.delegate.headerMapper.requestHeaderMatcher.strategies", List.class);
    assertEquals(2, requestHeaders.size());
    bus.unbindProducers("props.0");
    assertEquals(0, bindings.size());

    Properties properties = new Properties();
    properties.put("prefix", "foo.");
    properties.put("deliveryMode", "NON_PERSISTENT");
    properties.put("requestHeaderPatterns", "foo");
    properties.put("partitionKeyExpression", "'foo'");
    properties.put("partitionKeyExtractorClass", "foo");
    properties.put("partitionSelectorExpression", "0");
    properties.put("partitionSelectorClass", "foo");
    properties.put(BusProperties.NEXT_MODULE_COUNT, "1");

    bus.bindProducer("props.0", new DirectChannel(), properties);
    assertEquals(1, bindings.size());
    endpoint = bindings.get(0).getEndpoint();
    assertEquals("'foo.props.0-' + headers['partition']",
            TestUtils.getPropertyValue(endpoint, "handler.delegate.routingKeyExpression", SpelExpression.class)
                    .getExpressionString());
    mode = TestUtils.getPropertyValue(endpoint, "handler.delegate.defaultDeliveryMode",
            MessageDeliveryMode.class);
    assertEquals(MessageDeliveryMode.NON_PERSISTENT, mode);
    verifyFooRequestProducer(endpoint);

    try {
        bus.bindPubSubProducer("dummy", new DirectChannel(), properties);
        fail("Expected exception");
    } catch (IllegalArgumentException e) {
        assertThat(e.getMessage(),
                allOf(containsString("RabbitMessageBus does not support producer properties: "),
                        containsString("partitionSelectorExpression"),
                        containsString("partitionKeyExtractorClass"), containsString("partitionKeyExpression"),
                        containsString("partitionSelectorClass")));
        assertThat(e.getMessage(), containsString("for dummy."));
    }
    try {
        bus.bindProducer("queue:dummy", new DirectChannel(), properties);
        fail("Expected exception");
    } catch (IllegalArgumentException e) {
        assertThat(e.getMessage(),
                allOf(containsString("RabbitMessageBus does not support producer properties: "),
                        containsString("partitionSelectorExpression"),
                        containsString("partitionKeyExtractorClass"), containsString("partitionKeyExpression"),
                        containsString("partitionSelectorClass")));
        assertThat(e.getMessage(), containsString("for queue:dummy."));
    }

    bus.unbindProducers("props.0");
    assertEquals(0, bindings.size());
}