Search in sources :

Example 31 with MessageHeaders

use of org.springframework.messaging.MessageHeaders in project rocketmq-externals by apache.

the class RocketMQTemplate method convertToRocketMsg.

/**
 * Convert spring message to rocketMQ message
 *
 * @param destination formats: `topicName:tags`
 * @param message {@link org.springframework.messaging.Message}
 * @return instance of {@link org.apache.rocketmq.common.message.Message}
 */
private org.apache.rocketmq.common.message.Message convertToRocketMsg(String destination, Message<?> message) {
    Object payloadObj = message.getPayload();
    byte[] payloads;
    if (payloadObj instanceof String) {
        payloads = ((String) payloadObj).getBytes(Charset.forName(charset));
    } else {
        try {
            String jsonObj = this.objectMapper.writeValueAsString(payloadObj);
            payloads = jsonObj.getBytes(Charset.forName(charset));
        } catch (Exception e) {
            throw new RuntimeException("convert to RocketMQ message failed.", e);
        }
    }
    String[] tempArr = destination.split(":", 2);
    String topic = tempArr[0];
    String tags = "";
    if (tempArr.length > 1) {
        tags = tempArr[1];
    }
    org.apache.rocketmq.common.message.Message rocketMsg = new org.apache.rocketmq.common.message.Message(topic, tags, payloads);
    MessageHeaders headers = message.getHeaders();
    if (Objects.nonNull(headers) && !headers.isEmpty()) {
        Object keys = headers.get(MessageConst.PROPERTY_KEYS);
        if (!StringUtils.isEmpty(keys)) {
            // if headers has 'KEYS', set rocketMQ message key
            rocketMsg.setKeys(keys.toString());
        }
        // set rocketMQ message flag
        Object flagObj = headers.getOrDefault("FLAG", "0");
        int flag = 0;
        try {
            flag = Integer.parseInt(flagObj.toString());
        } catch (NumberFormatException e) {
            // ignore
            log.info("flag must be integer, flagObj:{}", flagObj);
        }
        rocketMsg.setFlag(flag);
        // set rocketMQ message waitStoreMsgOkObj
        Object waitStoreMsgOkObj = headers.getOrDefault("WAIT_STORE_MSG_OK", "true");
        boolean waitStoreMsgOK = Boolean.TRUE.equals(waitStoreMsgOkObj);
        rocketMsg.setWaitStoreMsgOK(waitStoreMsgOK);
        headers.entrySet().stream().filter(entry -> !Objects.equals(entry.getKey(), MessageConst.PROPERTY_KEYS) && !Objects.equals(entry.getKey(), "FLAG") && // exclude "KEYS", "FLAG", "WAIT_STORE_MSG_OK"
        !Objects.equals(entry.getKey(), "WAIT_STORE_MSG_OK")).forEach(entry -> {
            // add other properties with prefix "USERS_"
            rocketMsg.putUserProperty("USERS_" + entry.getKey(), String.valueOf(entry.getValue()));
        });
    }
    return rocketMsg;
}
Also used : SendCallback(org.apache.rocketmq.client.producer.SendCallback) MessagingException(org.springframework.messaging.MessagingException) Setter(lombok.Setter) Getter(lombok.Getter) InitializingBean(org.springframework.beans.factory.InitializingBean) Charset(java.nio.charset.Charset) Map(java.util.Map) SendResult(org.apache.rocketmq.client.producer.SendResult) MessagePostProcessor(org.springframework.messaging.core.MessagePostProcessor) Message(org.springframework.messaging.Message) AbstractMessageSendingTemplate(org.springframework.messaging.core.AbstractMessageSendingTemplate) DefaultMQProducer(org.apache.rocketmq.client.producer.DefaultMQProducer) MessageQueueSelector(org.apache.rocketmq.client.producer.MessageQueueSelector) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) SelectMessageQueueByHash(org.apache.rocketmq.client.producer.selector.SelectMessageQueueByHash) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) MimeTypeUtils(org.springframework.util.MimeTypeUtils) MessageHeaders(org.springframework.messaging.MessageHeaders) Objects(java.util.Objects) Slf4j(lombok.extern.slf4j.Slf4j) MessageConst(org.apache.rocketmq.common.message.MessageConst) DisposableBean(org.springframework.beans.factory.DisposableBean) MessageBuilder(org.springframework.messaging.support.MessageBuilder) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) Message(org.springframework.messaging.Message) MessagingException(org.springframework.messaging.MessagingException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) MessageHeaders(org.springframework.messaging.MessageHeaders)

Example 32 with MessageHeaders

use of org.springframework.messaging.MessageHeaders in project spring-framework by spring-projects.

the class MessageHeaderAccessorTests method existingHeadersModification.

@Test
public void existingHeadersModification() throws InterruptedException {
    Map<String, Object> map = new HashMap<>();
    map.put("foo", "bar");
    map.put("bar", "baz");
    GenericMessage<String> message = new GenericMessage<>("payload", map);
    Thread.sleep(50);
    MessageHeaderAccessor accessor = new MessageHeaderAccessor(message);
    accessor.setHeader("foo", "BAR");
    MessageHeaders actual = accessor.getMessageHeaders();
    assertEquals(3, actual.size());
    assertNotEquals(message.getHeaders().getId(), actual.getId());
    assertEquals("BAR", actual.get("foo"));
    assertEquals("baz", actual.get("bar"));
}
Also used : HashMap(java.util.HashMap) MessageHeaders(org.springframework.messaging.MessageHeaders) Test(org.junit.Test)

Example 33 with MessageHeaders

use of org.springframework.messaging.MessageHeaders in project spring-framework by spring-projects.

the class MessageHeaderAccessorTests method leaveMutableDefaultBehavior.

@Test
public void leaveMutableDefaultBehavior() {
    MessageHeaderAccessor accessor = new MessageHeaderAccessor();
    accessor.setHeader("foo", "bar");
    MessageHeaders headers = accessor.getMessageHeaders();
    Message<?> message = MessageBuilder.createMessage("payload", headers);
    this.thrown.expect(IllegalStateException.class);
    this.thrown.expectMessage("Already immutable");
    accessor.setLeaveMutable(true);
    this.thrown.expect(IllegalStateException.class);
    this.thrown.expectMessage("Already immutable");
    accessor.setHeader("foo", "baz");
    assertEquals("bar", headers.get("foo"));
    assertSame(accessor, MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class));
}
Also used : MessageHeaders(org.springframework.messaging.MessageHeaders) Test(org.junit.Test)

Example 34 with MessageHeaders

use of org.springframework.messaging.MessageHeaders in project spring-framework by spring-projects.

the class MessageHeaderAccessorTests method copyHeadersIfAbsent.

@Test
public void copyHeadersIfAbsent() {
    Map<String, Object> map1 = new HashMap<>();
    map1.put("foo", "bar");
    GenericMessage<String> message = new GenericMessage<>("payload", map1);
    MessageHeaderAccessor accessor = new MessageHeaderAccessor(message);
    Map<String, Object> map2 = new HashMap<>();
    map2.put("foo", "BAR");
    map2.put("bar", "baz");
    accessor.copyHeadersIfAbsent(map2);
    MessageHeaders actual = accessor.getMessageHeaders();
    assertEquals(3, actual.size());
    assertEquals("bar", actual.get("foo"));
    assertEquals("baz", actual.get("bar"));
}
Also used : HashMap(java.util.HashMap) MessageHeaders(org.springframework.messaging.MessageHeaders) Test(org.junit.Test)

Example 35 with MessageHeaders

use of org.springframework.messaging.MessageHeaders in project spring-framework by spring-projects.

the class StompHeaderAccessorTests method messageIdAndTimestampDefaultBehavior.

@Test
public void messageIdAndTimestampDefaultBehavior() {
    StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.SEND);
    MessageHeaders headers = headerAccessor.getMessageHeaders();
    assertNull(headers.getId());
    assertNull(headers.getTimestamp());
}
Also used : MessageHeaders(org.springframework.messaging.MessageHeaders) Test(org.junit.Test)

Aggregations

MessageHeaders (org.springframework.messaging.MessageHeaders)55 Test (org.junit.Test)39 HashMap (java.util.HashMap)15 Message (org.springframework.messaging.Message)10 SimpMessageType (org.springframework.messaging.simp.SimpMessageType)6 SimpMessageHeaderAccessor (org.springframework.messaging.simp.SimpMessageHeaderAccessor)5 MessageHeaderAccessor (org.springframework.messaging.support.MessageHeaderAccessor)4 MimeType (org.springframework.util.MimeType)3 Principal (java.security.Principal)2 HashSet (java.util.HashSet)2 MessageConverter (org.springframework.messaging.converter.MessageConverter)2 StringMessageConverter (org.springframework.messaging.converter.StringMessageConverter)2 TestPrincipal (org.springframework.messaging.simp.TestPrincipal)2 StompHeaderAccessor (org.springframework.messaging.simp.stomp.StompHeaderAccessor)2 GenericMessage (org.springframework.messaging.support.GenericMessage)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 Method (java.lang.reflect.Method)1 Charset (java.nio.charset.Charset)1 Map (java.util.Map)1