Example usage for org.springframework.integration.support MessageBuilder withPayload

List of usage examples for org.springframework.integration.support MessageBuilder withPayload

Introduction

In this page you can find the example usage for org.springframework.integration.support MessageBuilder withPayload.

Prototype

public static <T> MessageBuilder<T> withPayload(T payload) 

Source Link

Document

Create a builder for a new Message instance with the provided payload.

Usage

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

@Test
public void testSendAndReceive() throws Exception {
    Binder binder = getBinder();//from w  w  w.ja  va  2  s  .  co m
    BindingProperties outputBindingProperties = createProducerBindingProperties(createProducerProperties());
    DirectChannel moduleOutputChannel = createBindableChannel("output", outputBindingProperties);
    QueueChannel moduleInputChannel = new QueueChannel();
    Binding<MessageChannel> producerBinding = binder.bindProducer("foo.0", moduleOutputChannel,
            outputBindingProperties.getProducer());
    Binding<MessageChannel> consumerBinding = binder.bindConsumer("foo.0", "test", moduleInputChannel,
            createConsumerProperties());
    Message<?> message = MessageBuilder.withPayload("foo").setHeader(MessageHeaders.CONTENT_TYPE, "foo/bar")
            .build();
    // Let the consumer actually bind to the producer before sending a msg
    binderBindUnbindLatency();
    moduleOutputChannel.send(message);
    Message<?> inbound = receive(moduleInputChannel);
    assertThat(inbound).isNotNull();
    assertThat(inbound.getPayload()).isEqualTo("foo");
    assertThat(inbound.getHeaders().get(BinderHeaders.BINDER_ORIGINAL_CONTENT_TYPE)).isNull();
    assertThat(inbound.getHeaders().get(MessageHeaders.CONTENT_TYPE)).isEqualTo("foo/bar");
    producerBinding.unbind();
    consumerBinding.unbind();
}

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

@Test
public void testSendAndReceiveMultipleTopics() throws Exception {
    Binder binder = getBinder();/*from   w  w  w. ja va2s.  co m*/

    DirectChannel moduleOutputChannel1 = createBindableChannel("output1",
            createProducerBindingProperties(createProducerProperties()));
    DirectChannel moduleOutputChannel2 = createBindableChannel("output2",
            createProducerBindingProperties(createProducerProperties()));

    QueueChannel moduleInputChannel = new QueueChannel();

    Binding<MessageChannel> producerBinding1 = binder.bindProducer("foo.x", moduleOutputChannel1,
            createProducerProperties());
    Binding<MessageChannel> producerBinding2 = binder.bindProducer("foo.y", moduleOutputChannel2,
            createProducerProperties());

    Binding<MessageChannel> consumerBinding1 = binder.bindConsumer("foo.x", "test", moduleInputChannel,
            createConsumerProperties());
    Binding<MessageChannel> consumerBinding2 = binder.bindConsumer("foo.y", "test", moduleInputChannel,
            createConsumerProperties());

    String testPayload1 = "foo" + UUID.randomUUID().toString();
    Message<?> message1 = MessageBuilder.withPayload(testPayload1.getBytes()).build();
    String testPayload2 = "foo" + UUID.randomUUID().toString();
    Message<?> message2 = MessageBuilder.withPayload(testPayload2.getBytes()).build();

    // Let the consumer actually bind to the producer before sending a msg
    binderBindUnbindLatency();
    moduleOutputChannel1.send(message1);
    moduleOutputChannel2.send(message2);

    Message<?>[] messages = new Message[2];
    messages[0] = receive(moduleInputChannel);
    messages[1] = receive(moduleInputChannel);

    assertThat(messages[0]).isNotNull();
    assertThat(messages[1]).isNotNull();
    assertThat(messages).extracting("payload").containsExactlyInAnyOrder(testPayload1.getBytes(),
            testPayload2.getBytes());

    producerBinding1.unbind();
    producerBinding2.unbind();

    consumerBinding1.unbind();
    consumerBinding2.unbind();
}

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

@Test
public void testSendAndReceiveNoOriginalContentType() throws Exception {
    Binder binder = getBinder();//from   w  w  w.  jav  a  2  s  .com

    BindingProperties producerBindingProperties = createProducerBindingProperties(createProducerProperties());
    DirectChannel moduleOutputChannel = createBindableChannel("output", producerBindingProperties);
    QueueChannel moduleInputChannel = new QueueChannel();
    Binding<MessageChannel> producerBinding = binder.bindProducer("bar.0", moduleOutputChannel,
            producerBindingProperties.getProducer());
    Binding<MessageChannel> consumerBinding = binder.bindConsumer("bar.0", "test", moduleInputChannel,
            createConsumerProperties());
    binderBindUnbindLatency();

    Message<?> message = MessageBuilder.withPayload("foo").build();
    moduleOutputChannel.send(message);
    Message<?> inbound = receive(moduleInputChannel);
    assertThat(inbound).isNotNull();
    assertThat(inbound.getPayload()).isEqualTo("foo");
    assertThat(inbound.getHeaders().get(BinderHeaders.BINDER_ORIGINAL_CONTENT_TYPE)).isNull();
    assertThat(inbound.getHeaders().get(MessageHeaders.CONTENT_TYPE)).isEqualTo(MimeTypeUtils.TEXT_PLAIN_VALUE);
    producerBinding.unbind();
    consumerBinding.unbind();
}

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();/*from  w  w w . j  a  v a2s.  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.reactive.FluxToMessageChannelResultAdapter.java

public void adapt(Flux<?> streamListenerResult, MessageChannel bindingTarget) {
    streamListenerResult.doOnError(e -> this.log.error("Error while processing result", e)).retry()
            .subscribe(result -> bindingTarget.send(result instanceof Message<?> ? (Message<?>) result
                    : MessageBuilder.withPayload(result).build()));
}

From source file:org.springframework.cloud.stream.reactive.MessageChannelToFluxSenderParameterAdapter.java

@Override
public FluxSender adapt(MessageChannel bindingTarget, MethodParameter parameter) {
    return resultPublisher -> {
        MonoProcessor<Void> sendResult = MonoProcessor.create();
        // add error handling and reconnect in the event of an error
        resultPublisher.doOnError(e -> this.log.error("Error during processing: ", e)).retry().subscribe(
                result -> bindingTarget.send(result instanceof Message<?> ? (Message<?>) result
                        : MessageBuilder.withPayload(result).build()),
                e -> sendResult.onError(e), () -> sendResult.onComplete());
        return sendResult;
    };//from   w  w  w  .j a  v a  2 s.co m
}

From source file:org.springframework.cloud.stream.reactive.PublisherToMessageChannelResultAdapter.java

public Closeable adapt(Publisher<?> streamListenerResult, MessageChannel bindingTarget) {
    Disposable disposable = Flux.from(streamListenerResult)
            .doOnError(e -> this.log.error("Error while processing result", e)).retry()
            .subscribe(result -> bindingTarget.send(result instanceof Message<?> ? (Message<?>) result
                    : MessageBuilder.withPayload(result).build()));

    return disposable::dispose;
}

From source file:org.springframework.flex.messaging.integration.IntegrationAdapter.java

/**
 * Invoked when a Message is received from a Flex client.
 *//*from  w ww .j av a 2s. c om*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public Object invoke(flex.messaging.messages.Message flexMessage) {
    if (logger.isDebugEnabled()) {
        logger.debug("received Flex Message: " + flexMessage);
    }
    Message<?> message = null;
    if (this.extractPayload) {
        Map headers = flexMessage.getHeaders();
        headers.put(FlexHeaders.MESSAGE_CLIENT_ID, flexMessage.getClientId());
        headers.put(FlexHeaders.DESTINATION_ID, flexMessage.getDestination());
        headers.put(FlexHeaders.MESSAGE_ID, flexMessage.getMessageId());
        headers.put(FlexHeaders.TIMESTAMP, String.valueOf(flexMessage.getTimestamp()));
        if (FlexContext.getFlexClient() != null) {
            headers.put(FlexHeaders.FLEX_CLIENT_ID, FlexContext.getFlexClient().getId());
        }
        long timestamp = flexMessage.getTimestamp();
        message = MessageBuilder.withPayload(flexMessage.getBody()).copyHeaders(headers)
                .setExpirationDate(timestamp + flexMessage.getTimeToLive()).build();
    } else {
        message = new GenericMessage<flex.messaging.messages.Message>(flexMessage);
    }
    this.messageChannel.send(message);
    return null;
}

From source file:org.springframework.integration.activiti.gateway.AbstractActivityBehaviorMessagingGateway.java

protected MessageBuilder<?> doBasicOutboundMessageConstruction(ActivityExecution execution) throws Exception {
    Map<String, ?> headers = headerMapper.toHeaders(execution.getVariables());
    return MessageBuilder.withPayload(execution)
            .copyHeadersIfAbsent(contributeHeadersForOutboundMessage(execution)).copyHeaders(headers);
}

From source file:org.springframework.integration.activiti.utils.PrintingServiceActivator.java

@ServiceActivator
public Message<?> sayHello(Message<?> requestComingFromActiviti) throws Throwable {

    log.debug("entering ServiceActivator:sayHello");

    if (StringUtils.hasText(this.whatToPrint))
        log.debug(whatToPrint);/*from   w w w. j  ava  2s  .  com*/

    Map<String, Object> headers = requestComingFromActiviti.getHeaders();

    for (String k : headers.keySet())
        log.debug(String.format("%s = %s", k, headers.get(k)));

    log.debug("exiting ServiceActivator:sayHello");

    return MessageBuilder.withPayload(requestComingFromActiviti.getPayload())
            .copyHeadersIfAbsent(requestComingFromActiviti.getHeaders())
            .setHeader(ActivitiConstants.WELL_KNOWN_SPRING_INTEGRATION_HEADER_PREFIX + "test", "1 + 1").build();
}