Example usage for org.springframework.messaging MessageHandler MessageHandler

List of usage examples for org.springframework.messaging MessageHandler MessageHandler

Introduction

In this page you can find the example usage for org.springframework.messaging MessageHandler MessageHandler.

Prototype

MessageHandler

Source Link

Usage

From source file:com.acme.ModuleConfigurationTest.java

@Test
public void test() {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    Properties properties = new Properties();
    properties.put("prefix", "foo");
    properties.put("suffix", "bar");
    context.getEnvironment().getPropertySources().addLast(new PropertiesPropertySource("options", properties));
    context.register(TestConfiguration.class);
    context.refresh();//from  w w w.ja v a 2  s . co  m

    MessageChannel input = context.getBean("input", MessageChannel.class);
    SubscribableChannel output = context.getBean("output", SubscribableChannel.class);

    final AtomicBoolean handled = new AtomicBoolean();
    output.subscribe(new MessageHandler() {
        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            handled.set(true);
            assertEquals("foohellobar", message.getPayload());
        }
    });
    input.send(new GenericMessage<String>("hello"));
    assertTrue(handled.get());
}

From source file:eric.bottard.tis100.Runner.java

public Runner(int rows, int columns, String specificationFile, File solution) throws IOException {

    Specification specification = new LuaSpecification(specificationFile, rows, columns);

    List<String> nodeSources = loadSolution(solution, specification.getLayout());

    this.rows = rows;
    this.columns = columns;

    verticalChannels = new MessageChannel[columns * (rows + 1) * 2];
    horizontalChannels = new MessageChannel[rows * (columns + 1) * 2];

    // channels[2*x] = ltr / down-to-up
    // channels[2*x + 1] = rtl / up-to-down
    for (int row = 0; row <= rows; row++) {
        for (int column = 0; column < columns; column++) {
            verticalChannels[(row * columns + column) * 2] = (row == 0 || row == rows) ? new NullChannel()
                    : new RendezvousChannel();
            if (row == 0) {
                verticalChannels[(row * columns + column) * 2 + 1] = new QueueChannel(40);
            } else if (row == rows) {
                verticalChannels[(row * columns + column) * 2 + 1] = new PublishSubscribeChannel();
            } else {
                verticalChannels[(row * columns + column) * 2 + 1] = new RendezvousChannel();
            }/*from w ww  . ja  va2  s  .c o m*/
        }
    }

    for (int row = 0; row < rows; row++) {
        for (int column = 0; column <= columns; column++) {
            horizontalChannels[(column * rows + row) * 2] = (column == 0 || column == columns)
                    ? new NullChannel()
                    : new RendezvousChannel();
            horizontalChannels[(column * rows + row) * 2 + 1] = (column == 0 || column == columns)
                    ? new NullChannel()
                    : new RendezvousChannel();
        }
    }

    Thread[] threads = new Thread[rows * columns];
    Object mutex = new Object();

    for (int row = 0; row < rows; row++) {
        for (int column = 0; column < columns; column++) {
            final SpringNode node = NodeFactory.buildNode(nodeSources.get(row * columns + column));
            final NodePrettyPrinter printer = new NodePrettyPrinter(4 + row * 19,
                    SpecificationPrettyPrinter.WIDTH + 10 + column * 37, node);
            Ports ports = new PortsMapping(row, column);
            node.setPorts(ports);
            nodes.add(node);
            threads[row * columns + column] = new Thread() {
                @Override
                public void run() {

                    boolean more;
                    do {
                        synchronized (mutex) {
                            printer.draw(System.out);
                        }
                        try {
                            Thread.sleep(150);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        more = node.tick();
                    } while (more);
                }
            };
        }
    }

    List<Integer>[] actuals = new List[columns];
    SpecificationPrettyPrinter specificationPrettyPrinter = new SpecificationPrettyPrinter(specification, 2, 2,
            actuals);

    for (int i = 0; i < columns; i++) {
        Specification.Stream stream = specification.getInputStreams()[i];
        if (stream != null) {
            for (Integer in : stream.getData()) {
                verticalChannels[1 + 2 * i].send(new GenericMessage<>(in));
            }
        }
        stream = specification.getOutputStreams()[i];
        final List<Integer> actual = actuals[i] = new ArrayList<>();
        if (stream != null) {
            ((SubscribableChannel) verticalChannels[1 + 2 * (i + rows * columns)])
                    .subscribe(new MessageHandler() {
                        @Override
                        public void handleMessage(Message<?> message) throws MessagingException {
                            actual.add((Integer) message.getPayload());
                            synchronized (mutex) {
                                specificationPrettyPrinter.draw(System.out);
                            }
                        }
                    });
        }
    }
    synchronized (mutex) {
        specificationPrettyPrinter.draw(System.out);
    }

    for (int i = 0; i < rows * columns; i++) {
        threads[i].start();
    }

}

From source file:org.encuestame.core.test.integration.IntegrationTestCase.java

@Test
public void shouldAcceptBites() throws Exception {
    String message = "Test Message :" + dateFormat.format(Calendar.getInstance().getTime());

    // String message = "http://google.com";

    final AtomicReference<Message<?>> received = new AtomicReference<Message<?>>();
    bites.subscribe(new MessageHandler() {
        public void handleMessage(Message<?> message) throws MessagingException {
            received.set(message);/*from ww  w  .ja va2s  . c o m*/
        }
    });
    twitterAdapter.publishTweet(message);
    // assertThat(((String) received.get().getPayload()), is(message));
    // assertThat(received.get(), hasPayload(message));
}

From source file:org.springframework.cloud.stream.app.hdfs.dataset.sink.HdfsDatasetSinkConfiguration.java

@Bean
@ServiceActivator(inputChannel = "toSink")
public MessageHandler datasetSinkMessageHandler(final DatasetOperations datasetOperations) {
    return new MessageHandler() {

        @Override/*  w ww.  j a va2s .  c  o  m*/
        public void handleMessage(Message<?> message) throws MessagingException {
            Object payload = message.getPayload();
            if (payload instanceof Collection<?>) {
                Collection<?> payloads = (Collection<?>) payload;
                logger.debug("Writing a collection of {} POJOs" + payloads.size());
                datasetOperations.write((Collection<?>) message.getPayload());
            } else {
                // This should never happen since message handler is fronted by an aggregator
                throw new IllegalStateException("Expected a collection of POJOs but received "
                        + message.getPayload().getClass().getName());
            }
        }
    };
}

From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderTests.java

@Test
public void testSendAndReceiveBad() throws Exception {
    RabbitTestBinder binder = getBinder();
    DirectChannel moduleOutputChannel = createBindableChannel("output", new BindingProperties());
    DirectChannel moduleInputChannel = createBindableChannel("input", new BindingProperties());
    Binding<MessageChannel> producerBinding = binder.bindProducer("bad.0", moduleOutputChannel,
            createProducerProperties());
    Binding<MessageChannel> consumerBinding = binder.bindConsumer("bad.0", "test", moduleInputChannel,
            createConsumerProperties());
    Message<?> message = MessageBuilder.withPayload("bad").setHeader(MessageHeaders.CONTENT_TYPE, "foo/bar")
            .build();// w  w  w .j a 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);
    assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue();
    producerBinding.unbind();
    consumerBinding.unbind();
}

From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderTests.java

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

    RabbitTestBinder binder = getBinder();

    ExtendedConsumerProperties<RabbitConsumerProperties> consumerProperties = createConsumerProperties();
    consumerProperties.getExtension().setPrefix(TEST_PREFIX);
    consumerProperties.getExtension().setAutoBindDlq(true);
    consumerProperties.getExtension().setDurableSubscription(true);
    consumerProperties.setMaxAttempts(1); // disable retry
    DirectChannel moduleInputChannel = createBindableChannel("input",
            createConsumerBindingProperties(consumerProperties));
    moduleInputChannel.setBeanName("durableTest");
    moduleInputChannel.subscribe(new MessageHandler() {

        @Override//from   w  ww .  j av a 2s  . c o  m
        public void handleMessage(Message<?> message) throws MessagingException {
            throw new RuntimeException("foo");
        }

    });
    Binding<MessageChannel> consumerBinding = binder.bindConsumer("durabletest.0", "tgroup", moduleInputChannel,
            consumerProperties);

    RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource());
    template.convertAndSend(TEST_PREFIX + "durabletest.0", "", "foo");

    int n = 0;
    while (n++ < 100) {
        Object deadLetter = template.receiveAndConvert(TEST_PREFIX + "durabletest.0.tgroup.dlq");
        if (deadLetter != null) {
            assertThat(deadLetter).isEqualTo("foo");
            break;
        }
        Thread.sleep(100);
    }
    assertThat(n).isLessThan(100);

    consumerBinding.unbind();
    assertThat(admin.getQueueProperties(TEST_PREFIX + "durabletest.0.tgroup.dlq")).isNotNull();
}

From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderTests.java

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

    RabbitTestBinder binder = getBinder();
    ExtendedConsumerProperties<RabbitConsumerProperties> consumerProperties = createConsumerProperties();
    consumerProperties.getExtension().setPrefix(TEST_PREFIX);
    consumerProperties.getExtension().setAutoBindDlq(true);
    consumerProperties.getExtension().setDurableSubscription(false);
    consumerProperties.setMaxAttempts(1); // disable retry
    BindingProperties bindingProperties = createConsumerBindingProperties(consumerProperties);
    DirectChannel moduleInputChannel = createBindableChannel("input", bindingProperties);
    moduleInputChannel.setBeanName("nondurabletest");
    moduleInputChannel.subscribe(new MessageHandler() {

        @Override//from  w w  w.  ja  va  2 s.  co  m
        public void handleMessage(Message<?> message) throws MessagingException {
            throw new RuntimeException("foo");
        }

    });
    Binding<MessageChannel> consumerBinding = binder.bindConsumer("nondurabletest.0", "tgroup",
            moduleInputChannel, consumerProperties);

    consumerBinding.unbind();
    assertThat(admin.getQueueProperties(TEST_PREFIX + "nondurabletest.0.dlq")).isNull();
}

From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderTests.java

@Test
public void testAutoBindDLQ() throws Exception {
    RabbitTestBinder binder = getBinder();
    ExtendedConsumerProperties<RabbitConsumerProperties> consumerProperties = createConsumerProperties();
    consumerProperties.getExtension().setPrefix(TEST_PREFIX);
    consumerProperties.getExtension().setAutoBindDlq(true);
    consumerProperties.setMaxAttempts(1); // disable retry
    consumerProperties.getExtension().setDurableSubscription(true);
    BindingProperties bindingProperties = createConsumerBindingProperties(consumerProperties);
    DirectChannel moduleInputChannel = createBindableChannel("input", bindingProperties);
    moduleInputChannel.setBeanName("dlqTest");
    moduleInputChannel.subscribe(new MessageHandler() {

        @Override// w w  w.  j av a2 s.  c  om
        public void handleMessage(Message<?> message) throws MessagingException {
            throw new RuntimeException("foo");
        }

    });
    Binding<MessageChannel> consumerBinding = binder.bindConsumer("dlqtest", "default", moduleInputChannel,
            consumerProperties);

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

    int n = 0;
    while (n++ < 100) {
        Object deadLetter = template.receiveAndConvert(TEST_PREFIX + "dlqtest.default.dlq");
        if (deadLetter != null) {
            assertThat(deadLetter).isEqualTo("foo");
            break;
        }
        Thread.sleep(100);
    }
    assertThat(n).isLessThan(100);

    consumerBinding.unbind();

    ApplicationContext context = TestUtils.getPropertyValue(binder,
            "binder.provisioningProvider.autoDeclareContext", ApplicationContext.class);
    assertThat(context.containsBean(TEST_PREFIX + "dlqtest.default.binding")).isFalse();
    assertThat(context.containsBean(TEST_PREFIX + "dlqtest.default")).isFalse();
    assertThat(context.containsBean(TEST_PREFIX + "dlqtest.default.dlq.binding")).isFalse();
    assertThat(context.containsBean(TEST_PREFIX + "dlqtest.default.dlq")).isFalse();
}

From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderTests.java

@Test
public void testAutoBindDLQPartionedConsumerFirst() throws Exception {
    RabbitTestBinder binder = getBinder();
    ExtendedConsumerProperties<RabbitConsumerProperties> properties = createConsumerProperties();
    properties.getExtension().setPrefix("bindertest.");
    properties.getExtension().setAutoBindDlq(true);
    properties.setMaxAttempts(1); // disable retry
    properties.setPartitioned(true);/*from   w  w w.  ja  v  a2 s  .c o m*/
    properties.setInstanceIndex(0);
    DirectChannel input0 = createBindableChannel("input", createConsumerBindingProperties(properties));
    input0.setBeanName("test.input0DLQ");
    Binding<MessageChannel> input0Binding = binder.bindConsumer("partDLQ.0", "dlqPartGrp", input0, properties);
    Binding<MessageChannel> defaultConsumerBinding1 = binder.bindConsumer("partDLQ.0", "default",
            new QueueChannel(), properties);
    properties.setInstanceIndex(1);
    DirectChannel input1 = createBindableChannel("input1", createConsumerBindingProperties(properties));
    input1.setBeanName("test.input1DLQ");
    Binding<MessageChannel> input1Binding = binder.bindConsumer("partDLQ.0", "dlqPartGrp", input1, properties);
    Binding<MessageChannel> defaultConsumerBinding2 = binder.bindConsumer("partDLQ.0", "default",
            new QueueChannel(), properties);

    ExtendedProducerProperties<RabbitProducerProperties> producerProperties = createProducerProperties();
    producerProperties.getExtension().setPrefix("bindertest.");
    producerProperties.getExtension().setAutoBindDlq(true);
    producerProperties.setPartitionKeyExtractorClass(PartitionTestSupport.class);
    producerProperties.setPartitionSelectorClass(PartitionTestSupport.class);
    producerProperties.setPartitionCount(2);
    BindingProperties bindingProperties = createProducerBindingProperties(producerProperties);
    DirectChannel output = createBindableChannel("output", bindingProperties);
    output.setBeanName("test.output");
    Binding<MessageChannel> outputBinding = binder.bindProducer("partDLQ.0", output, producerProperties);

    final CountDownLatch latch0 = new CountDownLatch(1);
    input0.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            if (latch0.getCount() <= 0) {
                throw new RuntimeException("dlq");
            }
            latch0.countDown();
        }

    });

    final CountDownLatch latch1 = new CountDownLatch(1);
    input1.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            if (latch1.getCount() <= 0) {
                throw new RuntimeException("dlq");
            }
            latch1.countDown();
        }

    });

    output.send(new GenericMessage<>(1));
    assertThat(latch1.await(10, TimeUnit.SECONDS)).isTrue();

    output.send(new GenericMessage<>(0));
    assertThat(latch0.await(10, TimeUnit.SECONDS)).isTrue();

    output.send(new GenericMessage<>(1));

    RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource());
    template.setReceiveTimeout(10000);

    String streamDLQName = "bindertest.partDLQ.0.dlqPartGrp.dlq";

    org.springframework.amqp.core.Message received = template.receive(streamDLQName);
    assertThat(received).isNotNull();
    assertThat(received.getMessageProperties().getReceivedRoutingKey())
            .isEqualTo("bindertest.partDLQ.0.dlqPartGrp-1");
    assertThat(received.getMessageProperties().getHeaders()).doesNotContainKey(BinderHeaders.PARTITION_HEADER);

    output.send(new GenericMessage<>(0));
    received = template.receive(streamDLQName);
    assertThat(received).isNotNull();
    assertThat(received.getMessageProperties().getReceivedRoutingKey())
            .isEqualTo("bindertest.partDLQ.0.dlqPartGrp-0");
    assertThat(received.getMessageProperties().getHeaders()).doesNotContainKey(BinderHeaders.PARTITION_HEADER);

    input0Binding.unbind();
    input1Binding.unbind();
    defaultConsumerBinding1.unbind();
    defaultConsumerBinding2.unbind();
    outputBinding.unbind();
}

From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderTests.java

private void testAutoBindDLQPartionedConsumerFirstWithRepublishGuts(final boolean withRetry) throws Exception {
    RabbitTestBinder binder = getBinder();
    ExtendedConsumerProperties<RabbitConsumerProperties> properties = createConsumerProperties();
    properties.getExtension().setPrefix("bindertest.");
    properties.getExtension().setAutoBindDlq(true);
    properties.getExtension().setRepublishToDlq(true);
    properties.getExtension().setRepublishDeliveyMode(MessageDeliveryMode.NON_PERSISTENT);
    properties.setMaxAttempts(withRetry ? 2 : 1);
    properties.setPartitioned(true);//from  w  w  w . j  a  va 2s.c o  m
    properties.setInstanceIndex(0);
    DirectChannel input0 = createBindableChannel("input", createConsumerBindingProperties(properties));
    input0.setBeanName("test.input0DLQ");
    Binding<MessageChannel> input0Binding = binder.bindConsumer("partPubDLQ.0", "dlqPartGrp", input0,
            properties);
    Binding<MessageChannel> defaultConsumerBinding1 = binder.bindConsumer("partPubDLQ.0", "default",
            new QueueChannel(), properties);
    properties.setInstanceIndex(1);
    DirectChannel input1 = createBindableChannel("input1", createConsumerBindingProperties(properties));
    input1.setBeanName("test.input1DLQ");
    Binding<MessageChannel> input1Binding = binder.bindConsumer("partPubDLQ.0", "dlqPartGrp", input1,
            properties);
    Binding<MessageChannel> defaultConsumerBinding2 = binder.bindConsumer("partPubDLQ.0", "default",
            new QueueChannel(), properties);

    ExtendedProducerProperties<RabbitProducerProperties> producerProperties = createProducerProperties();
    producerProperties.getExtension().setPrefix("bindertest.");
    producerProperties.getExtension().setAutoBindDlq(true);
    producerProperties.setPartitionKeyExtractorClass(PartitionTestSupport.class);
    producerProperties.setPartitionSelectorClass(PartitionTestSupport.class);
    producerProperties.setPartitionCount(2);
    BindingProperties bindingProperties = createProducerBindingProperties(producerProperties);
    DirectChannel output = createBindableChannel("output", bindingProperties);
    output.setBeanName("test.output");
    Binding<MessageChannel> outputBinding = binder.bindProducer("partPubDLQ.0", output, producerProperties);

    final CountDownLatch latch0 = new CountDownLatch(1);
    input0.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            if (latch0.getCount() <= 0) {
                throw new RuntimeException("dlq");
            }
            latch0.countDown();
        }

    });

    final CountDownLatch latch1 = new CountDownLatch(1);
    input1.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            if (latch1.getCount() <= 0) {
                throw new RuntimeException("dlq");
            }
            latch1.countDown();
        }

    });

    ApplicationContext context = TestUtils.getPropertyValue(binder.getBinder(), "applicationContext",
            ApplicationContext.class);
    SubscribableChannel boundErrorChannel = context.getBean("bindertest.partPubDLQ.0.dlqPartGrp-0.errors",
            SubscribableChannel.class);
    SubscribableChannel globalErrorChannel = context.getBean("errorChannel", SubscribableChannel.class);
    final AtomicReference<Message<?>> boundErrorChannelMessage = new AtomicReference<>();
    final AtomicReference<Message<?>> globalErrorChannelMessage = new AtomicReference<>();
    final AtomicBoolean hasRecovererInCallStack = new AtomicBoolean(!withRetry);
    boundErrorChannel.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            boundErrorChannelMessage.set(message);
            String stackTrace = Arrays.toString(new RuntimeException().getStackTrace());
            hasRecovererInCallStack.set(stackTrace.contains("ErrorMessageSendingRecoverer"));
        }

    });
    globalErrorChannel.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            globalErrorChannelMessage.set(message);
        }

    });

    output.send(new GenericMessage<>(1));
    assertThat(latch1.await(10, TimeUnit.SECONDS)).isTrue();

    output.send(new GenericMessage<>(0));
    assertThat(latch0.await(10, TimeUnit.SECONDS)).isTrue();

    output.send(new GenericMessage<>(1));

    RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource());
    template.setReceiveTimeout(10000);

    String streamDLQName = "bindertest.partPubDLQ.0.dlqPartGrp.dlq";

    org.springframework.amqp.core.Message received = template.receive(streamDLQName);
    assertThat(received).isNotNull();
    assertThat(received.getMessageProperties().getHeaders().get("x-original-routingKey"))
            .isEqualTo("partPubDLQ.0-1");
    assertThat(received.getMessageProperties().getHeaders()).doesNotContainKey(BinderHeaders.PARTITION_HEADER);
    assertThat(received.getMessageProperties().getReceivedDeliveryMode())
            .isEqualTo(MessageDeliveryMode.NON_PERSISTENT);

    output.send(new GenericMessage<>(0));
    received = template.receive(streamDLQName);
    assertThat(received).isNotNull();
    assertThat(received.getMessageProperties().getHeaders().get("x-original-routingKey"))
            .isEqualTo("partPubDLQ.0-0");
    assertThat(received.getMessageProperties().getHeaders()).doesNotContainKey(BinderHeaders.PARTITION_HEADER);

    // verify we got a message on the dedicated error channel and the global (via bridge)
    assertThat(boundErrorChannelMessage.get()).isNotNull();
    assertThat(globalErrorChannelMessage.get()).isNotNull();
    assertThat(hasRecovererInCallStack.get()).isEqualTo(withRetry);

    input0Binding.unbind();
    input1Binding.unbind();
    defaultConsumerBinding1.unbind();
    defaultConsumerBinding2.unbind();
    outputBinding.unbind();
}