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

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

Introduction

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

Prototype

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

Source Link

Document

Create a new builder for a message with the given payload.

Usage

From source file:org.springframework.cloud.stream.binder.kafka.streams.KafkaStreamsStreamListenerSetupMethodOrchestrator.java

private KStream<?, ?> getkStream(String inboundName, KafkaStreamsStateStoreProperties storeSpec,
        BindingProperties bindingProperties, StreamsBuilder streamsBuilder, Serde<?> keySerde,
        Serde<?> valueSerde, Topology.AutoOffsetReset autoOffsetReset) {
    if (storeSpec != null) {
        StoreBuilder storeBuilder = buildStateStore(storeSpec);
        streamsBuilder.addStateStore(storeBuilder);
        if (LOG.isInfoEnabled()) {
            LOG.info("state store " + storeBuilder.name() + " added to topology");
        }/*from  www .ja  v a 2  s .  c  o  m*/
    }
    String[] bindingTargets = StringUtils
            .commaDelimitedListToStringArray(this.bindingServiceProperties.getBindingDestination(inboundName));

    KStream<?, ?> stream = streamsBuilder.stream(Arrays.asList(bindingTargets),
            Consumed.with(keySerde, valueSerde).withOffsetResetPolicy(autoOffsetReset));
    final boolean nativeDecoding = this.bindingServiceProperties.getConsumerProperties(inboundName)
            .isUseNativeDecoding();
    if (nativeDecoding) {
        LOG.info("Native decoding is enabled for " + inboundName
                + ". Inbound deserialization done at the broker.");
    } else {
        LOG.info("Native decoding is disabled for " + inboundName
                + ". Inbound message conversion done by Spring Cloud Stream.");
    }

    stream = stream.mapValues((value) -> {
        Object returnValue;
        String contentType = bindingProperties.getContentType();
        if (value != null && !StringUtils.isEmpty(contentType) && !nativeDecoding) {
            returnValue = MessageBuilder.withPayload(value).setHeader(MessageHeaders.CONTENT_TYPE, contentType)
                    .build();
        } else {
            returnValue = value;
        }
        return returnValue;
    });
    return stream;
}

From source file:org.springframework.integration.handler.AsyncHandlerTests.java

@Test
public void testGoodResultWithReplyChannelHeader() {
    this.whichTest = 0;
    this.handler.setOutputChannel(null);
    QueueChannel replyChannel = new QueueChannel();
    Message<?> message = MessageBuilder.withPayload("foo").setReplyChannel(replyChannel).build();
    this.handler.handleMessage(message);
    assertNull(replyChannel.receive(0));
    this.latch.countDown();
    Message<?> received = replyChannel.receive(10000);
    assertNotNull(received);//from   ww w. ja va2 s .c  o m
    assertEquals("reply", received.getPayload());
    assertNull(this.failedCallbackException);
}

From source file:org.springframework.integration.handler.AsyncHandlerTests.java

@Test
public void testGoodResultWithNoReplyChannelHeaderNoOutput() throws Exception {
    this.whichTest = 0;
    this.handler.setOutputChannel(null);
    QueueChannel errorChannel = new QueueChannel();
    Message<String> message = MessageBuilder.withPayload("foo").setErrorChannel(errorChannel).build();
    this.handler.handleMessage(message);
    assertNull(this.output.receive(0));
    this.latch.countDown();
    Message<?> errorMessage = errorChannel.receive(1000);
    assertNotNull(errorMessage);//from w w w  .j av a  2  s  .c o  m
    assertThat(errorMessage.getPayload(), instanceOf(DestinationResolutionException.class));
    assertEquals("no output-channel or replyChannel header available",
            ((Throwable) errorMessage.getPayload()).getMessage());
    assertNull(((MessagingException) errorMessage.getPayload()).getFailedMessage());
    assertNotNull(this.failedCallbackException);
    assertThat(this.failedCallbackException.getMessage(), containsString("or replyChannel header"));
}

From source file:org.springframework.integration.handler.AsyncHandlerTests.java

@Test
public void testRuntimeException() {
    QueueChannel errorChannel = new QueueChannel();
    Message<String> message = MessageBuilder.withPayload("foo").setErrorChannel(errorChannel).build();
    this.handler.handleMessage(message);
    assertNull(this.output.receive(0));
    this.whichTest = 1;
    this.latch.countDown();
    Message<?> received = errorChannel.receive(10000);
    assertNotNull(received);// w ww. j  a v a2 s  .c  om
    assertThat(received.getPayload(), instanceOf(MessageHandlingException.class));
    assertEquals("foo", ((Throwable) received.getPayload()).getCause().getMessage());
    assertSame(message, ((MessagingException) received.getPayload()).getFailedMessage());
    assertNull(this.failedCallbackException);
}

From source file:org.springframework.integration.handler.AsyncHandlerTests.java

@Test
public void testMessagingException() {
    QueueChannel errorChannel = new QueueChannel();
    Message<String> message = MessageBuilder.withPayload("foo").setErrorChannel(errorChannel).build();
    this.handler.handleMessage(message);
    assertNull(this.output.receive(0));
    this.whichTest = 2;
    this.latch.countDown();
    Message<?> received = errorChannel.receive(10000);
    assertNotNull(received);//from   w  w  w  .  j  av  a 2  s .  c  om
    assertThat(received.getPayload(), instanceOf(MessagingException.class));
    assertSame(message, ((MessagingException) received.getPayload()).getFailedMessage());
    assertNull(this.failedCallbackException);
}

From source file:org.springframework.integration.handler.AsyncHandlerTests.java

@Test
public void testMessagingExceptionNoErrorChannel() throws Exception {
    Message<String> message = MessageBuilder.withPayload("foo").build();
    this.handler.handleMessage(message);
    assertNull(this.output.receive(0));
    this.whichTest = 2;
    this.latch.countDown();
    assertTrue(this.exceptionLatch.await(10, TimeUnit.SECONDS));
    assertNotNull(this.failedCallbackException);
    assertThat(this.failedCallbackMessage, containsString("no 'errorChannel' header"));
}

From source file:org.springframework.integration.ip.tcp.connection.ConnectionEventTests.java

@Test
public void testOutboundChannelAdapterNoConnectionEvents() {
    TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    AbstractServerConnectionFactory scf = new AbstractServerConnectionFactory(0) {

        @Override/*from  ww w .  j a  va 2  s.c  om*/
        public void run() {
        }
    };
    final AtomicReference<ApplicationEvent> theEvent = new AtomicReference<ApplicationEvent>();
    scf.setApplicationEventPublisher(new ApplicationEventPublisher() {

        @Override
        public void publishEvent(Object event) {
        }

        @Override
        public void publishEvent(ApplicationEvent event) {
            theEvent.set(event);
        }

    });
    handler.setConnectionFactory(scf);
    handler.start();
    Message<String> message = MessageBuilder.withPayload("foo").setHeader(IpHeaders.CONNECTION_ID, "bar")
            .build();
    try {
        handler.handleMessage(message);
        fail("expected exception");
    } catch (MessageHandlingException e) {
        assertThat(e.getMessage(), Matchers.containsString("Unable to find outbound socket"));
    }
    assertNotNull(theEvent.get());
    TcpConnectionFailedCorrelationEvent event = (TcpConnectionFailedCorrelationEvent) theEvent.get();
    assertEquals("bar", event.getConnectionId());
    assertSame(message, ((MessagingException) event.getCause()).getFailedMessage());
}

From source file:org.springframework.integration.ip.tcp.connection.ConnectionEventTests.java

@Test
public void testInboundGatewayNoConnectionEvents() {
    TcpInboundGateway gw = new TcpInboundGateway();
    AbstractServerConnectionFactory scf = new AbstractServerConnectionFactory(0) {

        @Override//from w w  w.  j a  va2  s.c  o  m
        public void run() {
        }
    };
    final AtomicReference<ApplicationEvent> theEvent = new AtomicReference<ApplicationEvent>();
    scf.setApplicationEventPublisher(new ApplicationEventPublisher() {

        @Override
        public void publishEvent(Object event) {
        }

        @Override
        public void publishEvent(ApplicationEvent event) {
            theEvent.set(event);
        }

    });
    gw.setConnectionFactory(scf);
    DirectChannel requestChannel = new DirectChannel();
    requestChannel.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            ((MessageChannel) message.getHeaders().getReplyChannel()).send(message);
        }
    });
    gw.setRequestChannel(requestChannel);
    gw.start();
    Message<String> message = MessageBuilder.withPayload("foo").setHeader(IpHeaders.CONNECTION_ID, "bar")
            .build();
    gw.onMessage(message);
    assertNotNull(theEvent.get());
    TcpConnectionFailedCorrelationEvent event = (TcpConnectionFailedCorrelationEvent) theEvent.get();
    assertEquals("bar", event.getConnectionId());
    assertSame(message, ((MessagingException) event.getCause()).getFailedMessage());
}

From source file:org.springframework.integration.ip.tcp.connection.ConnectionEventTests.java

@Test
public void testOutboundGatewayNoConnectionEvents() {
    TcpOutboundGateway gw = new TcpOutboundGateway();
    AbstractClientConnectionFactory ccf = new AbstractClientConnectionFactory("localhost", 0) {
    };//from w  w  w  .j a v  a2 s  .c  o  m
    final AtomicReference<ApplicationEvent> theEvent = new AtomicReference<ApplicationEvent>();
    ccf.setApplicationEventPublisher(new ApplicationEventPublisher() {

        @Override
        public void publishEvent(Object event) {
        }

        @Override
        public void publishEvent(ApplicationEvent event) {
            theEvent.set(event);
        }

    });
    gw.setConnectionFactory(ccf);
    DirectChannel requestChannel = new DirectChannel();
    requestChannel
            .subscribe(message -> ((MessageChannel) message.getHeaders().getReplyChannel()).send(message));
    gw.start();
    Message<String> message = MessageBuilder.withPayload("foo").setHeader(IpHeaders.CONNECTION_ID, "bar")
            .build();
    gw.onMessage(message);
    assertNotNull(theEvent.get());
    TcpConnectionFailedCorrelationEvent event = (TcpConnectionFailedCorrelationEvent) theEvent.get();
    assertEquals("bar", event.getConnectionId());
    MessagingException messagingException = (MessagingException) event.getCause();
    assertSame(message, messagingException.getFailedMessage());
    assertEquals("Cannot correlate response - no pending reply for bar", messagingException.getMessage());

    message = new GenericMessage<String>("foo");
    gw.onMessage(message);
    assertNotNull(theEvent.get());
    event = (TcpConnectionFailedCorrelationEvent) theEvent.get();
    assertNull(event.getConnectionId());
    messagingException = (MessagingException) event.getCause();
    assertSame(message, messagingException.getFailedMessage());
    assertEquals("Cannot correlate response - no connection id", messagingException.getMessage());
}

From source file:org.springframework.messaging.converter.AbstractMessageConverter.java

@Override
@Nullable//from  w  w w  .ja  v  a  2 s.c o  m
public final Message<?> toMessage(Object payload, @Nullable MessageHeaders headers,
        @Nullable Object conversionHint) {
    if (!canConvertTo(payload, headers)) {
        return null;
    }

    Object payloadToUse = convertToInternal(payload, headers, conversionHint);
    if (payloadToUse == null) {
        return null;
    }

    MimeType mimeType = getDefaultContentType(payloadToUse);
    if (headers != null) {
        MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(headers,
                MessageHeaderAccessor.class);
        if (accessor != null && accessor.isMutable()) {
            if (mimeType != null) {
                accessor.setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, mimeType);
            }
            return MessageBuilder.createMessage(payloadToUse, accessor.getMessageHeaders());
        }
    }

    MessageBuilder<?> builder = MessageBuilder.withPayload(payloadToUse);
    if (headers != null) {
        builder.copyHeaders(headers);
    }
    if (mimeType != null) {
        builder.setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, mimeType);
    }
    return builder.build();
}