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

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

Introduction

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

Prototype

@Override
    public boolean subscribe(MessageHandler handler) 

Source Link

Usage

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 w  w .  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 ww . ja  v  a2  s.  c  om*/
    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  w w  . ja  va 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();/* ww  w  .ja  v a 2  s. c o m*/
    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 testDurablePubSubWithAutoBindDLQ() throws Exception {
    RabbitAdmin admin = new RabbitAdmin(this.rabbitAvailableRule.getResource());

    MessageBus bus = getMessageBus();/*from  w  w  w .ja  v a  2 s .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();//from  www.  j  ava 2 s  . co 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  ww  . j  a va 2  s  .  c om
    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");
}

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

@Test
public void testAutoBindDLQwithRepublish() throws Exception {
    // pre-declare the queue with dead-lettering, users can also use a policy
    RabbitAdmin admin = new RabbitAdmin(this.rabbitAvailableRule.getResource());
    Map<String, Object> args = new HashMap<String, Object>();
    args.put("x-dead-letter-exchange", "xdbustest.DLX");
    Queue queue = new Queue("xdbustest.dlqpubtest", true, false, false, args);
    admin.declareQueue(queue);/*from  w  ww .j  a v a  2s  .c  o  m*/

    MessageBus bus = getMessageBus();
    Properties properties = new Properties();
    properties.put("prefix", "xdbustest.");
    properties.put("autoBindDLQ", "true");
    properties.put("republishToDLQ", "true");
    properties.put("maxAttempts", "1"); // disable retry
    properties.put("requeue", "false");
    DirectChannel moduleInputChannel = new DirectChannel();
    moduleInputChannel.setBeanName("dlqPubTest");
    moduleInputChannel.subscribe(new MessageHandler() {

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

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

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

    int n = 0;
    while (n++ < 100) {
        org.springframework.amqp.core.Message deadLetter = template.receive("xdbustest.dlqpubtest.dlq");
        if (deadLetter != null) {
            assertEquals("foo", new String(deadLetter.getBody()));
            assertNotNull(deadLetter.getMessageProperties().getHeaders().get("x-exception-stacktrace"));
            break;
        }
        Thread.sleep(100);
    }
    assertTrue(n < 100);

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

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

private void doRegisterConsumer(String name, MessageChannel moduleInputChannel, Queue queue,
        RabbitPropertiesAccessor properties, boolean isPubSub) {
    // Fix for XD-2503
    // Temporarily overrides the thread context classloader with the one where the SimpleMessageListenerContainer is defined
    // This allows for the proxying that happens while initializing the SimpleMessageListenerContainer to work correctly
    ClassLoader originalClassloader = Thread.currentThread().getContextClassLoader();
    try {//from ww  w  .jav  a 2s. com
        ClassUtils.overrideThreadContextClassLoader(SimpleMessageListenerContainer.class.getClassLoader());
        SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer(
                this.connectionFactory);
        listenerContainer.setAcknowledgeMode(properties.getAcknowledgeMode(this.defaultAcknowledgeMode));
        listenerContainer.setChannelTransacted(properties.getTransacted(this.defaultChannelTransacted));
        listenerContainer
                .setDefaultRequeueRejected(properties.getRequeueRejected(this.defaultDefaultRequeueRejected));
        if (!isPubSub) {
            int concurrency = properties.getConcurrency(this.defaultConcurrency);
            concurrency = concurrency > 0 ? concurrency : 1;
            listenerContainer.setConcurrentConsumers(concurrency);
            int maxConcurrency = properties.getMaxConcurrency(this.defaultMaxConcurrency);
            if (maxConcurrency > concurrency) {
                listenerContainer.setMaxConcurrentConsumers(maxConcurrency);
            }
        }
        listenerContainer.setPrefetchCount(properties.getPrefetchCount(this.defaultPrefetchCount));
        listenerContainer.setTxSize(properties.getTxSize(this.defaultTxSize));
        listenerContainer.setTaskExecutor(new SimpleAsyncTaskExecutor(queue.getName() + "-"));
        listenerContainer.setQueues(queue);
        int maxAttempts = properties.getMaxAttempts(this.defaultMaxAttempts);
        if (maxAttempts > 1) {
            RetryOperationsInterceptor retryInterceptor = RetryInterceptorBuilder.stateless()
                    .maxAttempts(maxAttempts)
                    .backOffOptions(properties.getBackOffInitialInterval(this.defaultBackOffInitialInterval),
                            properties.getBackOffMultiplier(this.defaultBackOffMultiplier),
                            properties.getBackOffMaxInterval(this.defaultBackOffMaxInterval))
                    .recoverer(new RejectAndDontRequeueRecoverer()).build();
            listenerContainer.setAdviceChain(new Advice[] { retryInterceptor });
        }
        listenerContainer.setAfterReceivePostProcessors(this.decompressingPostProcessor);
        listenerContainer.setMessagePropertiesConverter(RabbitMessageBus.inboundMessagePropertiesConverter);
        listenerContainer.afterPropertiesSet();
        AmqpInboundChannelAdapter adapter = new AmqpInboundChannelAdapter(listenerContainer);
        adapter.setBeanFactory(this.getBeanFactory());
        DirectChannel bridgeToModuleChannel = new DirectChannel();
        bridgeToModuleChannel.setBeanFactory(this.getBeanFactory());
        bridgeToModuleChannel.setBeanName(name + ".bridge");
        adapter.setOutputChannel(bridgeToModuleChannel);
        adapter.setBeanName("inbound." + name);
        DefaultAmqpHeaderMapper mapper = new DefaultAmqpHeaderMapper();
        mapper.setRequestHeaderNames(properties.getRequestHeaderPattens(this.defaultRequestHeaderPatterns));
        mapper.setReplyHeaderNames(properties.getReplyHeaderPattens(this.defaultReplyHeaderPatterns));
        adapter.setHeaderMapper(mapper);
        adapter.afterPropertiesSet();
        Binding consumerBinding = Binding.forConsumer(name, adapter, moduleInputChannel, properties);
        addBinding(consumerBinding);
        ReceivingHandler convertingBridge = new ReceivingHandler();
        convertingBridge.setOutputChannel(moduleInputChannel);
        convertingBridge.setBeanName(name + ".convert.bridge");
        convertingBridge.afterPropertiesSet();
        bridgeToModuleChannel.subscribe(convertingBridge);
        consumerBinding.start();
    } finally {
        Thread.currentThread().setContextClassLoader(originalClassloader);
    }
}

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

@Test
public void testAutoBindDLQ() throws Exception {
    // pre-declare the queue with dead-lettering, users can also use a policy
    RabbitAdmin admin = new RabbitAdmin(this.rabbitAvailableRule.getResource());
    Map<String, Object> args = new HashMap<String, Object>();
    args.put("x-dead-letter-exchange", "xdbustest.DLX");
    Queue queue = new Queue("xdbustest.dlqtest", true, false, false, args);
    admin.declareQueue(queue);/*w w w . j a  v a2 s.c  om*/

    MessageBus bus = getMessageBus();
    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");
}