Example usage for org.springframework.messaging Message getHeaders

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

Introduction

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

Prototype

MessageHeaders getHeaders();

Source Link

Document

Return message headers for the message (never null but may be empty).

Usage

From source file:org.springframework.cloud.function.web.RequestProcessor.java

private void addHeaders(BodyBuilder builder, Message<?> message) {
    builder.headers(HeaderUtils.fromMessage(message.getHeaders()));
}

From source file:org.springframework.cloud.gcp.autoconfigure.pubsub.it.PubSubChannelAdaptersIntegrationTests.java

@Test
public void sendAndReceiveMessageAsString() {
    this.contextRunner.run((context) -> {
        try {/*ww w  .  ja va  2s. c  o  m*/
            Map<String, Object> headers = new HashMap<>();
            // Only String values for now..
            headers.put("storm", "lift your skinny fists");
            headers.put("static", "lift your skinny fists");
            headers.put("sleep", "lift your skinny fists");

            Message originalMessage = MessageBuilder.createMessage("I am a message.".getBytes(),
                    new MessageHeaders(headers));
            context.getBean("inputChannel", MessageChannel.class).send(originalMessage);

            Message<?> message = context.getBean("outputChannel", PollableChannel.class).receive(5000);
            assertThat(message).isNotNull();
            assertThat(message.getPayload()).isInstanceOf(byte[].class);
            String payload = new String((byte[]) message.getPayload());
            assertThat(payload).isEqualTo("I am a message.");

            assertThat(message.getHeaders().size()).isEqualTo(6);
            assertThat(message.getHeaders().get("storm")).isEqualTo("lift your skinny fists");
            assertThat(message.getHeaders().get("static")).isEqualTo("lift your skinny fists");
            assertThat(message.getHeaders().get("sleep")).isEqualTo("lift your skinny fists");
            assertThat(message.getHeaders().get(GcpPubSubHeaders.ORIGINAL_MESSAGE)).isNotNull();
        } 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 sendAndReceiveMessageManualAck() {
    this.contextRunner.run((context) -> {
        try {//from  ww  w.j a  v  a2s .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 w  w  . j ava 2s  .co 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.schema.avro.AvroMessageConverterSerializationTests.java

@Test
public void sourceWriteSameVersion() throws Exception {
    User specificRecord = new User();
    specificRecord.setName("joe");
    Schema v1 = new Schema.Parser().parse(AvroMessageConverterSerializationTests.class.getClassLoader()
            .getResourceAsStream("schemas/user.avsc"));
    GenericRecord genericRecord = new GenericData.Record(v1);
    genericRecord.put("name", "joe");
    SchemaRegistryClient client = new DefaultSchemaRegistryClient();
    AvroSchemaRegistryClientMessageConverter converter = new AvroSchemaRegistryClientMessageConverter(client);
    converter.setDynamicSchemaGenerationEnabled(false);
    converter.setContentTypeResolver(new StringConvertingContentTypeResolver());
    converter.setCacheManager(new ConcurrentMapCacheManager());
    converter.afterPropertiesSet();/*from w  ww .j av a2 s  .c  o  m*/

    Message specificMessage = converter.toMessage(specificRecord,
            new MutableMessageHeaders(Collections.<String, Object>emptyMap()),
            MimeTypeUtils.parseMimeType("application/*+avro"));
    SchemaReference specificRef = extractSchemaReference(
            MimeTypeUtils.parseMimeType(specificMessage.getHeaders().get("contentType").toString()));

    Message genericMessage = converter.toMessage(genericRecord,
            new MutableMessageHeaders(Collections.<String, Object>emptyMap()),
            MimeTypeUtils.parseMimeType("application/*+avro"));
    SchemaReference genericRef = extractSchemaReference(
            MimeTypeUtils.parseMimeType(genericMessage.getHeaders().get("contentType").toString()));

    Assert.assertEquals(genericRef, specificRef);
    Assert.assertEquals(1, genericRef.getVersion());
}

From source file:org.springframework.cloud.sleuth.instrument.messaging.MessagingSpanExtractor.java

<T> T getHeader(Message<?> message, String name, Class<T> type) {
    return message.getHeaders().get(name, type);
}

From source file:org.springframework.cloud.sleuth.instrument.messaging.MessagingSpanExtractor.java

boolean hasHeader(Message<?> message, String name) {
    return message.getHeaders().containsKey(name);
}

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

private void testMessage(Message<byte[]> message, String expectedPayload) {
    assertNotNull(this.sink.input());
    assertEquals(LoggingHandler.Level.WARN, this.logSinkHandler.getLevel());
    Log logger = TestUtils.getPropertyValue(this.logSinkHandler, "messageLogger", Log.class);
    assertEquals("foo", TestUtils.getPropertyValue(logger, "logger.name"));
    logger = spy(logger);/*from   ww w  .  j  av a  2 s .com*/
    new DirectFieldAccessor(this.logSinkHandler).setPropertyValue("messageLogger", logger);
    this.sink.input().send(message);
    ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class);
    verify(logger).warn(captor.capture());
    assertEquals(expectedPayload.toUpperCase(), captor.getValue());
    this.logSinkHandler.setLogExpressionString("#this");
    this.sink.input().send(message);
    verify(logger, times(2)).warn(captor.capture());

    Message captorMessage = (Message) captor.getAllValues().get(2);
    assertEquals("Unexpected payload value", expectedPayload, captorMessage.getPayload());

    MessageHeaders messageHeaders = captorMessage.getHeaders();
    assertEquals("Unexpected number of headers", 3, messageHeaders.size());

    String[] headers = { "contentType" };

    for (String header : headers) {
        assertTrue("Missing " + header + " header", messageHeaders.containsKey(header));
        assertEquals("Header " + header + " does not match", messageHeaders.get(header),
                message.getHeaders().get(header));
    }
}

From source file:org.springframework.cloud.stream.app.pmml.processor.PmmlProcessorConfiguration.java

private MutableMessage<?> convertToMutable(Message<?> input) {
    Object payload = input.getPayload();
    if (payload instanceof Tuple && !(payload instanceof MutableTuple)) {
        payload = TupleBuilder.mutableTuple().putAll((Tuple) payload).build();
    }//  w w w. j  a  va 2s  .c o  m
    return new MutableMessage<>(payload, input.getHeaders());
}

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();
}