Search in sources :

Example 26 with Message

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

the class GenericMessagingTemplateTests method convertAndSendWithSimpMessageHeaders.

@Test
public void convertAndSendWithSimpMessageHeaders() {
    MessageHeaderAccessor accessor = new MessageHeaderAccessor();
    accessor.setHeader("key", "value");
    accessor.setLeaveMutable(true);
    MessageHeaders headers = accessor.getMessageHeaders();
    this.template.convertAndSend("channel", "data", headers);
    List<Message<byte[]>> messages = this.messageChannel.getMessages();
    Message<byte[]> message = messages.get(0);
    assertSame(headers, message.getHeaders());
    assertFalse(accessor.isMutable());
}
Also used : Message(org.springframework.messaging.Message) GenericMessage(org.springframework.messaging.support.GenericMessage) MessageHeaderAccessor(org.springframework.messaging.support.MessageHeaderAccessor) MessageHeaders(org.springframework.messaging.MessageHeaders) Test(org.junit.Test)

Example 27 with Message

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

the class AbstractNioBufferReactorNettyCodec method decode.

@Override
public Collection<Message<P>> decode(ByteBuf inputBuffer) {
    ByteBuffer nioBuffer = inputBuffer.nioBuffer();
    int start = nioBuffer.position();
    List<Message<P>> messages = decodeInternal(nioBuffer);
    inputBuffer.skipBytes(nioBuffer.position() - start);
    return messages;
}
Also used : Message(org.springframework.messaging.Message) ByteBuffer(java.nio.ByteBuffer)

Example 28 with Message

use of org.springframework.messaging.Message 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 29 with Message

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

the class ChannelInterceptorTests method postSendInterceptorMessageWasNotSent.

@Test
public void postSendInterceptorMessageWasNotSent() {
    final AbstractMessageChannel testChannel = new AbstractMessageChannel() {

        @Override
        protected boolean sendInternal(Message<?> message, long timeout) {
            return false;
        }
    };
    final AtomicBoolean preSendInvoked = new AtomicBoolean(false);
    final AtomicBoolean completionInvoked = new AtomicBoolean(false);
    testChannel.addInterceptor(new ChannelInterceptorAdapter() {

        @Override
        public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
            assertInput(message, channel, sent);
            preSendInvoked.set(true);
        }

        @Override
        public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) {
            assertInput(message, channel, sent);
            completionInvoked.set(true);
        }

        private void assertInput(Message<?> message, MessageChannel channel, boolean sent) {
            assertNotNull(message);
            assertNotNull(channel);
            assertSame(testChannel, channel);
            assertFalse(sent);
        }
    });
    testChannel.send(MessageBuilder.withPayload("test").build());
    assertTrue(preSendInvoked.get());
    assertTrue(completionInvoked.get());
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Message(org.springframework.messaging.Message) MessageChannel(org.springframework.messaging.MessageChannel) MessagingException(org.springframework.messaging.MessagingException) Test(org.junit.Test)

Example 30 with Message

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

the class UserDestinationMessageHandlerTests method handleSubscribe.

@Test
public void handleSubscribe() {
    given(this.brokerChannel.send(Mockito.any(Message.class))).willReturn(true);
    this.handler.handleMessage(createWith(SimpMessageType.SUBSCRIBE, "joe", SESSION_ID, "/user/queue/foo"));
    ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
    Mockito.verify(this.brokerChannel).send(captor.capture());
    Message message = captor.getValue();
    assertEquals("/queue/foo-user123", SimpMessageHeaderAccessor.getDestination(message.getHeaders()));
}
Also used : Message(org.springframework.messaging.Message) Test(org.junit.Test)

Aggregations

Message (org.springframework.messaging.Message)51 Test (org.junit.Test)41 SimpMessageHeaderAccessor (org.springframework.messaging.simp.SimpMessageHeaderAccessor)16 MessageHeaders (org.springframework.messaging.MessageHeaders)14 StompHeaderAccessor (org.springframework.messaging.simp.stomp.StompHeaderAccessor)9 BinaryMessage (org.springframework.web.socket.BinaryMessage)9 TextMessage (org.springframework.web.socket.TextMessage)9 WebSocketMessage (org.springframework.web.socket.WebSocketMessage)6 ByteBuffer (java.nio.ByteBuffer)5 MessageChannel (org.springframework.messaging.MessageChannel)4 MessageHeaderAccessor (org.springframework.messaging.support.MessageHeaderAccessor)4 Method (java.lang.reflect.Method)3 MethodParameter (org.springframework.core.MethodParameter)3 TestPrincipal (org.springframework.messaging.simp.TestPrincipal)3 Principal (java.security.Principal)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 TextMessage (javax.jms.TextMessage)2 SynthesizingMethodParameter (org.springframework.core.annotation.SynthesizingMethodParameter)2 StubTextMessage (org.springframework.jms.StubTextMessage)2 MessagingException (org.springframework.messaging.MessagingException)2