Example usage for org.springframework.integration.channel QueueChannel receive

List of usage examples for org.springframework.integration.channel QueueChannel receive

Introduction

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

Prototype

@Override 
@Nullable
public Message<?> receive(long timeout) 

Source Link

Document

Receive the first available message from this channel.

Usage

From source file:com.chrisjansen.jms.gateway.JMSGatewayTest.java

@Test
public void testGatewayDemo() throws InterruptedException {

    final MessageChannel stdinToJmsoutChannel = applicationContext.getBean("stdinToJmsoutChannel",
            MessageChannel.class);

    stdinToJmsoutChannel.send(MessageBuilder.withPayload("activemq jms test").build());

    final QueueChannel queueChannel = applicationContext.getBean("queueChannel", QueueChannel.class);

    Message<String> reply = (Message<String>) queueChannel.receive(60000);
    Assert.assertNotNull(reply);/*from w  w w.  jav a  2s. c o m*/

    String out = reply.getPayload();
    Assert.assertEquals("JMS response: ACTIVEMQ JMS TEST", out);
}

From source file:com.opensourceagility.springintegration.alerts.AlertsIntegrationTest.java

@SuppressWarnings("unchecked")
@Test//ww  w  .  j a va  2s  .  c  o m
public void testChannelAdapterDemo() throws InterruptedException, ParseException {

    System.setProperty("spring.profiles.active", "testCase");

    final GenericXmlApplicationContext applicationContext = new GenericXmlApplicationContext(
            configFilesChannelAdapterDemo);

    final MessageChannel createAlertRequestChannel = applicationContext.getBean("createAlertRequestChannel",
            MessageChannel.class);

    createAlertTestData(createAlertRequestChannel, thisMinuteDate);

    final QueueChannel queueChannel = applicationContext.getBean("queueChannel", QueueChannel.class);

    for (int counter = 1; counter <= 50; counter++) {
        int id = counter * 2;
        Message<String> reply = (Message<String>) queueChannel.receive(10000);
        Assert.assertNotNull(reply);
        String out = reply.getPayload();
        Assert.assertEquals(getExpectedXml(id), out);
        LOGGER.debug("Received expected Alert XML from queue:" + out);
    }
    LOGGER.debug(
            "Asserted that urgent alerts are those 50 alerts with even ids, ranging from 2 up to 100... and that these are received from the queue");

    Message<String> reply = (Message<String>) queueChannel.receive(10000);
    Assert.assertNull(reply);

    LOGGER.debug("Sleeping for 2 minutes until files are expected to have been (mock) uploaded...");
    Thread.sleep(120 * 1000);

    final MockAmazonS3FileUploader mockFileProcessor = applicationContext.getBean("amazonS3FileUploader",
            MockAmazonS3FileUploader.class);
    Assert.assertEquals(2, mockFileProcessor.getLinesByFileName().size());
    LOGGER.debug("Asserted successfully that 2 csv files were expected");

    List<String> minute1Lines = mockFileProcessor.getLinesByFileName().get(thisMinuteString);
    List<String> minute2Lines = mockFileProcessor.getLinesByFileName().get(nextMinuteString);

    // Assert we have the correct 30 entries in the csv file for the 1st minute
    Assert.assertEquals(30, minute1Lines.size());
    LOGGER.debug("Asserted successfully that 30 alerts found in file:" + thisMinuteString);

    // Assert we have 20 correct entries in the csv file for the 2nd minute
    Assert.assertEquals(20, minute2Lines.size());
    LOGGER.debug("Asserted successfully that 20 alerts found in file:" + nextMinuteString);

    // Check that the 1st minute's csv lines are as expected
    for (int counter = 1; counter <= 30; counter++) {
        int id = counter * 2 - 1;
        String line = minute1Lines.get(counter - 1);
        Assert.assertEquals(getExpectedCsvLine(id), line);
        LOGGER.debug("Found expected csv line in file:" + thisMinuteString + ":" + line);

    }

    // Check that the 2nd minute's csv lines are as expected
    for (int counter = 31; counter <= 50; counter++) {
        int id = counter * 2 - 1;
        String line = minute2Lines.get(counter - 31);
        Assert.assertEquals(getExpectedCsvLine(id), line);
        LOGGER.debug("Found expected csv line in file:" + nextMinuteString + " : " + line);

    }

    LOGGER.debug(
            "Asserted that non-urgent alerts are those 50 alerts with odd ids, ranging from 1 up to 99... and that these are written to csv files and uploaded");

    LOGGER.debug("Completed test successfully, closing application context");

    applicationContext.close();
}

From source file:multibinder.TwoKafkaBindersApplicationTest.java

@Test
public void messagingWorks() {
    DirectChannel dataProducer = new DirectChannel();
    ((KafkaMessageChannelBinder) binderFactory.getBinder("kafka1")).bindProducer("dataIn", dataProducer,
            new ExtendedProducerProperties<>(new KafkaProducerProperties()));

    QueueChannel dataConsumer = new QueueChannel();
    ((KafkaMessageChannelBinder) binderFactory.getBinder("kafka2")).bindConsumer("dataOut",
            UUID.randomUUID().toString(), dataConsumer,
            new ExtendedConsumerProperties<>(new KafkaConsumerProperties()));

    String testPayload = "testFoo" + UUID.randomUUID().toString();
    dataProducer.send(MessageBuilder.withPayload(testPayload).build());

    Message<?> receive = dataConsumer.receive(5000);
    Assert.assertThat(receive, Matchers.notNullValue());
    Assert.assertThat(receive.getPayload(), CoreMatchers.equalTo(testPayload));
}

From source file:multibinder.RabbitAndKafkaBinderApplicationTests.java

@Test
public void messagingWorks() throws Exception {
    // passing connection arguments arguments to the embedded Kafka instance
    ConfigurableApplicationContext context = SpringApplication.run(MultibinderApplication.class,
            "--spring.cloud.stream.kafka.binder.brokers=" + kafkaEmbedded.getBrokersAsString(),
            "--spring.cloud.stream.kafka.binder.zkNodes=" + kafkaEmbedded.getZookeeperConnectionString(),
            "--spring.cloud.stream.bindings.output.producer.requiredGroups=" + this.randomGroup);
    DirectChannel dataProducer = new DirectChannel();
    BinderFactory<?> binderFactory = context.getBean(BinderFactory.class);

    QueueChannel dataConsumer = new QueueChannel();

    ((RabbitMessageChannelBinder) binderFactory.getBinder("rabbit")).bindConsumer("dataOut", this.randomGroup,
            dataConsumer, new ExtendedConsumerProperties<>(new RabbitConsumerProperties()));

    ((KafkaMessageChannelBinder) binderFactory.getBinder("kafka")).bindProducer("dataIn", dataProducer,
            new ExtendedProducerProperties<>(new KafkaProducerProperties()));

    String testPayload = "testFoo" + this.randomGroup;
    dataProducer.send(MessageBuilder.withPayload(testPayload).build());

    Message<?> receive = dataConsumer.receive(10000);
    Assert.assertThat(receive, Matchers.notNullValue());
    Assert.assertThat(receive.getPayload(), CoreMatchers.equalTo(testPayload));
    context.close();//w  w  w .  j a v  a2 s . c o m
}

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

@SuppressWarnings("unchecked")
@Test//from  w  w  w  . j  a  v a2s .co  m
public void testBatchingAndCompression() throws Exception {
    RabbitTestBinder binder = getBinder();
    ExtendedProducerProperties<RabbitProducerProperties> producerProperties = createProducerProperties();
    producerProperties.getExtension().setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);
    producerProperties.getExtension().setBatchingEnabled(true);
    producerProperties.getExtension().setBatchSize(2);
    producerProperties.getExtension().setBatchBufferLimit(100000);
    producerProperties.getExtension().setBatchTimeout(30000);
    producerProperties.getExtension().setCompress(true);
    producerProperties.setRequiredGroups("default");

    DirectChannel output = createBindableChannel("input", createProducerBindingProperties(producerProperties));
    output.setBeanName("batchingProducer");
    Binding<MessageChannel> producerBinding = binder.bindProducer("batching.0", output, producerProperties);

    Log logger = spy(TestUtils.getPropertyValue(binder, "binder.compressingPostProcessor.logger", Log.class));
    new DirectFieldAccessor(TestUtils.getPropertyValue(binder, "binder.compressingPostProcessor"))
            .setPropertyValue("logger", logger);
    when(logger.isTraceEnabled()).thenReturn(true);

    assertThat(TestUtils.getPropertyValue(binder, "binder.compressingPostProcessor.level"))
            .isEqualTo(Deflater.BEST_SPEED);

    output.send(new GenericMessage<>("foo".getBytes()));
    output.send(new GenericMessage<>("bar".getBytes()));

    Object out = spyOn("batching.0.default").receive(false);
    assertThat(out).isInstanceOf(byte[].class);
    assertThat(new String((byte[]) out)).isEqualTo("\u0000\u0000\u0000\u0003foo\u0000\u0000\u0000\u0003bar");

    ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class);
    verify(logger).trace(captor.capture());
    assertThat(captor.getValue().toString()).contains(("Compressed 14 to "));

    QueueChannel input = new QueueChannel();
    input.setBeanName("batchingConsumer");
    Binding<MessageChannel> consumerBinding = binder.bindConsumer("batching.0", "test", input,
            createConsumerProperties());

    output.send(new GenericMessage<>("foo".getBytes()));
    output.send(new GenericMessage<>("bar".getBytes()));

    Message<byte[]> in = (Message<byte[]>) input.receive(10000);
    assertThat(in).isNotNull();
    assertThat(new String(in.getPayload())).isEqualTo("foo");
    in = (Message<byte[]>) input.receive(10000);
    assertThat(in).isNotNull();
    assertThat(new String(in.getPayload())).isEqualTo("bar");
    assertThat(in.getHeaders().get(AmqpHeaders.DELIVERY_MODE)).isNull();

    producerBinding.unbind();
    consumerBinding.unbind();
}

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

@Test
public void testLateBinding() throws Exception {
    RabbitTestSupport.RabbitProxy proxy = new RabbitTestSupport.RabbitProxy();
    CachingConnectionFactory cf = new CachingConnectionFactory("localhost", proxy.getPort());

    RabbitMessageChannelBinder rabbitBinder = new RabbitMessageChannelBinder(cf, new RabbitProperties(),
            new RabbitExchangeQueueProvisioner(cf));
    RabbitTestBinder binder = new RabbitTestBinder(cf, rabbitBinder);

    ExtendedProducerProperties<RabbitProducerProperties> producerProperties = createProducerProperties();
    producerProperties.getExtension().setPrefix("latebinder.");
    producerProperties.getExtension().setAutoBindDlq(true);

    MessageChannel moduleOutputChannel = createBindableChannel("output",
            createProducerBindingProperties(producerProperties));
    Binding<MessageChannel> late0ProducerBinding = binder.bindProducer("late.0", moduleOutputChannel,
            producerProperties);//from  w  ww  . ja  v  a2 s  .  c o m

    QueueChannel moduleInputChannel = new QueueChannel();
    ExtendedConsumerProperties<RabbitConsumerProperties> rabbitConsumerProperties = createConsumerProperties();
    rabbitConsumerProperties.getExtension().setPrefix("latebinder.");
    Binding<MessageChannel> late0ConsumerBinding = binder.bindConsumer("late.0", "test", moduleInputChannel,
            rabbitConsumerProperties);

    producerProperties
            .setPartitionKeyExpression(spelExpressionParser.parseExpression("payload.equals('0') ? 0 : 1"));
    producerProperties.setPartitionSelectorExpression(spelExpressionParser.parseExpression("hashCode()"));
    producerProperties.setPartitionCount(2);

    MessageChannel partOutputChannel = createBindableChannel("output",
            createProducerBindingProperties(producerProperties));
    Binding<MessageChannel> partlate0ProducerBinding = binder.bindProducer("partlate.0", partOutputChannel,
            producerProperties);

    QueueChannel partInputChannel0 = new QueueChannel();
    QueueChannel partInputChannel1 = new QueueChannel();

    ExtendedConsumerProperties<RabbitConsumerProperties> partLateConsumerProperties = createConsumerProperties();
    partLateConsumerProperties.getExtension().setPrefix("latebinder.");
    partLateConsumerProperties.setPartitioned(true);
    partLateConsumerProperties.setInstanceIndex(0);
    Binding<MessageChannel> partlate0Consumer0Binding = binder.bindConsumer("partlate.0", "test",
            partInputChannel0, partLateConsumerProperties);
    partLateConsumerProperties.setInstanceIndex(1);
    Binding<MessageChannel> partlate0Consumer1Binding = binder.bindConsumer("partlate.0", "test",
            partInputChannel1, partLateConsumerProperties);

    ExtendedProducerProperties<RabbitProducerProperties> noDlqProducerProperties = createProducerProperties();
    noDlqProducerProperties.getExtension().setPrefix("latebinder.");
    MessageChannel noDLQOutputChannel = createBindableChannel("output",
            createProducerBindingProperties(noDlqProducerProperties));
    Binding<MessageChannel> noDlqProducerBinding = binder.bindProducer("lateNoDLQ.0", noDLQOutputChannel,
            noDlqProducerProperties);

    QueueChannel noDLQInputChannel = new QueueChannel();
    ExtendedConsumerProperties<RabbitConsumerProperties> noDlqConsumerProperties = createConsumerProperties();
    noDlqConsumerProperties.getExtension().setPrefix("latebinder.");
    Binding<MessageChannel> noDlqConsumerBinding = binder.bindConsumer("lateNoDLQ.0", "test", noDLQInputChannel,
            noDlqConsumerProperties);

    MessageChannel outputChannel = createBindableChannel("output",
            createProducerBindingProperties(noDlqProducerProperties));
    Binding<MessageChannel> pubSubProducerBinding = binder.bindProducer("latePubSub", outputChannel,
            noDlqProducerProperties);
    QueueChannel pubSubInputChannel = new QueueChannel();
    noDlqConsumerProperties.getExtension().setDurableSubscription(false);
    Binding<MessageChannel> nonDurableConsumerBinding = binder.bindConsumer("latePubSub", "lategroup",
            pubSubInputChannel, noDlqConsumerProperties);
    QueueChannel durablePubSubInputChannel = new QueueChannel();
    noDlqConsumerProperties.getExtension().setDurableSubscription(true);
    Binding<MessageChannel> durableConsumerBinding = binder.bindConsumer("latePubSub", "lateDurableGroup",
            durablePubSubInputChannel, noDlqConsumerProperties);

    proxy.start();

    moduleOutputChannel.send(new GenericMessage<>("foo"));
    Message<?> message = moduleInputChannel.receive(10000);
    assertThat(message).isNotNull();
    assertThat(message.getPayload()).isNotNull();

    noDLQOutputChannel.send(new GenericMessage<>("bar"));
    message = noDLQInputChannel.receive(10000);
    assertThat(message);
    assertThat(message.getPayload()).isEqualTo("bar");

    outputChannel.send(new GenericMessage<>("baz"));
    message = pubSubInputChannel.receive(10000);
    assertThat(message);
    assertThat(message.getPayload()).isEqualTo("baz");
    message = durablePubSubInputChannel.receive(10000);
    assertThat(message).isNotNull();
    assertThat(message.getPayload()).isEqualTo("baz");

    partOutputChannel.send(new GenericMessage<>("0"));
    partOutputChannel.send(new GenericMessage<>("1"));
    message = partInputChannel0.receive(10000);
    assertThat(message).isNotNull();
    assertThat(message.getPayload()).isEqualTo("0");
    message = partInputChannel1.receive(10000);
    assertThat(message).isNotNull();
    assertThat(message.getPayload()).isEqualTo("1");

    late0ProducerBinding.unbind();
    late0ConsumerBinding.unbind();
    partlate0ProducerBinding.unbind();
    partlate0Consumer0Binding.unbind();
    partlate0Consumer1Binding.unbind();
    noDlqProducerBinding.unbind();
    noDlqConsumerBinding.unbind();
    pubSubProducerBinding.unbind();
    nonDurableConsumerBinding.unbind();
    durableConsumerBinding.unbind();

    binder.cleanup();

    proxy.stop();
    cf.destroy();

    this.rabbitAvailableRule.getResource().destroy();
}

From source file:org.springframework.integration.aggregator.AggregatorTests.java

@Test
public void testCompleteGroupWithinTimeout() throws InterruptedException {
    QueueChannel replyChannel = new QueueChannel();
    Message<?> message1 = createMessage(3, "ABC", 3, 1, replyChannel, null);
    Message<?> message2 = createMessage(5, "ABC", 3, 2, replyChannel, null);
    Message<?> message3 = createMessage(7, "ABC", 3, 3, replyChannel, null);

    this.aggregator.handleMessage(message1);
    this.aggregator.handleMessage(message2);
    this.aggregator.handleMessage(message3);

    Message<?> reply = replyChannel.receive(10000);
    assertNotNull(reply);/* www  . ja  v a 2  s  .c  o m*/
    assertEquals(reply.getPayload(), 105);
}

From source file:org.springframework.integration.aggregator.AggregatorTests.java

@Test
public void testShouldNotSendPartialResultOnTimeoutByDefault() throws InterruptedException {
    QueueChannel discardChannel = new QueueChannel();
    this.aggregator.setDiscardChannel(discardChannel);
    QueueChannel replyChannel = new QueueChannel();
    Message<?> message = createMessage(3, "ABC", 2, 1, replyChannel, null);
    this.aggregator.handleMessage(message);
    this.store.expireMessageGroups(-10000);
    Message<?> reply = replyChannel.receive(1000);
    assertNull("No message should have been sent normally", reply);
    Message<?> discardedMessage = discardChannel.receive(1000);
    assertNotNull("A message should have been discarded", discardedMessage);
    assertEquals(message, discardedMessage);
    assertEquals(1, expiryEvents.size());
    assertSame(this.aggregator, expiryEvents.get(0).getSource());
    assertEquals("ABC", this.expiryEvents.get(0).getGroupId());
    assertEquals(1, this.expiryEvents.get(0).getMessageCount());
    assertEquals(true, this.expiryEvents.get(0).isDiscarded());
}

From source file:org.springframework.integration.aggregator.AggregatorTests.java

@Test
public void testShouldSendPartialResultOnTimeoutTrue() throws InterruptedException {
    this.aggregator.setSendPartialResultOnExpiry(true);
    QueueChannel replyChannel = new QueueChannel();
    Message<?> message1 = createMessage(3, "ABC", 3, 1, replyChannel, null);
    Message<?> message2 = createMessage(5, "ABC", 3, 2, replyChannel, null);
    this.aggregator.handleMessage(message1);
    this.aggregator.handleMessage(message2);
    this.store.expireMessageGroups(-10000);
    Message<?> reply = replyChannel.receive(1000);
    assertNotNull("A reply message should have been received", reply);
    assertEquals(15, reply.getPayload());
    assertEquals(1, expiryEvents.size());
    assertSame(this.aggregator, expiryEvents.get(0).getSource());
    assertEquals("ABC", this.expiryEvents.get(0).getGroupId());
    assertEquals(2, this.expiryEvents.get(0).getMessageCount());
    assertEquals(false, this.expiryEvents.get(0).isDiscarded());
    Message<?> message3 = createMessage(5, "ABC", 3, 3, replyChannel, null);
    this.aggregator.handleMessage(message3);
    assertEquals(1, this.store.getMessageGroup("ABC").size());
}

From source file:org.springframework.integration.aggregator.AggregatorTests.java

@Test
public void testGroupRemainsAfterTimeout() throws InterruptedException {
    this.aggregator.setSendPartialResultOnExpiry(true);
    this.aggregator.setExpireGroupsUponTimeout(false);
    QueueChannel replyChannel = new QueueChannel();
    QueueChannel discardChannel = new QueueChannel();
    this.aggregator.setDiscardChannel(discardChannel);
    Message<?> message1 = createMessage(3, "ABC", 3, 1, replyChannel, null);
    Message<?> message2 = createMessage(5, "ABC", 3, 2, replyChannel, null);
    this.aggregator.handleMessage(message1);
    this.aggregator.handleMessage(message2);
    this.store.expireMessageGroups(-10000);
    Message<?> reply = replyChannel.receive(1000);
    assertNotNull("A reply message should have been received", reply);
    assertEquals(15, reply.getPayload());
    assertEquals(1, expiryEvents.size());
    assertSame(this.aggregator, expiryEvents.get(0).getSource());
    assertEquals("ABC", this.expiryEvents.get(0).getGroupId());
    assertEquals(2, this.expiryEvents.get(0).getMessageCount());
    assertEquals(false, this.expiryEvents.get(0).isDiscarded());
    assertEquals(0, this.store.getMessageGroup("ABC").size());
    Message<?> message3 = createMessage(5, "ABC", 3, 3, replyChannel, null);
    this.aggregator.handleMessage(message3);
    assertEquals(0, this.store.getMessageGroup("ABC").size());
    Message<?> discardedMessage = discardChannel.receive(1000);
    assertNotNull("A message should have been discarded", discardedMessage);
    assertSame(message3, discardedMessage);
}