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.gcp.autoconfigure.pubsub.it.PubSubChannelAdaptersIntegrationTests.java

@Test
public void sendAndReceiveMessageManualAck() {
    this.contextRunner.run((context) -> {
        try {/*from  ww w.  java 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  ww . j a  va2 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();
            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.gcp.autoconfigure.pubsub.it.PubSubChannelAdaptersIntegrationTests.java

@Test
public void sendAndReceiveMessagePublishCallback() {
    this.contextRunner.run((context) -> {
        try {//from   w  w w  .j a  v a  2 s  . c  om
            ListenableFutureCallback<String> callbackSpy = Mockito.spy(new ListenableFutureCallback<String>() {
                @Override
                public void onFailure(Throwable ex) {

                }

                @Override
                public void onSuccess(String result) {

                }
            });
            context.getBean(PubSubMessageHandler.class).setPublishCallback(callbackSpy);
            context.getBean("inputChannel", MessageChannel.class)
                    .send(MessageBuilder.withPayload("I am a message.".getBytes()).build());

            Message<?> message = context.getBean("outputChannel", PollableChannel.class).receive(5000);
            assertThat(message).isNotNull();
            verify(callbackSpy, times(1)).onSuccess(any());
        } 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.netflix.hystrix.stream.HystrixStreamTask.java

@Scheduled(fixedRateString = "${hystrix.stream.queue.sendRate:500}")
public void sendMetrics() {
    ArrayList<String> metrics = new ArrayList<>();
    this.jsonMetrics.drainTo(metrics);

    if (!metrics.isEmpty()) {
        if (log.isTraceEnabled()) {
            log.trace("sending stream metrics size: " + metrics.size());
        }// w w w.java 2s.c  o m
        for (String json : metrics) {
            // TODO: batch all metrics to one message
            try {
                // TODO: remove the explicit content type when s-c-stream can handle
                // that for us
                this.outboundChannel.send(MessageBuilder.withPayload(json)
                        .setHeader(MessageHeaders.CONTENT_TYPE, this.properties.getContentType()).build());
            } catch (Exception ex) {
                if (log.isTraceEnabled()) {
                    log.trace("failed sending stream metrics: " + ex.getMessage());
                }
            }
        }
    }
}

From source file:org.springframework.cloud.stream.annotation.rxjava.SubjectMessageHandler.java

@Override
public synchronized void start() {
    if (!this.running) {
        this.subject = new SerializedSubject(PublishSubject.create());
        Observable<?> outputStream = this.processor.process(this.subject);
        this.subscription = outputStream.subscribe(new Action1<Object>() {

            @Override//from w  w w .j  a  v a2 s. c o m
            public void call(Object outputObject) {
                if (ClassUtils.isAssignable(Message.class, outputObject.getClass())) {
                    getOutputChannel().send((Message) outputObject);
                } else {
                    getOutputChannel().send(MessageBuilder.withPayload(outputObject).build());
                }
            }
        }, new Action1<Throwable>() {

            @Override
            public void call(Throwable throwable) {
                SubjectMessageHandler.this.logger.error(throwable.getMessage(), throwable);
            }
        }, new Action0() {

            @Override
            public void call() {
                SubjectMessageHandler.this.logger
                        .info("Subscription close for [" + SubjectMessageHandler.this.subscription + "]");
            }
        });
        this.running = true;
    }
}

From source file:org.springframework.cloud.stream.app.log.sink.LogSinkApplicationTests.java

@Test
public void testTextContentType() {
    Message<byte[]> message = MessageBuilder.withPayload("{\"foo\":\"bar\"}".getBytes())
            .setHeader("contentType", MimeType.valueOf("text/plain")).build();
    this.testMessage(message, "{\"foo\":\"bar\"}");
}

From source file:org.springframework.cloud.stream.app.log.sink.LogSinkApplicationTests.java

@Test
public void testJsonContentType() {
    Message<byte[]> message = MessageBuilder.withPayload("{\"foo\":\"bar\"}".getBytes())
            .setHeader("contentType", new MimeType("json")).build();
    this.testMessage(message, "{\"foo\":\"bar\"}");
}

From source file:org.springframework.cloud.stream.app.tasklaunchrequest.DataFlowTaskLaunchRequestAutoConfiguration.java

private Message dataflowTaskLaunchRequest(Message message) {

    Assert.hasText(taskLaunchRequestProperties.getTaskName(), "'taskName' is required");
    log.info(String.format("creating a task launch request for task %s",
            taskLaunchRequestProperties.getTaskName()));
    TaskLaunchRequestContext taskLaunchRequestContext = taskLaunchRequestContext(message);

    DataFlowTaskLaunchRequest taskLaunchRequest = new DataFlowTaskLaunchRequest();

    List<String> evaluatedArgs = evaluateArgExpressions(message, KeyValueListParser
            .parseCommaDelimitedKeyValuePairs(taskLaunchRequestProperties.getArgExpressions()));

    taskLaunchRequest.addCommmandLineArguments(taskLaunchRequestProperties.getArgs())
            .addCommmandLineArguments(evaluatedArgs)
            .addCommmandLineArguments(taskLaunchRequestContext.getCommandLineArgs());

    taskLaunchRequest.setDeploymentProperties(deploymentProperties);
    taskLaunchRequest.setTaskName(taskLaunchRequestProperties.getTaskName());

    MessageBuilder<?> builder = MessageBuilder.withPayload(taskLaunchRequest).copyHeaders(message.getHeaders());

    return adjustHeaders(builder, message.getHeaders()).build();
}

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

/**
 * Serialize {@link KStream} records on outbound based on contentType.
 *
 * @param outboundBindTarget outbound KStream target
 * @return serialized KStream// w w w  . java  2s.co m
 */
@SuppressWarnings("rawtypes")
public KStream serializeOnOutbound(KStream<?, ?> outboundBindTarget) {
    String contentType = this.kstreamBindingInformationCatalogue.getContentType(outboundBindTarget);
    MessageConverter messageConverter = this.compositeMessageConverterFactory
            .getMessageConverterForAllRegistered();

    return outboundBindTarget.mapValues((v) -> {
        Message<?> message = v instanceof Message<?> ? (Message<?>) v : MessageBuilder.withPayload(v).build();
        Map<String, Object> headers = new HashMap<>(message.getHeaders());
        if (!StringUtils.isEmpty(contentType)) {
            headers.put(MessageHeaders.CONTENT_TYPE, contentType);
        }
        MessageHeaders messageHeaders = new MessageHeaders(headers);
        return messageConverter.toMessage(message.getPayload(), messageHeaders).getPayload();
    });
}

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

/**
 * Deserialize incoming {@link KStream} based on content type.
 *
 * @param valueClass on KStream value//from   w w w . j  a v  a2  s.  co m
 * @param bindingTarget inbound KStream target
 * @return deserialized KStream
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public KStream deserializeOnInbound(Class<?> valueClass, KStream<?, ?> bindingTarget) {
    MessageConverter messageConverter = this.compositeMessageConverterFactory
            .getMessageConverterForAllRegistered();
    final PerRecordContentTypeHolder perRecordContentTypeHolder = new PerRecordContentTypeHolder();

    resolvePerRecordContentType(bindingTarget, perRecordContentTypeHolder);

    //Deserialize using a branching strategy
    KStream<?, ?>[] branch = bindingTarget.branch(
            //First filter where the message is converted and return true if everything went well, return false otherwise.
            (o, o2) -> {
                boolean isValidRecord = false;

                try {
                    //if the record is a tombstone, ignore and exit from processing further.
                    if (o2 != null) {
                        if (o2 instanceof Message || o2 instanceof String || o2 instanceof byte[]) {
                            Message<?> m1 = null;
                            if (o2 instanceof Message) {
                                m1 = perRecordContentTypeHolder.contentType != null
                                        ? MessageBuilder.fromMessage((Message<?>) o2)
                                                .setHeader(MessageHeaders.CONTENT_TYPE,
                                                        perRecordContentTypeHolder.contentType)
                                                .build()
                                        : (Message<?>) o2;
                            } else {
                                m1 = perRecordContentTypeHolder.contentType != null
                                        ? MessageBuilder.withPayload(o2)
                                                .setHeader(MessageHeaders.CONTENT_TYPE,
                                                        perRecordContentTypeHolder.contentType)
                                                .build()
                                        : MessageBuilder.withPayload(o2).build();
                            }
                            convertAndSetMessage(o, valueClass, messageConverter, m1);
                        } else {
                            keyValueThreadLocal.set(new KeyValue<>(o, o2));
                        }
                        isValidRecord = true;
                    } else {
                        LOG.info("Received a tombstone record. This will be skipped from further processing.");
                    }
                } catch (Exception e) {
                    LOG.warn("Deserialization has failed. This will be skipped from further processing.", e);
                    //pass through
                }
                return isValidRecord;
            },
            //second filter that catches any messages for which an exception thrown in the first filter above.
            (k, v) -> true);
    //process errors from the second filter in the branch above.
    processErrorFromDeserialization(bindingTarget, branch[1]);

    //first branch above is the branch where the messages are converted, let it go through further processing.
    return branch[0].mapValues((o2) -> {
        Object objectValue = keyValueThreadLocal.get().value;
        keyValueThreadLocal.remove();
        return objectValue;
    });
}