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

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

Introduction

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

Prototype

@Override
    public final void setBeanName(String beanName) 

Source Link

Usage

From source file:org.springframework.integration.amqp.outbound.AsyncAmqpGatewayTests.java

@Test
public void testConfirmsAndReturns() throws Exception {
    CachingConnectionFactory ccf = new CachingConnectionFactory("localhost");
    ccf.setPublisherConfirms(true);//  w w w .j  av a 2 s . c o m
    ccf.setPublisherReturns(true);
    RabbitTemplate template = new RabbitTemplate(ccf);
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(ccf);
    container.setBeanName("replyContainer");
    container.setQueueNames("asyncRQ1");
    container.afterPropertiesSet();
    container.start();
    AsyncRabbitTemplate asyncTemplate = new AsyncRabbitTemplate(template, container);
    asyncTemplate.setEnableConfirms(true);
    asyncTemplate.setMandatory(true);

    SimpleMessageListenerContainer receiver = new SimpleMessageListenerContainer(ccf);
    receiver.setBeanName("receiver");
    receiver.setQueueNames("asyncQ1");
    final CountDownLatch waitForAckBeforeReplying = new CountDownLatch(1);
    MessageListenerAdapter messageListener = new MessageListenerAdapter(
            (ReplyingMessageListener<String, String>) foo -> {
                try {
                    waitForAckBeforeReplying.await(10, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                return foo.toUpperCase();
            });
    receiver.setMessageListener(messageListener);
    receiver.afterPropertiesSet();
    receiver.start();

    AsyncAmqpOutboundGateway gateway = new AsyncAmqpOutboundGateway(asyncTemplate);
    Log logger = spy(TestUtils.getPropertyValue(gateway, "logger", Log.class));
    given(logger.isDebugEnabled()).willReturn(true);
    final CountDownLatch replyTimeoutLatch = new CountDownLatch(1);
    willAnswer(invocation -> {
        invocation.callRealMethod();
        replyTimeoutLatch.countDown();
        return null;
    }).given(logger).debug(startsWith("Reply not required and async timeout for"));
    new DirectFieldAccessor(gateway).setPropertyValue("logger", logger);
    QueueChannel outputChannel = new QueueChannel();
    outputChannel.setBeanName("output");
    QueueChannel returnChannel = new QueueChannel();
    returnChannel.setBeanName("returns");
    QueueChannel ackChannel = new QueueChannel();
    ackChannel.setBeanName("acks");
    QueueChannel errorChannel = new QueueChannel();
    errorChannel.setBeanName("errors");
    gateway.setOutputChannel(outputChannel);
    gateway.setReturnChannel(returnChannel);
    gateway.setConfirmAckChannel(ackChannel);
    gateway.setConfirmNackChannel(ackChannel);
    gateway.setConfirmCorrelationExpressionString("#this");
    gateway.setExchangeName("");
    gateway.setRoutingKey("asyncQ1");
    gateway.setBeanFactory(mock(BeanFactory.class));
    gateway.afterPropertiesSet();
    gateway.start();

    Message<?> message = MessageBuilder.withPayload("foo").setErrorChannel(errorChannel).build();

    gateway.handleMessage(message);

    Message<?> ack = ackChannel.receive(10000);
    assertNotNull(ack);
    assertEquals("foo", ack.getPayload());
    assertEquals(true, ack.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM));
    waitForAckBeforeReplying.countDown();

    Message<?> received = outputChannel.receive(10000);
    assertNotNull(received);
    assertEquals("FOO", received.getPayload());

    // timeout tests
    asyncTemplate.setReceiveTimeout(10);

    receiver.setMessageListener(message1 -> {
    });
    // reply timeout with no requiresReply
    message = MessageBuilder.withPayload("bar").setErrorChannel(errorChannel).build();
    gateway.handleMessage(message);
    assertTrue(replyTimeoutLatch.await(10, TimeUnit.SECONDS));

    // reply timeout with requiresReply
    gateway.setRequiresReply(true);
    message = MessageBuilder.withPayload("baz").setErrorChannel(errorChannel).build();
    gateway.handleMessage(message);

    received = errorChannel.receive(10000);
    assertThat(received, instanceOf(ErrorMessage.class));
    ErrorMessage error = (ErrorMessage) received;
    assertThat(error.getPayload(), instanceOf(MessagingException.class));
    assertThat(error.getPayload().getCause(), instanceOf(AmqpReplyTimeoutException.class));
    asyncTemplate.setReceiveTimeout(30000);
    receiver.setMessageListener(messageListener);

    // error on sending result
    DirectChannel errorForce = new DirectChannel();
    errorForce.setBeanName("errorForce");
    errorForce.subscribe(message1 -> {
        throw new RuntimeException("intentional");
    });
    gateway.setOutputChannel(errorForce);
    message = MessageBuilder.withPayload("qux").setErrorChannel(errorChannel).build();
    gateway.handleMessage(message);
    received = errorChannel.receive(10000);
    assertThat(received, instanceOf(ErrorMessage.class));
    error = (ErrorMessage) received;
    assertThat(error.getPayload(), instanceOf(MessagingException.class));
    assertEquals("QUX", ((MessagingException) error.getPayload()).getFailedMessage().getPayload());

    gateway.setRoutingKey(UUID.randomUUID().toString());
    message = MessageBuilder.withPayload("fiz").setErrorChannel(errorChannel).build();
    gateway.handleMessage(message);
    Message<?> returned = returnChannel.receive(10000);
    assertNotNull(returned);
    assertEquals("fiz", returned.getPayload());
    ackChannel.receive(10000);
    ackChannel.purge(null);

    asyncTemplate = mock(AsyncRabbitTemplate.class);
    RabbitMessageFuture future = asyncTemplate.new RabbitMessageFuture(null, null);
    willReturn(future).given(asyncTemplate).sendAndReceive(anyString(), anyString(),
            any(org.springframework.amqp.core.Message.class));
    DirectFieldAccessor dfa = new DirectFieldAccessor(future);
    dfa.setPropertyValue("nackCause", "nacknack");
    SettableListenableFuture<Boolean> confirmFuture = new SettableListenableFuture<Boolean>();
    confirmFuture.set(false);
    dfa.setPropertyValue("confirm", confirmFuture);
    new DirectFieldAccessor(gateway).setPropertyValue("template", asyncTemplate);

    message = MessageBuilder.withPayload("buz").setErrorChannel(errorChannel).build();
    gateway.handleMessage(message);

    ack = ackChannel.receive(10000);
    assertNotNull(ack);
    assertEquals("buz", ack.getPayload());
    assertEquals("nacknack", ack.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM_NACK_CAUSE));
    assertEquals(false, ack.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM));

    asyncTemplate.stop();
    receiver.stop();
    ccf.destroy();
}

From source file:org.springframework.integration.channel.P2pChannelTests.java

@Test
public void testDirectChannelLoggingWithMoreThenOneSubscriber() {
    final DirectChannel channel = new DirectChannel();
    channel.setBeanName("directChannel");

    verifySubscriptions(channel);/*from w  w w  .ja  v a2 s.  c  om*/
}

From source file:org.springframework.integration.jdbc.JdbcMessageStoreTests.java

@Test
@Transactional//from  w w  w. j  a v a2 s.  c  o  m
public void testWithMessageHistory() throws Exception {

    Message<?> message = new GenericMessage<String>("Hello");
    DirectChannel fooChannel = new DirectChannel();
    fooChannel.setBeanName("fooChannel");
    DirectChannel barChannel = new DirectChannel();
    barChannel.setBeanName("barChannel");

    message = MessageHistory.write(message, fooChannel);
    message = MessageHistory.write(message, barChannel);
    messageStore.addMessage(message);
    message = messageStore.getMessage(message.getHeaders().getId());
    MessageHistory messageHistory = MessageHistory.read(message);
    assertNotNull(messageHistory);
    assertEquals(2, messageHistory.size());
    Properties fooChannelHistory = messageHistory.get(0);
    assertEquals("fooChannel", fooChannelHistory.get("name"));
    assertEquals("channel", fooChannelHistory.get("type"));
}

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 www .j a  va 2 s.  com*/
    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 ww  . j a v  a  2  s  .c o  m
    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.ja  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 va  2  s  .c  o 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.xd.dirt.integration.bus.rabbit.RabbitMessageBusTests.java

@Test
public void testDurablePubSubWithAutoBindDLQ() throws Exception {
    RabbitAdmin admin = new RabbitAdmin(this.rabbitAvailableRule.getResource());

    MessageBus bus = getMessageBus();//from w  w  w.  ja v a 2s .co m
    Properties properties = new Properties();
    properties.put("prefix", "xdbustest.");
    properties.put("autoBindDLQ", "true");
    properties.put("durableSubscription", "true");
    properties.put("maxAttempts", "1"); // disable retry
    properties.put("requeue", "false");
    DirectChannel moduleInputChannel = new DirectChannel();
    moduleInputChannel.setBeanName("durableTest");
    moduleInputChannel.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            throw new RuntimeException("foo");
        }

    });
    bus.bindPubSubConsumer("teststream.tap:stream:durabletest.0", moduleInputChannel, properties);

    RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource());
    template.convertAndSend("xdbustest.topic.tap:stream:durabletest.0", "", "foo");

    int n = 0;
    while (n++ < 100) {
        Object deadLetter = template.receiveAndConvert("xdbustest.teststream.tap:stream:durabletest.0.dlq");
        if (deadLetter != null) {
            assertEquals("foo", deadLetter);
            break;
        }
        Thread.sleep(100);
    }
    assertTrue(n < 100);

    bus.unbindConsumer("teststream.tap:stream:durabletest.0", moduleInputChannel);
    assertNotNull(admin.getQueueProperties("xdbustest.teststream.tap:stream:durabletest.0.dlq"));
    admin.deleteQueue("xdbustest.teststream.tap:stream:durabletest.0.dlq");
    admin.deleteQueue("xdbustest.teststream.tap:stream:durabletest.0");
    admin.deleteExchange("xdbustest.topic.tap:stream:durabletest.0");
    admin.deleteExchange("xdbustest.DLX");
}

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

@Test
public void testNonDurablePubSubWithAutoBindDLQ() throws Exception {
    RabbitAdmin admin = new RabbitAdmin(this.rabbitAvailableRule.getResource());

    MessageBus bus = getMessageBus();/*w w w .j a v a 2 s.c o  m*/
    Properties properties = new Properties();
    properties.put("prefix", "xdbustest.");
    properties.put("autoBindDLQ", "true");
    properties.put("durableSubscription", "false");
    properties.put("maxAttempts", "1"); // disable retry
    properties.put("requeue", "false");
    DirectChannel moduleInputChannel = new DirectChannel();
    moduleInputChannel.setBeanName("nondurabletest");
    moduleInputChannel.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            throw new RuntimeException("foo");
        }

    });
    bus.bindPubSubConsumer("teststream.tap:stream:nondurabletest.0", moduleInputChannel, properties);

    bus.unbindConsumer("teststream.tap:stream:nondurabletest.0", moduleInputChannel);
    assertNull(admin.getQueueProperties("xdbustest.teststream.tap:stream:nondurabletest.0.dlq"));
    admin.deleteQueue("xdbustest.teststream.tap:stream:nondurabletest.0");
    admin.deleteExchange("xdbustest.topic.tap:stream:nondurabletest.0");
}

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

@Test
public void testAutoBindDLQ() throws Exception {
    RabbitAdmin admin = new RabbitAdmin(this.rabbitAvailableRule.getResource());

    MessageBus bus = getMessageBus();/*from  w w  w.  j  av  a  2  s  . co  m*/
    Properties properties = new Properties();
    properties.put("prefix", "xdbustest.");
    properties.put("autoBindDLQ", "true");
    properties.put("maxAttempts", "1"); // disable retry
    properties.put("requeue", "false");
    DirectChannel moduleInputChannel = new DirectChannel();
    moduleInputChannel.setBeanName("dlqTest");
    moduleInputChannel.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            throw new RuntimeException("foo");
        }

    });
    bus.bindConsumer("dlqtest", moduleInputChannel, properties);

    RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource());
    template.convertAndSend("", "xdbustest.dlqtest", "foo");

    int n = 0;
    while (n++ < 100) {
        Object deadLetter = template.receiveAndConvert("xdbustest.dlqtest.dlq");
        if (deadLetter != null) {
            assertEquals("foo", deadLetter);
            break;
        }
        Thread.sleep(100);
    }
    assertTrue(n < 100);

    bus.unbindConsumer("dlqtest", moduleInputChannel);
    admin.deleteQueue("xdbustest.dlqtest.dlq");
    admin.deleteQueue("xdbustest.dlqtest");
    admin.deleteExchange("xdbustest.DLX");
}