Example usage for org.springframework.messaging PollableChannel receive

List of usage examples for org.springframework.messaging PollableChannel receive

Introduction

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

Prototype

@Nullable
Message<?> receive(long timeout);

Source Link

Document

Receive a message from this channel, blocking until either a message is available or the specified timeout period elapses.

Usage

From source file:helloworld.HelloWorldApp.java

public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("spring-integration-helloword-context.xml");
    MessageChannel inputChannel = context.getBean("inputChannel", MessageChannel.class);
    PollableChannel outputChannel = context.getBean("outputChannel", PollableChannel.class);
    inputChannel.send(new GenericMessage<String>("World"));
    System.out.println("==> HelloWorldDemo: " + outputChannel.receive(0).getPayload());
}

From source file:com.github.exper0.efilecopier.ftp.FtpInboundChannelAdapterSample.java

@Test
public void runDemo() throws Exception {
    Files.copy(this.getClass().getResourceAsStream("/test-files/a.txt"),
            Paths.get(TestSuite.FTP_ROOT_DIR, "a.txt"));
    Files.copy(this.getClass().getResourceAsStream("/test-files/b.txt"),
            Paths.get(TestSuite.FTP_ROOT_DIR, "b.txt"));
    FtpReportSettings settings = new FtpReportSettings();
    settings.setPort(4444);//from  w ww.  ja  va  2s. c o  m
    settings.setHost("localhost");
    settings.setLocalDir(LOCAL_FTP_TEMP_DIR + "/ftpInbound");
    settings.setRemoteDir("/");
    settings.setUser("demo");
    settings.setPassword("demo");
    FtpAdapterFactory factory = new FtpAdapterFactory();
    try (FileAdapter adapter = factory.createAdapter(settings)) {
        adapter.activate();
        PollableChannel ftpChannel = adapter.channel();
        Message<?> message1 = ftpChannel.receive(2000);
        Message<?> message2 = ftpChannel.receive(2000);
        Message<?> message3 = ftpChannel.receive(1000);

        LOGGER.info(String.format("Received first file message: %s.", message1));
        LOGGER.info(String.format("Received second file message: %s.", message2));
        LOGGER.info(String.format("Received nothing else: %s.", message3));

        assertNotNull(message1);
        assertNotNull(message2);
        assertNull("Was NOT expecting a third message.", message3);
    }
}

From source file:org.springframework.cloud.gcp.autoconfigure.pubsub.it.PubSubChannelAdaptersIntegrationTests.java

@Test
public void sendAndReceiveMessageManualAck() {
    this.contextRunner.run((context) -> {
        try {/*ww  w .j  av  a  2 s .  c o m*/
            context.getBean(PubSubInboundChannelAdapter.class).setAckMode(AckMode.MANUAL);
            context.getBean("inputChannel", MessageChannel.class)
                    .send(MessageBuilder.withPayload("I am a message.".getBytes()).build());

            PollableChannel channel = context.getBean("outputChannel", PollableChannel.class);

            Message<?> message = channel.receive(10000);
            assertThat(message).isNotNull();
            BasicAcknowledgeablePubsubMessage origMessage = (BasicAcknowledgeablePubsubMessage) message
                    .getHeaders().get(GcpPubSubHeaders.ORIGINAL_MESSAGE);
            assertThat(origMessage).isNotNull();
            origMessage.nack();

            message = channel.receive(10000);
            assertThat(message).isNotNull();
            origMessage = (BasicAcknowledgeablePubsubMessage) message.getHeaders()
                    .get(GcpPubSubHeaders.ORIGINAL_MESSAGE);
            assertThat(origMessage).isNotNull();
            origMessage.ack();

            message = channel.receive(10000);
            assertThat(message).isNull();
        } finally {
            PubSubAdmin pubSubAdmin = context.getBean(PubSubAdmin.class);
            pubSubAdmin.deleteSubscription((String) context.getBean("subscriptionName"));
            pubSubAdmin.deleteTopic((String) context.getBean("topicName"));
        }
    });
}

From source file:org.springframework.cloud.gcp.autoconfigure.pubsub.it.PubSubChannelAdaptersIntegrationTests.java

@Test
@SuppressWarnings("deprecation")
public void sendAndReceiveMessageManualAckThroughAcknowledgementHeader() {
    this.contextRunner.run((context) -> {
        try {//from w w w.  java 2s .c o m
            context.getBean(PubSubInboundChannelAdapter.class).setAckMode(AckMode.MANUAL);
            context.getBean("inputChannel", MessageChannel.class)
                    .send(MessageBuilder.withPayload("I am a message.".getBytes()).build());

            PollableChannel channel = context.getBean("outputChannel", PollableChannel.class);

            Message<?> message = channel.receive(10000);
            assertThat(message).isNotNull();
            AckReplyConsumer acker = (AckReplyConsumer) message.getHeaders()
                    .get(GcpPubSubHeaders.ACKNOWLEDGEMENT);
            assertThat(acker).isNotNull();
            acker.ack();

            message = channel.receive(10000);
            assertThat(message).isNull();

            validateOutput("ACKNOWLEDGEMENT header is deprecated");
        } finally {
            PubSubAdmin pubSubAdmin = context.getBean(PubSubAdmin.class);
            pubSubAdmin.deleteSubscription((String) context.getBean("subscriptionName"));
            pubSubAdmin.deleteTopic((String) context.getBean("topicName"));
        }
    });
}

From source file:org.springframework.cloud.stream.binder.AbstractBinderTests.java

/**
 * Attempt to receive a message on the given channel,
 * waiting up to 1s * additionalMultiplier * {@link #timeoutMultiplier}).
 *
 * Allows accomodating tests which are slower than normal (e.g. retry).
 *//*  w w  w.  j a  va 2 s  .com*/
protected Message<?> receive(PollableChannel channel, int additionalMultiplier) {
    long startTime = System.currentTimeMillis();
    Message<?> receive = channel.receive((int) (1000 * timeoutMultiplier * additionalMultiplier));
    long elapsed = System.currentTimeMillis() - startTime;
    logger.debug("receive() took " + elapsed / 1000 + " seconds");
    return receive;
}

From source file:org.springframework.integration.config.xml.GatewayParserTests.java

@Test
public void testOneWay() {
    TestService service = (TestService) context.getBean("oneWay");
    service.oneWay("foo");
    PollableChannel channel = (PollableChannel) context.getBean("requestChannel");
    Message<?> result = channel.receive(1000);
    assertEquals("foo", result.getPayload());
}

From source file:org.springframework.integration.config.xml.GatewayParserTests.java

@Test
public void testOneWayOverride() {
    TestService service = (TestService) context.getBean("methodOverride");
    service.oneWay("foo");
    PollableChannel channel = (PollableChannel) context.getBean("otherRequestChannel");
    Message<?> result = channel.receive(1000);
    assertEquals("fiz", result.getPayload());
    assertEquals("bar", result.getHeaders().get("foo"));
    assertEquals("qux", result.getHeaders().get("baz"));
    GatewayProxyFactoryBean fb = context.getBean("&methodOverride", GatewayProxyFactoryBean.class);
    Map<?, ?> methods = TestUtils.getPropertyValue(fb, "methodMetadataMap", Map.class);
    GatewayMethodMetadata meta = (GatewayMethodMetadata) methods.get("oneWay");
    assertNotNull(meta);//from w  w  w  .  j  a v a2 s .co  m
    assertEquals("456", meta.getRequestTimeout());
    assertEquals("123", meta.getReplyTimeout());
    assertEquals("foo", meta.getReplyChannelName());
}

From source file:org.springframework.integration.config.xml.GatewayParserTests.java

private void startResponder(final PollableChannel requestChannel, final MessageChannel replyChannel) {
    Executors.newSingleThreadExecutor().execute(() -> {
        Message<?> request = requestChannel.receive(60000);
        assertNotNull("Request not received", request);
        Message<?> reply = MessageBuilder.fromMessage(request).setCorrelationId(request.getHeaders().getId())
                .build();//from  ww w  .j  av  a 2  s  .c  o  m
        Object payload = null;
        if (request.getPayload().equals("futureSync")) {
            payload = new AsyncResult<Message<?>>(reply);
        } else if (request.getPayload().equals("flowCompletable")) {
            payload = CompletableFuture.<String>completedFuture("SYNC_COMPLETABLE");
        } else if (request.getPayload().equals("flowCustomCompletable")) {
            MyCompletableFuture myCompletableFuture1 = new MyCompletableFuture();
            myCompletableFuture1.complete("SYNC_CUSTOM_COMPLETABLE");
            payload = myCompletableFuture1;
        } else if (request.getPayload().equals("flowCompletableM")) {
            payload = CompletableFuture.<Message<?>>completedFuture(reply);
        } else if (request.getPayload().equals("flowCustomCompletableM")) {
            MyCompletableMessageFuture myCompletableFuture2 = new MyCompletableMessageFuture();
            myCompletableFuture2.complete(reply);
            payload = myCompletableFuture2;
        }
        if (payload != null) {
            reply = MessageBuilder.withPayload(payload).copyHeaders(reply.getHeaders()).build();
        }
        replyChannel.send(reply);
    });
}

From source file:org.springframework.integration.configuration.EnableIntegrationTests.java

@Test
public void testBridgeAnnotations() {
    GenericMessage<?> testMessage = new GenericMessage<Object>("foo");
    this.bridgeInput.send(testMessage);
    Message<?> receive = this.bridgeOutput.receive(2000);
    assertNotNull(receive);/*w ww  .  j  a  v a  2 s .  c  o  m*/
    assertSame(receive, testMessage);
    assertNull(this.bridgeOutput.receive(10));

    this.pollableBridgeInput.send(testMessage);
    receive = this.pollableBridgeOutput.receive(2000);
    assertNotNull(receive);
    assertSame(receive, testMessage);
    assertNull(this.pollableBridgeOutput.receive(10));

    try {
        this.metaBridgeInput.send(testMessage);
        fail("MessageDeliveryException expected");
    } catch (Exception e) {
        assertThat(e, Matchers.instanceOf(MessageDeliveryException.class));
        assertThat(e.getMessage(), Matchers.containsString("Dispatcher has no subscribers"));
    }

    this.context
            .getBean("enableIntegrationTests.ContextConfiguration.metaBridgeOutput.bridgeFrom", Lifecycle.class)
            .start();

    this.metaBridgeInput.send(testMessage);
    receive = this.metaBridgeOutput.receive(2000);
    assertNotNull(receive);
    assertSame(receive, testMessage);
    assertNull(this.metaBridgeOutput.receive(10));

    this.bridgeToInput.send(testMessage);
    receive = this.bridgeToOutput.receive(2000);
    assertNotNull(receive);
    assertSame(receive, testMessage);
    assertNull(this.bridgeToOutput.receive(10));

    PollableChannel replyChannel = new QueueChannel();
    Message<?> bridgeMessage = MessageBuilder.fromMessage(testMessage).setReplyChannel(replyChannel).build();
    this.pollableBridgeToInput.send(bridgeMessage);
    receive = replyChannel.receive(2000);
    assertNotNull(receive);
    assertSame(receive, bridgeMessage);
    assertNull(replyChannel.receive(10));

    try {
        this.myBridgeToInput.send(testMessage);
        fail("MessageDeliveryException expected");
    } catch (Exception e) {
        assertThat(e, Matchers.instanceOf(MessageDeliveryException.class));
        assertThat(e.getMessage(), Matchers.containsString("Dispatcher has no subscribers"));
    }

    this.context
            .getBean("enableIntegrationTests.ContextConfiguration.myBridgeToInput.bridgeTo", Lifecycle.class)
            .start();

    this.myBridgeToInput.send(bridgeMessage);
    receive = replyChannel.receive(2000);
    assertNotNull(receive);
    assertSame(receive, bridgeMessage);
    assertNull(replyChannel.receive(10));
}

From source file:org.springframework.integration.dsl.test.IntegrationFlowTests.java

@Test
public void testGatewayFlow() throws Exception {
    PollableChannel replyChannel = new QueueChannel();
    Message<String> message = MessageBuilder.withPayload("foo").setReplyChannel(replyChannel).build();

    this.gatewayInput.send(message);

    Message<?> receive = replyChannel.receive(2000);
    assertNotNull(receive);// ww w  .j  a  v  a2 s. c  o  m
    assertEquals("FOO", receive.getPayload());
    assertNull(this.gatewayError.receive(1));

    message = MessageBuilder.withPayload("bar").setReplyChannel(replyChannel).build();

    this.gatewayInput.send(message);

    receive = replyChannel.receive(1);
    assertNull(receive);

    receive = this.gatewayError.receive(2000);
    assertNotNull(receive);
    assertThat(receive, instanceOf(ErrorMessage.class));
    assertThat(receive.getPayload(), instanceOf(MessageRejectedException.class));
    assertThat(((Exception) receive.getPayload()).getMessage(), containsString("' rejected Message"));
}