org.springframework.messaging.converter.MessageConverter Java Examples

The following examples show how to use org.springframework.messaging.converter.MessageConverter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RqueueMessageConfigTest.java    From rqueue with Apache License 2.0 6 votes vote down vote up
@Test
public void rqueueMessageSenderWithMessageConverters() throws IllegalAccessException {
  SimpleRqueueListenerContainerFactory factory = new SimpleRqueueListenerContainerFactory();
  MessageConverter messageConverter = new GenericMessageConverter();
  RqueueListenerConfig messageConfig = new RqueueListenerConfig();
  factory.setMessageConverters(Collections.singletonList(messageConverter));
  FieldUtils.writeField(messageConfig, "simpleRqueueListenerContainerFactory", factory, true);
  factory.setRedisConnectionFactory(mock(RedisConnectionFactory.class));
  assertNotNull(messageConfig.rqueueMessageSender(rqueueMessageTemplate));
  RqueueMessageSender messageSender = messageConfig.rqueueMessageSender(rqueueMessageTemplate);
  boolean messageConverterIsConfigured = false;
  for (MessageConverter converter : messageSender.getMessageConverters()) {
    messageConverterIsConfigured =
        messageConverterIsConfigured || converter.hashCode() == messageConverter.hashCode();
  }
  assertTrue(messageConverterIsConfigured);
}
 
Example #2
Source File: MessageConverterConfigurerTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
public void testConfigureOutputChannelWithBadContentType() {
	BindingServiceProperties props = new BindingServiceProperties();
	BindingProperties bindingProps = new BindingProperties();
	bindingProps.setContentType("application/json");
	props.setBindings(Collections.singletonMap("foo", bindingProps));
	CompositeMessageConverterFactory converterFactory = new CompositeMessageConverterFactory(
			Collections.<MessageConverter>emptyList(), null);
	MessageConverterConfigurer configurer = new MessageConverterConfigurer(props,
			converterFactory.getMessageConverterForAllRegistered());
	QueueChannel out = new QueueChannel();
	configurer.configureOutputChannel(out, "foo");
	out.send(new GenericMessage<Foo>(new Foo(), Collections
			.<String, Object>singletonMap(MessageHeaders.CONTENT_TYPE, "bad/ct")));
	Message<?> received = out.receive(0);
	assertThat(received).isNotNull();
	assertThat(received.getPayload()).isInstanceOf(Foo.class);
}
 
Example #3
Source File: MessageBrokerConfigurationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void configureMessageConvertersCustom() {
	final MessageConverter testConverter = mock(MessageConverter.class);
	AbstractMessageBrokerConfiguration config = new BaseTestMessageBrokerConfig() {
		@Override
		protected boolean configureMessageConverters(List<MessageConverter> messageConverters) {
			messageConverters.add(testConverter);
			return false;
		}
	};

	CompositeMessageConverter compositeConverter = config.brokerMessageConverter();
	assertThat(compositeConverter.getConverters().size(), Matchers.is(1));
	Iterator<MessageConverter> iterator = compositeConverter.getConverters().iterator();
	assertThat(iterator.next(), Matchers.is(testConverter));
}
 
Example #4
Source File: RocketMQMessageConverter.java    From rocketmq-spring with Apache License 2.0 6 votes vote down vote up
public RocketMQMessageConverter() {
    List<MessageConverter> messageConverters = new ArrayList<>();
    ByteArrayMessageConverter byteArrayMessageConverter = new ByteArrayMessageConverter();
    byteArrayMessageConverter.setContentTypeResolver(null);
    messageConverters.add(byteArrayMessageConverter);
    messageConverters.add(new StringMessageConverter());
    if (JACKSON_PRESENT) {
        messageConverters.add(new MappingJackson2MessageConverter());
    }
    if (FASTJSON_PRESENT) {
        try {
            messageConverters.add(
                (MessageConverter)ClassUtils.forName(
                    "com.alibaba.fastjson.support.spring.messaging.MappingFastJsonMessageConverter",
                    ClassUtils.getDefaultClassLoader()).newInstance());
        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException ignored) {
            //ignore this exception
        }
    }
    messageConverter = new CompositeMessageConverter(messageConverters);
}
 
Example #5
Source File: EventRouter.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
private void sendHistoryToNewSubscriber(AbstractSubProtocolEvent ev) {
    Message<byte[]> msg = ev.getMessage();
    StompHeaderAccessor ha = StompHeaderAccessor.wrap(msg);
    String pattern = ha.getDestination();
    if(!pattern.startsWith(PREFIX)) {
        // we must send only to appropriate paths
        return;
    }
    MessageConverter messageConverter = this.simpMessagingTemplate.getMessageConverter();

    for(BusData data: buses.values()) {
        String dest = getDestination(data.getId());
        if(!this.pathMatcher.match(pattern, dest)) {
            continue;
        }
        for(Object obj: data.getEvents()) {
            StompHeaderAccessor mha = Stomp.createHeaders(ha.getSessionId(), ha.getSubscriptionId());
            mha.setDestination(dest);
            Message<?> message = messageConverter.toMessage(obj, mha.getMessageHeaders());
            clientChannel.send(message);
        }
    }
}
 
Example #6
Source File: MessageBrokerConfigurationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void configureMessageConvertersCustom() {
	final MessageConverter testConverter = mock(MessageConverter.class);
	AbstractMessageBrokerConfiguration config = new BaseTestMessageBrokerConfig() {
		@Override
		protected boolean configureMessageConverters(List<MessageConverter> messageConverters) {
			messageConverters.add(testConverter);
			return false;
		}
	};

	CompositeMessageConverter compositeConverter = config.brokerMessageConverter();
	assertThat(compositeConverter.getConverters().size(), Matchers.is(1));
	Iterator<MessageConverter> iterator = compositeConverter.getConverters().iterator();
	assertThat(iterator.next(), Matchers.is(testConverter));
}
 
Example #7
Source File: SimpAnnotationMethodMessageHandler.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Create an instance of SimpAnnotationMethodMessageHandler with the given
 * message channels and broker messaging template.
 * @param clientInboundChannel the channel for receiving messages from clients (e.g. WebSocket clients)
 * @param clientOutboundChannel the channel for messages to clients (e.g. WebSocket clients)
 * @param brokerTemplate a messaging template to send application messages to the broker
 */
public SimpAnnotationMethodMessageHandler(SubscribableChannel clientInboundChannel,
		MessageChannel clientOutboundChannel, SimpMessageSendingOperations brokerTemplate) {

	Assert.notNull(clientInboundChannel, "clientInboundChannel must not be null");
	Assert.notNull(clientOutboundChannel, "clientOutboundChannel must not be null");
	Assert.notNull(brokerTemplate, "brokerTemplate must not be null");

	this.clientInboundChannel = clientInboundChannel;
	this.clientMessagingTemplate = new SimpMessagingTemplate(clientOutboundChannel);
	this.brokerTemplate = brokerTemplate;

	Collection<MessageConverter> converters = new ArrayList<MessageConverter>();
	converters.add(new StringMessageConverter());
	converters.add(new ByteArrayMessageConverter());
	this.messageConverter = new CompositeMessageConverter(converters);
}
 
Example #8
Source File: MessageBrokerConfigurationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void configureMessageConvertersCustomAndDefault() {
	final MessageConverter testConverter = mock(MessageConverter.class);

	AbstractMessageBrokerConfiguration config = new BaseTestMessageBrokerConfig() {
		@Override
		protected boolean configureMessageConverters(List<MessageConverter> messageConverters) {
			messageConverters.add(testConverter);
			return true;
		}
	};
	CompositeMessageConverter compositeConverter = config.brokerMessageConverter();

	assertThat(compositeConverter.getConverters().size(), Matchers.is(4));
	Iterator<MessageConverter> iterator = compositeConverter.getConverters().iterator();
	assertThat(iterator.next(), Matchers.is(testConverter));
	assertThat(iterator.next(), Matchers.instanceOf(StringMessageConverter.class));
	assertThat(iterator.next(), Matchers.instanceOf(ByteArrayMessageConverter.class));
	assertThat(iterator.next(), Matchers.instanceOf(MappingJackson2MessageConverter.class));
}
 
Example #9
Source File: SimpAnnotationMethodMessageHandler.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Create an instance of SimpAnnotationMethodMessageHandler with the given
 * message channels and broker messaging template.
 * @param clientInboundChannel the channel for receiving messages from clients (e.g. WebSocket clients)
 * @param clientOutboundChannel the channel for messages to clients (e.g. WebSocket clients)
 * @param brokerTemplate a messaging template to send application messages to the broker
 */
public SimpAnnotationMethodMessageHandler(SubscribableChannel clientInboundChannel,
		MessageChannel clientOutboundChannel, SimpMessageSendingOperations brokerTemplate) {

	Assert.notNull(clientInboundChannel, "clientInboundChannel must not be null");
	Assert.notNull(clientOutboundChannel, "clientOutboundChannel must not be null");
	Assert.notNull(brokerTemplate, "brokerTemplate must not be null");

	this.clientInboundChannel = clientInboundChannel;
	this.clientMessagingTemplate = new SimpMessagingTemplate(clientOutboundChannel);
	this.brokerTemplate = brokerTemplate;

	Collection<MessageConverter> converters = new ArrayList<>();
	converters.add(new StringMessageConverter());
	converters.add(new ByteArrayMessageConverter());
	this.messageConverter = new CompositeMessageConverter(converters);
}
 
Example #10
Source File: AbstractMessageChannelMessagingSendingTemplate.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
protected void initMessageConverter(MessageConverter messageConverter) {

		StringMessageConverter stringMessageConverter = new StringMessageConverter();
		stringMessageConverter.setSerializedPayloadClass(String.class);

		List<MessageConverter> messageConverters = new ArrayList<>();
		messageConverters.add(stringMessageConverter);

		if (messageConverter != null) {
			messageConverters.add(messageConverter);
		}
		else {
			MappingJackson2MessageConverter mappingJackson2MessageConverter = new MappingJackson2MessageConverter();
			mappingJackson2MessageConverter.setSerializedPayloadClass(String.class);
			messageConverters.add(mappingJackson2MessageConverter);
		}

		setMessageConverter(new CompositeMessageConverter(messageConverters));
	}
 
Example #11
Source File: DefaultMessageHandlerMethodFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void customMessageConverterFailure() throws Exception {
	DefaultMessageHandlerMethodFactory instance = createInstance();
	MessageConverter messageConverter = new ByteArrayMessageConverter();
	instance.setMessageConverter(messageConverter);
	instance.afterPropertiesSet();

	InvocableHandlerMethod invocableHandlerMethod =
			createInvocableHandlerMethod(instance, "simpleString", String.class);

	thrown.expect(MessageConversionException.class);
	invocableHandlerMethod.invoke(MessageBuilder.withPayload(123).build());
}
 
Example #12
Source File: Stomp.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
/**
 * Send message to queue of current session
 * @param subscriptionId
 * @param dest
 * @param msg
 */
public void sendToSubscription(String subscriptionId, String dest, Object msg) {
    Assert.notNull(subscriptionId, "subscriptionId is null");
    StompHeaderAccessor sha = createHeaders(sessionId, subscriptionId);
    MessageConverter messageConverter = this.template.getMessageConverter();
    sha.setDestination("/queue/" + dest);
    Message<?> message = messageConverter.toMessage(msg, sha.getMessageHeaders());
    clientChannel.send(message);
}
 
Example #13
Source File: MessageSendingTemplateTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test(expected = MessageConversionException.class)
public void convertAndSendNoMatchingConverter() {

	MessageConverter converter = new CompositeMessageConverter(
			Arrays.<MessageConverter>asList(new MappingJackson2MessageConverter()));
	this.template.setMessageConverter(converter);

	this.headers.put(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_XML);
	this.template.convertAndSend("home", "payload", new MessageHeaders(this.headers));
}
 
Example #14
Source File: SimpAnnotationMethodMessageHandler.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Configure a {@link MessageConverter} to use to convert the payload of a message from
 * its serialized form with a specific MIME type to an Object matching the target method
 * parameter. The converter is also used when sending a message to the message broker.
 * @see CompositeMessageConverter
 */
public void setMessageConverter(MessageConverter converter) {
	this.messageConverter = converter;
	if (converter != null) {
		((AbstractMessageSendingTemplate<?>) this.clientMessagingTemplate).setMessageConverter(converter);
	}
}
 
Example #15
Source File: MessageUtils.java    From rqueue with Apache License 2.0 5 votes vote down vote up
public static Object convertMessageToObject(
    Message<String> message, List<MessageConverter> messageConverters) {
  notEmpty(messageConverters, "messageConverters cannot be empty");
  for (MessageConverter messageConverter : messageConverters) {
    try {
      return messageConverter.fromMessage(message, null);
    } catch (Exception e) {
    }
  }
  return null;
}
 
Example #16
Source File: MessageSendingTemplateTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test(expected = MessageConversionException.class)
public void convertAndSendNoMatchingConverter() {

	MessageConverter converter = new CompositeMessageConverter(
			Arrays.<MessageConverter>asList(new MappingJackson2MessageConverter()));
	this.template.setMessageConverter(converter);

	this.headers.put(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_XML);
	this.template.convertAndSend("home", "payload", new MessageHeaders(this.headers));
}
 
Example #17
Source File: AppConfig.java    From Mastering-Microservices-with-Java-Third-Edition with MIT License 5 votes vote down vote up
@Bean
@StreamMessageConverter
public MessageConverter bookingOrderMessageConverter() throws IOException {
  LOG.info("avro message converter bean initialized.");
  MessageConverter avroSchemaMessageConverter = new AvroSchemaMessageConverter(
      MimeType.valueOf("application/*+avro"));
  ((AvroSchemaMessageConverter) avroSchemaMessageConverter)
      .setSchemaLocation(new ClassPathResource("avro/bookingOrder.avsc"));
  return avroSchemaMessageConverter;
}
 
Example #18
Source File: DefaultMessageHandlerMethodFactoryTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void customMessageConverterFailure() throws Exception {
	DefaultMessageHandlerMethodFactory instance = createInstance();
	MessageConverter messageConverter = new ByteArrayMessageConverter();
	instance.setMessageConverter(messageConverter);
	instance.afterPropertiesSet();

	InvocableHandlerMethod invocableHandlerMethod =
			createInvocableHandlerMethod(instance, "simpleString", String.class);

	thrown.expect(MessageConversionException.class);
	invocableHandlerMethod.invoke(MessageBuilder.withPayload(123).build());
}
 
Example #19
Source File: WebSocketConfig.java    From bearchoke with Apache License 2.0 5 votes vote down vote up
@Override
public boolean configureMessageConverters(List<MessageConverter> converters) {
    MappingJackson2MessageConverter jacksonConverter = new MappingJackson2MessageConverter();
    jacksonConverter.setObjectMapper(objectMapper);
    converters.add(jacksonConverter);

    return true;
}
 
Example #20
Source File: MessageMethodArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before
public void setup() throws Exception {
	this.method = MessageMethodArgumentResolverTests.class.getDeclaredMethod("handle",
			Message.class, Message.class, Message.class, Message.class, ErrorMessage.class, Message.class);

	this.converter = mock(MessageConverter.class);
	this.resolver = new MessageMethodArgumentResolver(this.converter);
}
 
Example #21
Source File: QueueMessageHandler.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
private CompositeMessageConverter createPayloadArgumentCompositeConverter() {
	List<MessageConverter> payloadArgumentConverters = new ArrayList<>(
			this.messageConverters);

	ObjectMessageConverter objectMessageConverter = new ObjectMessageConverter();
	objectMessageConverter.setStrictContentTypeMatch(true);
	payloadArgumentConverters.add(objectMessageConverter);

	payloadArgumentConverters.add(new SimpleMessageConverter());

	return new CompositeMessageConverter(payloadArgumentConverters);
}
 
Example #22
Source File: MultiServerUserRegistry.java    From spring-analysis-note with MIT License 5 votes vote down vote up
void addRemoteRegistryDto(Message<?> message, MessageConverter converter, long expirationPeriod) {
	UserRegistrySnapshot registry = (UserRegistrySnapshot) converter.fromMessage(message, UserRegistrySnapshot.class);
	if (registry != null && !registry.getId().equals(this.id)) {
		registry.init(expirationPeriod, this.sessionLookup);
		this.remoteRegistries.put(registry.getId(), registry);
	}
}
 
Example #23
Source File: AbstractMessageBrokerConfiguration.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Bean
public CompositeMessageConverter brokerMessageConverter() {
	List<MessageConverter> converters = new ArrayList<>();
	boolean registerDefaults = configureMessageConverters(converters);
	if (registerDefaults) {
		converters.add(new StringMessageConverter());
		converters.add(new ByteArrayMessageConverter());
		if (jackson2Present) {
			converters.add(createJacksonConverter());
		}
	}
	return new CompositeMessageConverter(converters);
}
 
Example #24
Source File: MultiServerUserRegistry.java    From java-technology-stack with MIT License 5 votes vote down vote up
void addRemoteRegistryDto(Message<?> message, MessageConverter converter, long expirationPeriod) {
	UserRegistrySnapshot registry = (UserRegistrySnapshot) converter.fromMessage(message, UserRegistrySnapshot.class);
	if (registry != null && !registry.getId().equals(this.id)) {
		registry.init(expirationPeriod, this.sessionLookup);
		this.remoteRegistries.put(registry.getId(), registry);
	}
}
 
Example #25
Source File: KafkaStreamsMessageConversionDelegate.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
private void convertAndSetMessage(Object o, Class<?> valueClass,
		MessageConverter messageConverter, Message<?> msg) {
	Object result = valueClass.isAssignableFrom(msg.getPayload().getClass())
			? msg.getPayload() : messageConverter.fromMessage(msg, valueClass);

	Assert.notNull(result, "Failed to convert message " + msg);

	keyValueThreadLocal.set(new KeyValue<>(o, result));
}
 
Example #26
Source File: SimpleFunctionRegistryTests.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void before() {
	List<MessageConverter> messageConverters = new ArrayList<>();
	JsonMapper jsonMapper = new GsonMapper(new Gson());
	messageConverters.add(NegotiatingMessageConverterWrapper.wrap(new JsonMessageConverter(jsonMapper)));
	messageConverters.add(NegotiatingMessageConverterWrapper.wrap(new ByteArrayMessageConverter()));
	messageConverters.add(NegotiatingMessageConverterWrapper.wrap(new StringMessageConverter()));
	this.messageConverter = new CompositeMessageConverter(messageConverters);

	this.conversionService = new DefaultConversionService();
}
 
Example #27
Source File: MessageConverterConfigurerTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
public void testConfigureOutputChannelCannotConvert() {
	BindingServiceProperties props = new BindingServiceProperties();
	BindingProperties bindingProps = new BindingProperties();
	bindingProps.setContentType("foo/bar");
	props.setBindings(Collections.singletonMap("foo", bindingProps));
	MessageConverter converter = new AbstractMessageConverter(
			new MimeType("foo", "bar")) {

		@Override
		protected boolean supports(Class<?> clazz) {
			return true;
		}

		@Override
		protected Object convertToInternal(Object payload, MessageHeaders headers,
				Object conversionHint) {
			return null;
		}

	};
	CompositeMessageConverterFactory converterFactory = new CompositeMessageConverterFactory(
			Collections.<MessageConverter>singletonList(converter), null);
	MessageConverterConfigurer configurer = new MessageConverterConfigurer(props,
			converterFactory.getMessageConverterForAllRegistered());
	QueueChannel out = new QueueChannel();
	configurer.configureOutputChannel(out, "foo");
	try {
		out.send(new GenericMessage<Foo>(new Foo(),
				Collections.<String, Object>singletonMap(MessageHeaders.CONTENT_TYPE,
						"bad/ct")));
		fail("Expected MessageConversionException: " + out.receive(0));
	}
	catch (MessageConversionException e) {
		assertThat(e.getMessage())
				.endsWith("to the configured output type: 'foo/bar'");
	}
}
 
Example #28
Source File: AbstractMessageReceivingTemplate.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Convert from the given message to the given target class.
 * @param message the message to convert
 * @param targetClass the target class to convert the payload to
 * @return the converted payload of the reply message (never {@code null})
 */
@SuppressWarnings("unchecked")
@Nullable
protected <T> T doConvert(Message<?> message, Class<T> targetClass) {
	MessageConverter messageConverter = getMessageConverter();
	T value = (T) messageConverter.fromMessage(message, targetClass);
	if (value == null) {
		throw new MessageConversionException(message, "Unable to convert payload [" + message.getPayload() +
				"] to type [" + targetClass + "] using converter [" + messageConverter + "]");
	}
	return value;
}
 
Example #29
Source File: MessageConverterDelegateSerdeTest.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
@Ignore
public void testCompositeNonNativeSerdeUsingAvroContentType() {
	Random random = new Random();
	Sensor sensor = new Sensor();
	sensor.setId(UUID.randomUUID().toString() + "-v1");
	sensor.setAcceleration(random.nextFloat() * 10);
	sensor.setVelocity(random.nextFloat() * 100);
	sensor.setTemperature(random.nextFloat() * 50);

	List<MessageConverter> messageConverters = new ArrayList<>();
	messageConverters.add(new AvroSchemaMessageConverter(new AvroSchemaServiceManagerImpl()));
	CompositeMessageConverterFactory compositeMessageConverterFactory = new CompositeMessageConverterFactory(
			messageConverters, new ObjectMapper());
	MessageConverterDelegateSerde messageConverterDelegateSerde = new MessageConverterDelegateSerde(
			compositeMessageConverterFactory.getMessageConverterForAllRegistered());

	Map<String, Object> configs = new HashMap<>();
	configs.put("valueClass", Sensor.class);
	configs.put("contentType", "application/avro");
	messageConverterDelegateSerde.configure(configs, false);
	final byte[] serialized = messageConverterDelegateSerde.serializer().serialize(null,
			sensor);

	final Object deserialized = messageConverterDelegateSerde.deserializer()
			.deserialize(null, serialized);

	assertThat(deserialized).isEqualTo(sensor);
}
 
Example #30
Source File: MessageMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Before
public void setup() throws Exception {
	this.method = MessageMethodArgumentResolverTests.class.getDeclaredMethod("handle",
			Message.class, Message.class, Message.class, Message.class, ErrorMessage.class, Message.class);

	this.converter = mock(MessageConverter.class);
	this.resolver = new MessageMethodArgumentResolver(this.converter);
}