Example usage for org.springframework.messaging Message getPayload

List of usage examples for org.springframework.messaging Message getPayload

Introduction

In this page you can find the example usage for org.springframework.messaging Message getPayload.

Prototype

T getPayload();

Source Link

Document

Return the message payload.

Usage

From source file:org.springframework.cloud.stream.app.tensorflow.processor.TensorflowProcessorConfiguration.java

@ServiceActivator(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT)
public Message<?> evaluate(Message<?> input) {

    Map<String, Object> processorContext = new ConcurrentHashMap<>();

    Map<String, Object> inputData = tensorflowInputConverter.convert(input, processorContext);

    Tensor outputTensor = tensorFlowService.evaluate(inputData, properties.getOutputName(),
            properties.getOutputIndex());

    Object outputData = tensorflowOutputConverter.convert(outputTensor, processorContext);

    if (properties.isSaveOutputInHeader()) {
        // Add the result to the message header
        return MessageBuilder.withPayload(input.getPayload()).copyHeadersIfAbsent(input.getHeaders())
                .setHeaderIfAbsent(TF_OUTPUT_HEADER, outputData).build();
    }/*from ww  w.j  a  v a2 s  .  co  m*/

    // Add the outputData as part of the message payload
    Message<?> outputMessage = MessageBuilder.withPayload(outputData).copyHeadersIfAbsent(input.getHeaders())
            .build();

    return outputMessage;
}

From source file:org.springframework.cloud.stream.app.tensorflow.processor.TensorflowProcessorConfiguration.java

@Bean
@ConditionalOnMissingBean(name = "tensorflowInputConverter")
public TensorflowInputConverter tensorflowInputConverter() {
    return new TensorflowInputConverter() {

        @Override/*from w w w  . ja v a 2 s. c  o m*/
        public Map<String, Object> convert(Message<?> input, Map<String, Object> processorContext) {

            if (input.getHeaders().containsKey(TF_INPUT_HEADER)) {
                return (Map<String, Object>) input.getHeaders().get(TF_INPUT_HEADER, Map.class);
            } else if (input.getPayload() instanceof Map) {
                return (Map<String, Object>) input.getPayload();
            }
            throw new RuntimeException("Unsupported input format: " + input);

        }
    };
}

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

@ServiceActivator(inputChannel = Sink.INPUT)
public void throughputSink(Message<?> message) {
    if (start.get() == -1L) {
        synchronized (start) {
            if (start.get() == -1L) {
                // assume a homogeneous message structure - this is intended for
                // performance tests so we can assume that the messages are similar;
                // therefore we'll do our reporting based on the first message
                Object payload = message.getPayload();
                if (payload instanceof byte[] || payload instanceof String) {
                    reportBytes = true;/*w w w .  j  ava  2  s.co  m*/
                }
                start.set(System.currentTimeMillis());
                executorService.execute(new ReportStats());
            }
        }
    }
    intermediateCounter.incrementAndGet();
    if (reportBytes) {
        Object payload = message.getPayload();
        if (payload instanceof byte[]) {
            intermediateBytes.addAndGet(((byte[]) payload).length);
        } else if (payload instanceof String) {
            intermediateBytes.addAndGet((((String) payload).getBytes()).length);
        }
    }
}

From source file:org.springframework.cloud.stream.app.twitter.sentiment.processor.TwitterSentimentTensorflowInputConverter.java

@Override
public Map<String, Object> convert(Message<?> input, Map<String, Object> processorContext) {

    try {//w  w w  .j a  v a2s  .  co m
        Object payload = input.getPayload();

        if (payload instanceof String) {
            Map tweetJsonMap = objectMapper.readValue((String) payload, Map.class);
            processorContext.put(PROCESSOR_CONTEXT_TWEET_JSON_MAP, tweetJsonMap);
            return getStringObjectMap(tweetJsonMap);
        } else if (payload instanceof Map) {
            processorContext.put(PROCESSOR_CONTEXT_TWEET_JSON_MAP, payload);
            return getStringObjectMap((Map) payload);
        }

        throw new IllegalArgumentException("Unsupported payload type:" + input.getPayload());
    } catch (IOException e) {
        throw new RuntimeException("Can't parse input tweet json: " + input.getPayload());
    }

}

From source file:org.springframework.cloud.stream.app.websocket.sink.WebsocketSinkConfiguration.java

@ServiceActivator(inputChannel = Sink.INPUT)
public void websocketSink(Message<?> message) {
    if (logger.isTraceEnabled()) {
        logger.trace(String.format("Handling message: %s", message));
    }//from  w ww .jav a2  s  .  c o m

    SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
    headers.setMessageTypeIfNotSet(SimpMessageType.MESSAGE);
    String messagePayload = message.getPayload().toString();
    for (Channel channel : WebsocketSinkServer.channels) {
        if (logger.isTraceEnabled()) {
            logger.trace(
                    String.format("Writing message %s to channel %s", messagePayload, channel.localAddress()));
        }

        channel.write(new TextWebSocketFrame(messagePayload));
        channel.flush();
    }

    if (traceEndpointEnabled) {
        addMessageToTraceRepository(message);
    }
}

From source file:org.springframework.cloud.stream.app.websocket.sink.WebsocketSinkConfiguration.java

private void addMessageToTraceRepository(Message<?> message) {
    Map<String, Object> trace = new LinkedHashMap<>();
    trace.put("type", "text");
    trace.put("direction", "out");
    trace.put("id", message.getHeaders().getId());
    trace.put("payload", message.getPayload().toString());
    websocketTraceRepository.add(trace);

}

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

protected final MessageValues serializePayloadIfNecessary(Message<?> message) {
    Object originalPayload = message.getPayload();
    Object originalContentType = message.getHeaders().get(MessageHeaders.CONTENT_TYPE);

    // Pass content type as String since some transport adapters will exclude
    // CONTENT_TYPE Header otherwise
    Object contentType = JavaClassMimeTypeConversion
            .mimeTypeFromObject(originalPayload, ObjectUtils.nullSafeToString(originalContentType)).toString();
    Object payload = serializePayloadIfNecessary(originalPayload);
    MessageValues messageValues = new MessageValues(message);
    messageValues.setPayload(payload);//from   w ww.  ja va 2 s .c om
    messageValues.put(MessageHeaders.CONTENT_TYPE, contentType);
    if (originalContentType != null && !originalContentType.toString().equals(contentType.toString())) {
        messageValues.put(BinderHeaders.BINDER_ORIGINAL_CONTENT_TYPE, originalContentType.toString());
    }
    return messageValues;
}

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

@Test
public void testSendAndReceive() throws Exception {
    Binder binder = getBinder();//  ww  w  .jav  a2s.  com
    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 testSendAndReceiveNoOriginalContentType() throws Exception {
    Binder binder = getBinder();//  ww  w.  j a v  a2  s.c  om

    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.kafka.streams.KafkaStreamsMessageConversionDelegate.java

/**
 * Serialize {@link KStream} records on outbound based on contentType.
 *
 * @param outboundBindTarget outbound KStream target
 * @return serialized KStream/*ww w . j  av a2 s.  c o 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();
    });
}