List of usage examples for org.springframework.messaging Message getPayload
T getPayload();
From source file:org.springframework.cloud.stream.binder.kafka.streams.KafkaStreamsMessageConversionDelegate.java
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)); }
From source file:org.springframework.cloud.stream.binder.kafka.streams.KafkaStreamsMessageConversionDelegate.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private void processErrorFromDeserialization(KStream<?, ?> bindingTarget, KStream<?, ?> branch) { branch.process(() -> new Processor() { ProcessorContext context;/*from w w w . j a va 2s . c o m*/ @Override public void init(ProcessorContext context) { this.context = context; } @Override public void process(Object o, Object o2) { //Only continue if the record was not a tombstone. if (o2 != null) { if (KafkaStreamsMessageConversionDelegate.this.kstreamBindingInformationCatalogue .isDlqEnabled(bindingTarget)) { String destination = this.context.topic(); if (o2 instanceof Message) { Message message = (Message) o2; KafkaStreamsMessageConversionDelegate.this.sendToDlqAndContinue.sendToDlq(destination, (byte[]) o, (byte[]) message.getPayload(), this.context.partition()); } else { KafkaStreamsMessageConversionDelegate.this.sendToDlqAndContinue.sendToDlq(destination, (byte[]) o, (byte[]) o2, this.context.partition()); } } else if (KafkaStreamsMessageConversionDelegate.this.kstreamBinderConfigurationProperties .getSerdeError() == KafkaStreamsBinderConfigurationProperties.SerdeError.logAndFail) { throw new IllegalStateException( "Inbound deserialization failed. Stopping further processing of records."); } else if (KafkaStreamsMessageConversionDelegate.this.kstreamBinderConfigurationProperties .getSerdeError() == KafkaStreamsBinderConfigurationProperties.SerdeError.logAndContinue) { //quietly passing through. No action needed, this is similar to log and continue. LOG.error("Inbound deserialization failed. Skipping this record and continuing."); } } } @Override public void close() { } }); }
From source file:org.springframework.cloud.stream.binder.pubsub.PubSubMessageHandler.java
protected PubSubMessage convert(Message<?> message) throws Exception { String encodedHeaders = encodeHeaders(message.getHeaders()); String topic = producerProperties.isPartitioned() ? topics.get((Integer) message.getHeaders().get(BinderHeaders.PARTITION_HEADER)).name() : topics.get(0).name();//from www. ja v a 2 s . c o m PubSubMessage pubSubMessage = new PubSubMessage( com.google.cloud.pubsub.Message.builder(ByteArray.copyFrom((byte[]) message.getPayload())) .addAttribute(PubSubBinder.SCST_HEADERS, encodedHeaders).build(), topic); return pubSubMessage; }
From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderTests.java
@SuppressWarnings("unchecked") @Test// www. ja v a 2 s . c o m public void testBatchingAndCompression() throws Exception { RabbitTestBinder binder = getBinder(); ExtendedProducerProperties<RabbitProducerProperties> producerProperties = createProducerProperties(); producerProperties.getExtension().setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT); producerProperties.getExtension().setBatchingEnabled(true); producerProperties.getExtension().setBatchSize(2); producerProperties.getExtension().setBatchBufferLimit(100000); producerProperties.getExtension().setBatchTimeout(30000); producerProperties.getExtension().setCompress(true); producerProperties.setRequiredGroups("default"); DirectChannel output = createBindableChannel("input", createProducerBindingProperties(producerProperties)); output.setBeanName("batchingProducer"); Binding<MessageChannel> producerBinding = binder.bindProducer("batching.0", output, producerProperties); Log logger = spy(TestUtils.getPropertyValue(binder, "binder.compressingPostProcessor.logger", Log.class)); new DirectFieldAccessor(TestUtils.getPropertyValue(binder, "binder.compressingPostProcessor")) .setPropertyValue("logger", logger); when(logger.isTraceEnabled()).thenReturn(true); assertThat(TestUtils.getPropertyValue(binder, "binder.compressingPostProcessor.level")) .isEqualTo(Deflater.BEST_SPEED); output.send(new GenericMessage<>("foo".getBytes())); output.send(new GenericMessage<>("bar".getBytes())); Object out = spyOn("batching.0.default").receive(false); assertThat(out).isInstanceOf(byte[].class); assertThat(new String((byte[]) out)).isEqualTo("\u0000\u0000\u0000\u0003foo\u0000\u0000\u0000\u0003bar"); ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class); verify(logger).trace(captor.capture()); assertThat(captor.getValue().toString()).contains(("Compressed 14 to ")); QueueChannel input = new QueueChannel(); input.setBeanName("batchingConsumer"); Binding<MessageChannel> consumerBinding = binder.bindConsumer("batching.0", "test", input, createConsumerProperties()); output.send(new GenericMessage<>("foo".getBytes())); output.send(new GenericMessage<>("bar".getBytes())); Message<byte[]> in = (Message<byte[]>) input.receive(10000); assertThat(in).isNotNull(); assertThat(new String(in.getPayload())).isEqualTo("foo"); in = (Message<byte[]>) input.receive(10000); assertThat(in).isNotNull(); assertThat(new String(in.getPayload())).isEqualTo("bar"); assertThat(in.getHeaders().get(AmqpHeaders.DELIVERY_MODE)).isNull(); producerBinding.unbind(); consumerBinding.unbind(); }
From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderTests.java
@Test public void testLateBinding() throws Exception { RabbitTestSupport.RabbitProxy proxy = new RabbitTestSupport.RabbitProxy(); CachingConnectionFactory cf = new CachingConnectionFactory("localhost", proxy.getPort()); RabbitMessageChannelBinder rabbitBinder = new RabbitMessageChannelBinder(cf, new RabbitProperties(), new RabbitExchangeQueueProvisioner(cf)); RabbitTestBinder binder = new RabbitTestBinder(cf, rabbitBinder); ExtendedProducerProperties<RabbitProducerProperties> producerProperties = createProducerProperties(); producerProperties.getExtension().setPrefix("latebinder."); producerProperties.getExtension().setAutoBindDlq(true); MessageChannel moduleOutputChannel = createBindableChannel("output", createProducerBindingProperties(producerProperties)); Binding<MessageChannel> late0ProducerBinding = binder.bindProducer("late.0", moduleOutputChannel, producerProperties);// w ww.jav a 2 s. c o m QueueChannel moduleInputChannel = new QueueChannel(); ExtendedConsumerProperties<RabbitConsumerProperties> rabbitConsumerProperties = createConsumerProperties(); rabbitConsumerProperties.getExtension().setPrefix("latebinder."); Binding<MessageChannel> late0ConsumerBinding = binder.bindConsumer("late.0", "test", moduleInputChannel, rabbitConsumerProperties); producerProperties .setPartitionKeyExpression(spelExpressionParser.parseExpression("payload.equals('0') ? 0 : 1")); producerProperties.setPartitionSelectorExpression(spelExpressionParser.parseExpression("hashCode()")); producerProperties.setPartitionCount(2); MessageChannel partOutputChannel = createBindableChannel("output", createProducerBindingProperties(producerProperties)); Binding<MessageChannel> partlate0ProducerBinding = binder.bindProducer("partlate.0", partOutputChannel, producerProperties); QueueChannel partInputChannel0 = new QueueChannel(); QueueChannel partInputChannel1 = new QueueChannel(); ExtendedConsumerProperties<RabbitConsumerProperties> partLateConsumerProperties = createConsumerProperties(); partLateConsumerProperties.getExtension().setPrefix("latebinder."); partLateConsumerProperties.setPartitioned(true); partLateConsumerProperties.setInstanceIndex(0); Binding<MessageChannel> partlate0Consumer0Binding = binder.bindConsumer("partlate.0", "test", partInputChannel0, partLateConsumerProperties); partLateConsumerProperties.setInstanceIndex(1); Binding<MessageChannel> partlate0Consumer1Binding = binder.bindConsumer("partlate.0", "test", partInputChannel1, partLateConsumerProperties); ExtendedProducerProperties<RabbitProducerProperties> noDlqProducerProperties = createProducerProperties(); noDlqProducerProperties.getExtension().setPrefix("latebinder."); MessageChannel noDLQOutputChannel = createBindableChannel("output", createProducerBindingProperties(noDlqProducerProperties)); Binding<MessageChannel> noDlqProducerBinding = binder.bindProducer("lateNoDLQ.0", noDLQOutputChannel, noDlqProducerProperties); QueueChannel noDLQInputChannel = new QueueChannel(); ExtendedConsumerProperties<RabbitConsumerProperties> noDlqConsumerProperties = createConsumerProperties(); noDlqConsumerProperties.getExtension().setPrefix("latebinder."); Binding<MessageChannel> noDlqConsumerBinding = binder.bindConsumer("lateNoDLQ.0", "test", noDLQInputChannel, noDlqConsumerProperties); MessageChannel outputChannel = createBindableChannel("output", createProducerBindingProperties(noDlqProducerProperties)); Binding<MessageChannel> pubSubProducerBinding = binder.bindProducer("latePubSub", outputChannel, noDlqProducerProperties); QueueChannel pubSubInputChannel = new QueueChannel(); noDlqConsumerProperties.getExtension().setDurableSubscription(false); Binding<MessageChannel> nonDurableConsumerBinding = binder.bindConsumer("latePubSub", "lategroup", pubSubInputChannel, noDlqConsumerProperties); QueueChannel durablePubSubInputChannel = new QueueChannel(); noDlqConsumerProperties.getExtension().setDurableSubscription(true); Binding<MessageChannel> durableConsumerBinding = binder.bindConsumer("latePubSub", "lateDurableGroup", durablePubSubInputChannel, noDlqConsumerProperties); proxy.start(); moduleOutputChannel.send(new GenericMessage<>("foo")); Message<?> message = moduleInputChannel.receive(10000); assertThat(message).isNotNull(); assertThat(message.getPayload()).isNotNull(); noDLQOutputChannel.send(new GenericMessage<>("bar")); message = noDLQInputChannel.receive(10000); assertThat(message); assertThat(message.getPayload()).isEqualTo("bar"); outputChannel.send(new GenericMessage<>("baz")); message = pubSubInputChannel.receive(10000); assertThat(message); assertThat(message.getPayload()).isEqualTo("baz"); message = durablePubSubInputChannel.receive(10000); assertThat(message).isNotNull(); assertThat(message.getPayload()).isEqualTo("baz"); partOutputChannel.send(new GenericMessage<>("0")); partOutputChannel.send(new GenericMessage<>("1")); message = partInputChannel0.receive(10000); assertThat(message).isNotNull(); assertThat(message.getPayload()).isEqualTo("0"); message = partInputChannel1.receive(10000); assertThat(message).isNotNull(); assertThat(message.getPayload()).isEqualTo("1"); late0ProducerBinding.unbind(); late0ConsumerBinding.unbind(); partlate0ProducerBinding.unbind(); partlate0Consumer0Binding.unbind(); partlate0Consumer1Binding.unbind(); noDlqProducerBinding.unbind(); noDlqConsumerBinding.unbind(); pubSubProducerBinding.unbind(); nonDurableConsumerBinding.unbind(); durableConsumerBinding.unbind(); binder.cleanup(); proxy.stop(); cf.destroy(); this.rabbitAvailableRule.getResource().destroy(); }
From source file:org.springframework.cloud.stream.binder.test.integration.EndToEndIntegrationTests.java
private Iterable<?> extractPayload(Iterable<Message> messages) { List<Object> output = new ArrayList<>(); for (Message message : messages) { output.add(message.getPayload()); }//from ww w . jav a 2s . co m return output; }
From source file:org.springframework.cloud.stream.config.MessageChannelConfigurerTests.java
@Test public void testMessageConverterConfigurer() throws Exception { final CountDownLatch latch = new CountDownLatch(1); MessageHandler messageHandler = new MessageHandler() { @Override/*w w w .j a v a2 s . c om*/ public void handleMessage(Message<?> message) throws MessagingException { assertThat(message.getPayload()).isInstanceOf(Tuple.class); assertThat(((Tuple) message.getPayload()).getFieldNames().get(0)).isEqualTo("message"); assertThat(((Tuple) message.getPayload()).getValue(0)).isEqualTo("Hi"); latch.countDown(); } }; testSink.input().subscribe(messageHandler); testSink.input().send(MessageBuilder.withPayload("{\"message\":\"Hi\"}").build()); assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); testSink.input().unsubscribe(messageHandler); }
From source file:org.springframework.cloud.stream.converter.AbstractFromMessageConverter.java
@Override protected boolean canConvertFrom(Message<?> message, Class<?> targetClass) { return super.canConvertFrom(message, targetClass) && supportsPayloadType(message.getPayload().getClass()); }
From source file:org.springframework.cloud.stream.converter.JsonUnmarshallingConverter.java
@Override protected boolean canConvertFrom(Message<?> message, Class<?> targetClass) { if ((message.getPayload() instanceof String) || (message.getPayload() instanceof byte[])) { return true; }//from w w w . j a v a 2 s .c o m return canConvertFromBasedOnContentTypeHeader(message); }
From source file:org.springframework.cloud.stream.converter.JsonUnmarshallingConverter.java
@Override protected Object convertFromInternal(Message<?> message, Class<?> targetClass, Object conversionHint) { Object payload = message.getPayload(); try {/*from w ww . ja v a 2 s .c om*/ return payload instanceof byte[] ? objectMapper.readValue((byte[]) payload, targetClass) : objectMapper.readValue((String) payload, targetClass); } catch (IOException e) { throw new MessageConversionException("Cannot parse payload ", e); } }