Search in sources :

Example 1 with Message

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

the class DefaultStompSession method createMessage.

@SuppressWarnings("unchecked")
private Message<byte[]> createMessage(StompHeaderAccessor accessor, Object payload) {
    accessor.updateSimpMessageHeadersFromStompHeaders();
    Message<byte[]> message;
    if (payload == null) {
        message = MessageBuilder.createMessage(EMPTY_PAYLOAD, accessor.getMessageHeaders());
    } else if (payload instanceof byte[]) {
        message = MessageBuilder.createMessage((byte[]) payload, accessor.getMessageHeaders());
    } else {
        message = (Message<byte[]>) getMessageConverter().toMessage(payload, accessor.getMessageHeaders());
        accessor.updateStompHeadersFromSimpMessageHeaders();
        if (message == null) {
            throw new MessageConversionException("Unable to convert payload with type='" + payload.getClass().getName() + "', contentType='" + accessor.getContentType() + "', converter=[" + getMessageConverter() + "]");
        }
    }
    return message;
}
Also used : MessageConversionException(org.springframework.messaging.converter.MessageConversionException) Message(org.springframework.messaging.Message)

Example 2 with Message

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

the class SimpAnnotationMethodMessageHandlerTests method listenableFutureFailure.

@Test
@SuppressWarnings("unchecked")
public void listenableFutureFailure() {
    Message emptyMessage = (Message) MessageBuilder.withPayload(new byte[0]).build();
    given(this.channel.send(any(Message.class))).willReturn(true);
    given(this.converter.toMessage(any(), any(MessageHeaders.class))).willReturn(emptyMessage);
    ListenableFutureController controller = new ListenableFutureController();
    this.messageHandler.registerHandler(controller);
    this.messageHandler.setDestinationPrefixes(Arrays.asList("/app1", "/app2/"));
    Message<?> message = createMessage("/app1/listenable-future/failure");
    this.messageHandler.handleMessage(message);
    controller.future.run();
    assertTrue(controller.exceptionCaught);
}
Also used : Message(org.springframework.messaging.Message) MessageHeaders(org.springframework.messaging.MessageHeaders) Test(org.junit.Test)

Example 3 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 4 with Message

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

the class JmsMockTests method setup.

@Before
public void setup() throws JMSException {
    Mockito.reset(this.mockJmsTemplate);
    TextMessage message = mock(TextMessage.class);
    willReturn(new SimpleMessageConverter()).given(this.mockJmsTemplate).getMessageConverter();
    willReturn(message).given(this.mockJmsTemplate).receiveSelected(isNull());
    willAnswer((Answer<String>) invocation -> testMessageHolder.get()).given(message).getText();
}
Also used : DirtiesContext(org.springframework.test.annotation.DirtiesContext) MessagingException(org.springframework.messaging.MessagingException) SimpleMessageConverter(org.springframework.jms.support.converter.SimpleMessageConverter) RunWith(org.junit.runner.RunWith) SubscribableChannel(org.springframework.messaging.SubscribableChannel) Autowired(org.springframework.beans.factory.annotation.Autowired) AtomicReference(java.util.concurrent.atomic.AtomicReference) BDDMockito.willReturn(org.mockito.BDDMockito.willReturn) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) SpringJUnit4ClassRunner(org.springframework.test.context.junit4.SpringJUnit4ClassRunner) BDDMockito.given(org.mockito.BDDMockito.given) Qualifier(org.springframework.beans.factory.annotation.Qualifier) JmsTemplate(org.springframework.jms.core.JmsTemplate) Message(org.springframework.messaging.Message) Before(org.junit.Before) ArgumentMatchers.isNull(org.mockito.ArgumentMatchers.isNull) ClassMode(org.springframework.test.annotation.DirtiesContext.ClassMode) TextMessage(javax.jms.TextMessage) Assert.assertTrue(org.junit.Assert.assertTrue) SourcePollingChannelAdapter(org.springframework.integration.endpoint.SourcePollingChannelAdapter) IOException(java.io.IOException) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) MessageChannel(org.springframework.messaging.MessageChannel) JMSException(javax.jms.JMSException) BDDMockito.willAnswer(org.mockito.BDDMockito.willAnswer) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) Mockito(org.mockito.Mockito) MessageHandler(org.springframework.messaging.MessageHandler) ContextConfiguration(org.springframework.test.context.ContextConfiguration) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) Assert.assertEquals(org.junit.Assert.assertEquals) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Mockito.mock(org.mockito.Mockito.mock) SimpleMessageConverter(org.springframework.jms.support.converter.SimpleMessageConverter) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) TextMessage(javax.jms.TextMessage) Before(org.junit.Before)

Example 5 with Message

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

the class AggregatorDemoTest method testGatewayDemo.

@Test
public void testGatewayDemo() throws InterruptedException {
    System.setProperty("spring.profiles.active", "testCase");
    final GenericXmlApplicationContext applicationContext = new GenericXmlApplicationContext(configFilesGatewayDemo);
    final MessageChannel stdinToJmsOutChannel = applicationContext.getBean("stdinToJmsOutChannel", MessageChannel.class);
    stdinToJmsOutChannel.send(MessageBuilder.withPayload("jms test").build());
    final QueueChannel queueChannel = applicationContext.getBean("queueChannel", QueueChannel.class);
    @SuppressWarnings("unchecked") Message<List<String>> reply = (Message<List<String>>) queueChannel.receive(600000);
    Assert.assertNotNull(reply);
    List<String> out = reply.getPayload();
    Assert.assertEquals("[JMS TEST, JMS TEST]", out.toString());
    applicationContext.close();
}
Also used : MessageChannel(org.springframework.messaging.MessageChannel) QueueChannel(org.springframework.integration.channel.QueueChannel) Message(org.springframework.messaging.Message) List(java.util.List) GenericXmlApplicationContext(org.springframework.context.support.GenericXmlApplicationContext) Test(org.junit.Test)

Aggregations

Message (org.springframework.messaging.Message)577 Test (org.junit.Test)415 GenericMessage (org.springframework.messaging.support.GenericMessage)265 QueueChannel (org.springframework.integration.channel.QueueChannel)185 MessageChannel (org.springframework.messaging.MessageChannel)116 ArrayList (java.util.ArrayList)110 BeanFactory (org.springframework.beans.factory.BeanFactory)85 CountDownLatch (java.util.concurrent.CountDownLatch)78 AtomicReference (java.util.concurrent.atomic.AtomicReference)65 DirectChannel (org.springframework.integration.channel.DirectChannel)63 MessageHandler (org.springframework.messaging.MessageHandler)57 Test (org.junit.jupiter.api.Test)56 PollableChannel (org.springframework.messaging.PollableChannel)55 List (java.util.List)53 ErrorMessage (org.springframework.messaging.support.ErrorMessage)52 Matchers.containsString (org.hamcrest.Matchers.containsString)50 MessagingException (org.springframework.messaging.MessagingException)49 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)41 Assert.assertEquals (org.junit.Assert.assertEquals)40 Assert.assertTrue (org.junit.Assert.assertTrue)39