Example usage for org.springframework.messaging.support GenericMessage GenericMessage

List of usage examples for org.springframework.messaging.support GenericMessage GenericMessage

Introduction

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

Prototype

public GenericMessage(T payload) 

Source Link

Document

Create a new message with the given payload.

Usage

From source file:io.riox.springxd.sinks.websocket.WebsocketSinkTests.java

@Test
public void testMultiplePaths() throws Exception {

    final List<String> messages1 = new ArrayList<String>();
    final List<String> messages2 = new ArrayList<String>();

    Field f1 = WebsocketSink.class.getDeclaredField("port");
    f1.setAccessible(true);/*from   w  w w.  ja v  a  2 s .  co  m*/
    Field f2 = WebsocketSink.class.getDeclaredField("path");
    f2.setAccessible(true);

    WebsocketSink sink1 = configs.get(0).sink;
    WebsocketSink sink2 = configs.get(1).sink;

    Method m1 = WebsocketSink.class.getDeclaredMethod("input");
    m1.setAccessible(true);
    final MessageChannel channel1 = (MessageChannel) m1.invoke(sink1);
    final MessageChannel channel2 = (MessageChannel) m1.invoke(sink2);

    URI uri1 = new URI("http://localhost:" + configs.get(0).port + configs.get(0).path);
    URI uri2 = new URI("http://localhost:" + configs.get(1).port + configs.get(1).path);
    URI uri3 = new URI("http://localhost:" + configs.get(1).port + "/invalid_path");

    /* create WS clients */
    final int numMsg1 = 2000;
    final int numMsg2 = 3000;
    final CountDownLatch connectLatch = new CountDownLatch(3);
    final CountDownLatch messagesLatch = new CountDownLatch(numMsg1 + numMsg2);
    WebSocketClient c1 = new WebSocketClient(uri1) {
        public void onMessage(String msg) {
            messages1.add(msg);
            messagesLatch.countDown();
        }

        public void onClose(int arg0, String arg1, boolean arg2) {
        }

        public void onError(Exception e) {
        }

        public void onOpen(ServerHandshake arg0) {
            connectLatch.countDown();
        }
    };
    c1.connect();
    WebSocketClient c2 = new WebSocketClient(uri2) {
        public void onMessage(String msg) {
            messages2.add(msg);
            messagesLatch.countDown();
        }

        public void onClose(int arg0, String arg1, boolean arg2) {
        }

        public void onError(Exception e) {
        }

        public void onOpen(ServerHandshake arg0) {
            connectLatch.countDown();
        }
    };
    c2.connect();
    WebSocketClient c3 = new WebSocketClient(uri3) {
        public void onMessage(String msg) {
            messagesLatch.countDown();
        }

        public void onClose(int arg0, String arg1, boolean arg2) {
        }

        public void onError(Exception e) {
            e.printStackTrace();
        }

        public void onOpen(ServerHandshake arg0) {
            connectLatch.countDown();
        }
    };
    c3.connect();
    connectLatch.await(1, TimeUnit.SECONDS);

    /* send test messages */
    new Thread() {
        public void run() {
            for (int i = 0; i < numMsg1; i++) {
                channel1.send(new GenericMessage<String>("foo"));
            }
        }
    }.start();
    new Thread() {
        public void run() {
            for (int i = 0; i < numMsg2; i++) {
                channel2.send(new GenericMessage<String>("bar"));
            }
        }
    }.start();

    /* assertions */
    assertTrue(messagesLatch.await(5, TimeUnit.SECONDS));
    assertEquals(numMsg1, messages1.size());
    assertEquals(numMsg2, messages2.size());
    for (String m : messages1) {
        assertEquals("foo", m);
    }
    for (String m : messages2) {
        assertEquals("bar", m);
    }

}

From source file:org.springframework.integration.aws.outbound.S3MessageHandlerTests.java

@Test
public void testCopy() throws InterruptedException {
    Map<String, String> payload = new HashMap<>();
    payload.put("key", "mySource");
    payload.put("destination", "theirBucket");
    payload.put("destinationKey", "theirTarget");
    this.s3ProcessChannel.send(new GenericMessage<>(payload));

    Message<?> receive = this.s3ReplyChannel.receive(10000);
    assertThat(receive).isNotNull();/*from w w  w.j  a v a 2 s  .  co m*/

    assertThat(receive.getPayload()).isInstanceOf(Copy.class);
    Copy copy = (Copy) receive.getPayload();
    assertThat(copy.getDescription())
            .isEqualTo("Copying object from myBucket/mySource to theirBucket/theirTarget");

    copy.waitForCompletion();

    assertThat(copy.getState()).isEqualTo(Transfer.TransferState.Completed);
}

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

@Test
public void testTwitterChannel() {
    log.debug("testTwitterChannel");
    MessageChannel twitterOutChannel = this.twitterTransformedChannel;
    Message<String> twitterUpdate = new GenericMessage<String>(
            "22 Testing  http://www.google.es new Twitter samples for #springintegration "
                    + RandomStringUtils.random(2));
    log.debug("twitterOutChannel message " + twitterUpdate.getPayload());
    twitterOutChannel.send(twitterUpdate);
    log.debug("twitterOutChannel");
}

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

@Test
public void testTwitterChannel() {
    //System.out.println("testTwitterChannel");
    MessageChannel twitterOutChannel = this.twitterTransformedChannel;
    Message<String> twitterUpdate = new GenericMessage<String>("Testing new Twitter "
            + "http://www.google.es samples for #springintegration " + RandomStringUtils.random(4));
    //System.out.println("twitterOutChannel message "+twitterUpdate.getPayload());
    twitterOutChannel.send(twitterUpdate);
    //System.out.println("twitterOutChannel");
}

From source file:org.springframework.batch.integration.chunk.ChunkMessageChannelItemWriter.java

public void write(List<? extends T> items) throws Exception {

    // Block until expecting <= throttle limit
    while (localState.getExpecting() > throttleLimit) {
        getNextResult();//from www.  j av a 2s  .  c om
    }

    if (!items.isEmpty()) {

        ChunkRequest<T> request = localState.getRequest(items);
        if (logger.isDebugEnabled()) {
            logger.debug("Dispatching chunk: " + request);
        }
        messagingGateway.send(new GenericMessage<ChunkRequest<T>>(request));
        localState.incrementExpected();

    }

}

From source file:org.springframework.cloud.stream.app.tcp.client.processor.TcpClientTests.java

protected void doTest(AbstractByteArraySerializer encoderDecoder, String prefix, String payload, String suffix)
        throws Exception {
    server.setEncoder(encoderDecoder);//  w  w  w. ja  va 2s.  c  o  m
    server.setDecoder(encoderDecoder);
    server.setPrefix(prefix);
    server.setSuffix(suffix);
    Message<String> messageToSend = new GenericMessage<>(payload);
    assertTrue(channels.input().send(messageToSend));
    assertThat(this.messageCollector.forChannel(channels.output()),
            receivesPayloadThat(is((payload + "-received").getBytes())));
    server.serverSocket.close();
}

From source file:org.springframework.cloud.stream.app.tcp.sink.TcpSinkTests.java

protected void doTest(AbstractByteArraySerializer decoder) throws Exception {
    server.setDecoder(decoder);/*w  ww.  j a  v  a 2 s .  c om*/
    Message<String> message = new GenericMessage<>("foo");
    assertTrue(channels.input().send(message));
    String received = server.queue.poll(10, TimeUnit.SECONDS);
    assertEquals("foo", received);

    assertTrue(channels.input().send(message));
    received = server.queue.poll(10, TimeUnit.SECONDS);
    assertEquals("foo", received);
}

From source file:org.springframework.cloud.stream.app.throughput.sink.ThroughputSinkTests.java

@Test
public void testSink() throws Exception {
    assertNotNull(this.sink.input());
    this.sink.input().send(new GenericMessage<>("foo"));
    Log logger = spy(TestUtils.getPropertyValue(this.configuration, "logger", Log.class));
    new DirectFieldAccessor(this.configuration).setPropertyValue("logger", logger);
    final CountDownLatch latch = new CountDownLatch(1);
    doAnswer(new Answer<Void>() {

        @Override//www .j  a  va2  s.  c  om
        public Void answer(InvocationOnMock invocation) throws Throwable {
            invocation.callRealMethod();
            latch.countDown();
            return null;
        }

    }).when(logger).info(anyString());
    assertTrue(latch.await(10, TimeUnit.SECONDS));
}

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

@Test
public void testProducerProperties() throws Exception {
    RabbitTestBinder binder = getBinder();
    Binding<MessageChannel> producerBinding = binder.bindProducer("props.0",
            createBindableChannel("input", new BindingProperties()), createProducerProperties());
    Lifecycle endpoint = extractEndpoint(producerBinding);
    MessageDeliveryMode mode = TestUtils.getPropertyValue(endpoint, "defaultDeliveryMode",
            MessageDeliveryMode.class);
    assertThat(mode).isEqualTo(MessageDeliveryMode.PERSISTENT);
    List<?> requestHeaders = TestUtils.getPropertyValue(endpoint, "headerMapper.requestHeaderMatcher.matchers",
            List.class);
    assertThat(requestHeaders).hasSize(2);
    producerBinding.unbind();//  w  w  w  . java  2 s .  co  m
    assertThat(endpoint.isRunning()).isFalse();
    assertThat(TestUtils.getPropertyValue(endpoint, "amqpTemplate.transactional", Boolean.class)).isFalse();

    ExtendedProducerProperties<RabbitProducerProperties> producerProperties = createProducerProperties();
    producerProperties.getExtension().setPrefix("foo.");
    producerProperties.getExtension().setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);
    producerProperties.getExtension().setHeaderPatterns(new String[] { "foo" });
    producerProperties.setPartitionKeyExpression(spelExpressionParser.parseExpression("'foo'"));
    producerProperties.setPartitionKeyExtractorClass(TestPartitionKeyExtractorClass.class);
    producerProperties.setPartitionSelectorExpression(spelExpressionParser.parseExpression("0"));
    producerProperties.setPartitionSelectorClass(TestPartitionSelectorClass.class);
    producerProperties.setPartitionCount(1);
    producerProperties.getExtension().setTransacted(true);
    producerProperties.getExtension().setDelayExpression("42");
    producerProperties.setRequiredGroups("prodPropsRequired");

    BindingProperties producerBindingProperties = createProducerBindingProperties(producerProperties);
    DirectChannel channel = createBindableChannel("output", producerBindingProperties);
    producerBinding = binder.bindProducer("props.0", channel, producerProperties);
    endpoint = extractEndpoint(producerBinding);
    assertThat(getEndpointRouting(endpoint))
            .isEqualTo("'props.0-' + headers['" + BinderHeaders.PARTITION_HEADER + "']");
    assertThat(
            TestUtils.getPropertyValue(endpoint, "delayExpression", SpelExpression.class).getExpressionString())
                    .isEqualTo("42");
    mode = TestUtils.getPropertyValue(endpoint, "defaultDeliveryMode", MessageDeliveryMode.class);
    assertThat(mode).isEqualTo(MessageDeliveryMode.NON_PERSISTENT);
    assertThat(TestUtils.getPropertyValue(endpoint, "amqpTemplate.transactional", Boolean.class)).isTrue();
    verifyFooRequestProducer(endpoint);
    channel.send(new GenericMessage<>("foo"));
    org.springframework.amqp.core.Message received = new RabbitTemplate(this.rabbitAvailableRule.getResource())
            .receive("foo.props.0.prodPropsRequired-0", 10_000);
    assertThat(received).isNotNull();
    assertThat(received.getMessageProperties().getReceivedDelay()).isEqualTo(42);

    producerBinding.unbind();
    assertThat(endpoint.isRunning()).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 ww  . j  av a  2  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();
}