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.stream.config.MessageChannelConfigurerTests.java

@Test
public void testPartitionHeader() throws Exception {
    this.testSource.output().send(MessageBuilder.withPayload("{\"message\":\"Hi\"}").build());
    Message<?> message = this.messageCollector.forChannel(testSource.output()).poll(1, TimeUnit.SECONDS);
    assertThat(message.getHeaders().get(BinderHeaders.PARTITION_HEADER).equals(0));
    assertNull(message.getHeaders().get(BinderHeaders.PARTITION_OVERRIDE));
}

From source file:org.springframework.cloud.stream.config.MessageChannelConfigurerTests.java

@Test
public void testPartitionHeaderWithPartitionOverride() throws Exception {
    this.testSource.output().send(MessageBuilder.withPayload("{\"message\":\"Hi\"}")
            .setHeader(BinderHeaders.PARTITION_OVERRIDE, 123).build());
    Message<?> message = this.messageCollector.forChannel(testSource.output()).poll(1, TimeUnit.SECONDS);
    assertThat(message.getHeaders().get(BinderHeaders.PARTITION_HEADER).equals(123));
    assertNull(message.getHeaders().get(BinderHeaders.PARTITION_OVERRIDE));
}

From source file:org.springframework.cloud.stream.converter.JsonUnmarshallingConverter.java

private boolean canConvertFromBasedOnContentTypeHeader(Message<?> message) {
    Object contentTypeHeader = message.getHeaders().get(MessageHeaders.CONTENT_TYPE);
    if (contentTypeHeader instanceof String) {
        return MimeTypeUtils.APPLICATION_JSON.includes(MimeTypeUtils.parseMimeType((String) contentTypeHeader));
    } else if (contentTypeHeader instanceof MimeType) {
        return MimeTypeUtils.APPLICATION_JSON.includes((MimeType) contentTypeHeader);
    } else {/*from w  w w .j a va 2s  .c o m*/
        return contentTypeHeader == null;
    }
}

From source file:org.springframework.cloud.stream.function.FunctionInvoker.java

@SuppressWarnings("unchecked")
private <T> Message<O> toMessage(T value, Message<I> originalMessage) {
    if (logger.isDebugEnabled()) {
        logger.debug("Converting result back to message using the original message: " + originalMessage);
    }/*from   w w w.jav a  2s .  c  o  m*/
    return (Message<O>) (value instanceof Message ? value
            : this.messageConverter.toMessage(value, originalMessage.getHeaders()));
}

From source file:org.springframework.cloud.stream.module.websocket.sink.WebsocketSink.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.integration.aggregator.AggregatorTests.java

@Test
public void testCustomAggPerf() throws InterruptedException, ExecutionException, TimeoutException {
    class CustomHandler extends AbstractMessageHandler {

        // custom aggregator, only handles a single correlation

        private final ReentrantLock lock = new ReentrantLock();

        private final Collection<Message<?>> messages = new ArrayList<Message<?>>(60000);

        private final MessageChannel outputChannel;

        private CustomHandler(MessageChannel outputChannel) {
            this.outputChannel = outputChannel;
        }//from  ww w .  j  a va2s  .  com

        @Override
        public void handleMessageInternal(Message<?> requestMessage) {
            lock.lock();
            try {
                this.messages.add(requestMessage);
                if (this.messages.size() == 60000) {
                    List<Object> payloads = new ArrayList<Object>(this.messages.size());
                    for (Message<?> message : this.messages) {
                        payloads.add(message.getPayload());
                    }
                    this.messages.clear();
                    outputChannel.send(getMessageBuilderFactory().withPayload(payloads)
                            .copyHeaders(requestMessage.getHeaders()).build());
                }
            } finally {
                lock.unlock();
            }
        }

    }

    DirectChannel outputChannel = new DirectChannel();
    CustomHandler handler = new CustomHandler(outputChannel);

    final CompletableFuture<Collection<?>> resultFuture = new CompletableFuture<>();
    outputChannel.subscribe(message -> {
        Collection<?> payload = (Collection<?>) message.getPayload();
        logger.warn("Received " + payload.size());
        resultFuture.complete(payload);
    });
    Message<?> message = new GenericMessage<String>("foo");
    StopWatch stopwatch = new StopWatch();
    stopwatch.start();
    for (int i = 0; i < 120000; i++) {
        if (i % 10000 == 0) {
            stopwatch.stop();
            logger.warn("Sent " + i + " in " + stopwatch.getTotalTimeSeconds() + " (10k in "
                    + stopwatch.getLastTaskTimeMillis() + "ms)");
            stopwatch.start();
        }
        handler.handleMessage(message);
    }
    stopwatch.stop();
    logger.warn("Sent " + 120000 + " in " + stopwatch.getTotalTimeSeconds() + " (10k in "
            + stopwatch.getLastTaskTimeMillis() + "ms)");

    Collection<?> result = resultFuture.get(10, TimeUnit.SECONDS);
    assertNotNull(result);
    assertEquals(60000, result.size());
}

From source file:org.springframework.integration.amqp.outbound.AsyncAmqpGatewayTests.java

@Test
public void testConfirmsAndReturns() throws Exception {
    CachingConnectionFactory ccf = new CachingConnectionFactory("localhost");
    ccf.setPublisherConfirms(true);/* www  .jav  a2 s.com*/
    ccf.setPublisherReturns(true);
    RabbitTemplate template = new RabbitTemplate(ccf);
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(ccf);
    container.setBeanName("replyContainer");
    container.setQueueNames("asyncRQ1");
    container.afterPropertiesSet();
    container.start();
    AsyncRabbitTemplate asyncTemplate = new AsyncRabbitTemplate(template, container);
    asyncTemplate.setEnableConfirms(true);
    asyncTemplate.setMandatory(true);

    SimpleMessageListenerContainer receiver = new SimpleMessageListenerContainer(ccf);
    receiver.setBeanName("receiver");
    receiver.setQueueNames("asyncQ1");
    final CountDownLatch waitForAckBeforeReplying = new CountDownLatch(1);
    MessageListenerAdapter messageListener = new MessageListenerAdapter(
            (ReplyingMessageListener<String, String>) foo -> {
                try {
                    waitForAckBeforeReplying.await(10, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                return foo.toUpperCase();
            });
    receiver.setMessageListener(messageListener);
    receiver.afterPropertiesSet();
    receiver.start();

    AsyncAmqpOutboundGateway gateway = new AsyncAmqpOutboundGateway(asyncTemplate);
    Log logger = spy(TestUtils.getPropertyValue(gateway, "logger", Log.class));
    given(logger.isDebugEnabled()).willReturn(true);
    final CountDownLatch replyTimeoutLatch = new CountDownLatch(1);
    willAnswer(invocation -> {
        invocation.callRealMethod();
        replyTimeoutLatch.countDown();
        return null;
    }).given(logger).debug(startsWith("Reply not required and async timeout for"));
    new DirectFieldAccessor(gateway).setPropertyValue("logger", logger);
    QueueChannel outputChannel = new QueueChannel();
    outputChannel.setBeanName("output");
    QueueChannel returnChannel = new QueueChannel();
    returnChannel.setBeanName("returns");
    QueueChannel ackChannel = new QueueChannel();
    ackChannel.setBeanName("acks");
    QueueChannel errorChannel = new QueueChannel();
    errorChannel.setBeanName("errors");
    gateway.setOutputChannel(outputChannel);
    gateway.setReturnChannel(returnChannel);
    gateway.setConfirmAckChannel(ackChannel);
    gateway.setConfirmNackChannel(ackChannel);
    gateway.setConfirmCorrelationExpressionString("#this");
    gateway.setExchangeName("");
    gateway.setRoutingKey("asyncQ1");
    gateway.setBeanFactory(mock(BeanFactory.class));
    gateway.afterPropertiesSet();
    gateway.start();

    Message<?> message = MessageBuilder.withPayload("foo").setErrorChannel(errorChannel).build();

    gateway.handleMessage(message);

    Message<?> ack = ackChannel.receive(10000);
    assertNotNull(ack);
    assertEquals("foo", ack.getPayload());
    assertEquals(true, ack.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM));
    waitForAckBeforeReplying.countDown();

    Message<?> received = outputChannel.receive(10000);
    assertNotNull(received);
    assertEquals("FOO", received.getPayload());

    // timeout tests
    asyncTemplate.setReceiveTimeout(10);

    receiver.setMessageListener(message1 -> {
    });
    // reply timeout with no requiresReply
    message = MessageBuilder.withPayload("bar").setErrorChannel(errorChannel).build();
    gateway.handleMessage(message);
    assertTrue(replyTimeoutLatch.await(10, TimeUnit.SECONDS));

    // reply timeout with requiresReply
    gateway.setRequiresReply(true);
    message = MessageBuilder.withPayload("baz").setErrorChannel(errorChannel).build();
    gateway.handleMessage(message);

    received = errorChannel.receive(10000);
    assertThat(received, instanceOf(ErrorMessage.class));
    ErrorMessage error = (ErrorMessage) received;
    assertThat(error.getPayload(), instanceOf(MessagingException.class));
    assertThat(error.getPayload().getCause(), instanceOf(AmqpReplyTimeoutException.class));
    asyncTemplate.setReceiveTimeout(30000);
    receiver.setMessageListener(messageListener);

    // error on sending result
    DirectChannel errorForce = new DirectChannel();
    errorForce.setBeanName("errorForce");
    errorForce.subscribe(message1 -> {
        throw new RuntimeException("intentional");
    });
    gateway.setOutputChannel(errorForce);
    message = MessageBuilder.withPayload("qux").setErrorChannel(errorChannel).build();
    gateway.handleMessage(message);
    received = errorChannel.receive(10000);
    assertThat(received, instanceOf(ErrorMessage.class));
    error = (ErrorMessage) received;
    assertThat(error.getPayload(), instanceOf(MessagingException.class));
    assertEquals("QUX", ((MessagingException) error.getPayload()).getFailedMessage().getPayload());

    gateway.setRoutingKey(UUID.randomUUID().toString());
    message = MessageBuilder.withPayload("fiz").setErrorChannel(errorChannel).build();
    gateway.handleMessage(message);
    Message<?> returned = returnChannel.receive(10000);
    assertNotNull(returned);
    assertEquals("fiz", returned.getPayload());
    ackChannel.receive(10000);
    ackChannel.purge(null);

    asyncTemplate = mock(AsyncRabbitTemplate.class);
    RabbitMessageFuture future = asyncTemplate.new RabbitMessageFuture(null, null);
    willReturn(future).given(asyncTemplate).sendAndReceive(anyString(), anyString(),
            any(org.springframework.amqp.core.Message.class));
    DirectFieldAccessor dfa = new DirectFieldAccessor(future);
    dfa.setPropertyValue("nackCause", "nacknack");
    SettableListenableFuture<Boolean> confirmFuture = new SettableListenableFuture<Boolean>();
    confirmFuture.set(false);
    dfa.setPropertyValue("confirm", confirmFuture);
    new DirectFieldAccessor(gateway).setPropertyValue("template", asyncTemplate);

    message = MessageBuilder.withPayload("buz").setErrorChannel(errorChannel).build();
    gateway.handleMessage(message);

    ack = ackChannel.receive(10000);
    assertNotNull(ack);
    assertEquals("buz", ack.getPayload());
    assertEquals("nacknack", ack.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM_NACK_CAUSE));
    assertEquals(false, ack.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM));

    asyncTemplate.stop();
    receiver.stop();
    ccf.destroy();
}

From source file:org.springframework.integration.aws.inbound.S3InboundStreamingChannelAdapterTests.java

@Test
public void testS3InboundStreamingChannelAdapter() throws IOException {
    Message<?> message = this.s3FilesChannel.receive(10000);
    assertThat(message).isNotNull();//from  w w w .java  2 s.c  o  m
    assertThat(message.getPayload()).isInstanceOf(InputStream.class);
    assertThat(message.getHeaders().get(FileHeaders.REMOTE_FILE)).isEqualTo("subdir/a.test");

    InputStream inputStreamA = (InputStream) message.getPayload();
    assertThat(inputStreamA).isNotNull();
    assertThat(IOUtils.toString(inputStreamA)).isEqualTo("Hello");

    message = this.s3FilesChannel.receive(10000);
    assertThat(message).isNotNull();
    assertThat(message.getPayload()).isInstanceOf(InputStream.class);
    assertThat(message.getHeaders().get(FileHeaders.REMOTE_FILE)).isEqualTo("subdir/b.test");
    InputStream inputStreamB = (InputStream) message.getPayload();
    assertThat(IOUtils.toString(inputStreamB)).isEqualTo("Bye");

    assertThat(this.s3FilesChannel.receive(10)).isNull();
}

From source file:org.springframework.integration.aws.inbound.SnsInboundChannelAdapter.java

@Override
@SuppressWarnings("unchecked")
protected void send(Object object) {
    Message<?> message = (Message<?>) object;
    Map<String, String> payload = (HashMap<String, String>) message.getPayload();
    AbstractIntegrationMessageBuilder<?> messageToSendBuilder;
    if (this.payloadExpression != null) {
        messageToSendBuilder = getMessageBuilderFactory()
                .withPayload(this.payloadExpression.getValue(this.evaluationContext, message))
                .copyHeaders(message.getHeaders());
    } else {/*from  ww  w  .j a  va  2s.c  o m*/
        messageToSendBuilder = getMessageBuilderFactory().fromMessage(message);
    }

    String type = payload.get("Type");
    if ("SubscriptionConfirmation".equals(type) || "UnsubscribeConfirmation".equals(type)) {
        JsonNode content = this.jackson2HttpMessageConverter.getObjectMapper().valueToTree(payload);
        NotificationStatus notificationStatus = this.notificationStatusResolver
                .resolveNotificationStatus(content);
        if (this.handleNotificationStatus) {
            messageToSendBuilder.setHeader(AwsHeaders.NOTIFICATION_STATUS, notificationStatus);
        } else {
            if ("SubscriptionConfirmation".equals(type)) {
                notificationStatus.confirmSubscription();
            }
            return;
        }
    }
    messageToSendBuilder.setHeader(AwsHeaders.SNS_MESSAGE_TYPE, type).setHeader(AwsHeaders.MESSAGE_ID,
            payload.get("MessageId"));
    super.send(messageToSendBuilder.build());
}

From source file:org.springframework.integration.config.xml.GatewayParserTests.java

@Test
public void testOneWayOverride() {
    TestService service = (TestService) context.getBean("methodOverride");
    service.oneWay("foo");
    PollableChannel channel = (PollableChannel) context.getBean("otherRequestChannel");
    Message<?> result = channel.receive(1000);
    assertEquals("fiz", result.getPayload());
    assertEquals("bar", result.getHeaders().get("foo"));
    assertEquals("qux", result.getHeaders().get("baz"));
    GatewayProxyFactoryBean fb = context.getBean("&methodOverride", GatewayProxyFactoryBean.class);
    Map<?, ?> methods = TestUtils.getPropertyValue(fb, "methodMetadataMap", Map.class);
    GatewayMethodMetadata meta = (GatewayMethodMetadata) methods.get("oneWay");
    assertNotNull(meta);//from   w w  w  .  jav a 2  s. com
    assertEquals("456", meta.getRequestTimeout());
    assertEquals("123", meta.getReplyTimeout());
    assertEquals("foo", meta.getReplyChannelName());
}