List of usage examples for org.springframework.messaging Message getPayload
T getPayload();
From source file:org.springframework.integration.aggregator.BarrierMessageHandlerTests.java
@Test public void testRequestBeforeReply() throws Exception { final BarrierMessageHandler handler = new BarrierMessageHandler(10000); QueueChannel outputChannel = new QueueChannel(); handler.setOutputChannel(outputChannel); handler.setBeanFactory(mock(BeanFactory.class)); handler.afterPropertiesSet();// w w w . j av a 2 s. co m final AtomicReference<Exception> dupCorrelation = new AtomicReference<Exception>(); final CountDownLatch latch = new CountDownLatch(1); Runnable runnable = () -> { try { handler.handleMessage(MessageBuilder.withPayload("foo").setCorrelationId("foo").build()); } catch (MessagingException e) { dupCorrelation.set(e); } latch.countDown(); }; ExecutorService exec = Executors.newCachedThreadPool(); exec.execute(runnable); exec.execute(runnable); Map<?, ?> suspensions = TestUtils.getPropertyValue(handler, "suspensions", Map.class); int n = 0; while (n++ < 100 && suspensions.size() == 0) { Thread.sleep(100); } Map<?, ?> inProcess = TestUtils.getPropertyValue(handler, "inProcess", Map.class); assertEquals(1, inProcess.size()); assertTrue("suspension did not appear in time", n < 100); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertNotNull(dupCorrelation.get()); assertThat(dupCorrelation.get().getMessage(), startsWith("Correlation key (foo) is already in use by")); handler.trigger(MessageBuilder.withPayload("bar").setCorrelationId("foo").build()); Message<?> received = outputChannel.receive(10000); assertNotNull(received); List<?> result = (List<?>) received.getPayload(); assertEquals("foo", result.get(0)); assertEquals("bar", result.get(1)); assertEquals(0, suspensions.size()); assertEquals(0, inProcess.size()); }
From source file:org.springframework.integration.aggregator.BarrierMessageHandlerTests.java
@Test public void testReplyBeforeRequest() throws Exception { final BarrierMessageHandler handler = new BarrierMessageHandler(10000); QueueChannel outputChannel = new QueueChannel(); handler.setOutputChannel(outputChannel); handler.setBeanFactory(mock(BeanFactory.class)); handler.afterPropertiesSet();//w w w . j a va 2s . c o m Executors.newSingleThreadExecutor() .execute(() -> handler.trigger(MessageBuilder.withPayload("bar").setCorrelationId("foo").build())); Map<?, ?> suspensions = TestUtils.getPropertyValue(handler, "suspensions", Map.class); int n = 0; while (n++ < 100 && suspensions.size() == 0) { Thread.sleep(100); } assertTrue("suspension did not appear in time", n < 100); handler.handleMessage(MessageBuilder.withPayload("foo").setCorrelationId("foo").build()); Message<?> received = outputChannel.receive(10000); assertNotNull(received); List<?> result = (ArrayList<?>) received.getPayload(); assertEquals("foo", result.get(0)); assertEquals("bar", result.get(1)); assertEquals(0, suspensions.size()); }
From source file:org.springframework.integration.aggregator.BarrierMessageHandlerTests.java
@Test public void testJavaConfig() { Message<?> releasing = MessageBuilder.withPayload("bar").setCorrelationId("foo").build(); this.release.send(releasing); Message<?> suspending = MessageBuilder.withPayload("foo").setCorrelationId("foo").build(); this.in.send(suspending); Message<?> out = this.out.receive(10000); assertNotNull(out);// ww w. j a v a 2 s . c o m assertEquals("[foo, bar]", out.getPayload().toString()); Message<?> publisherMessage = this.publisherChannel.receive(10000); assertNotNull(publisherMessage); assertEquals("BAR", publisherMessage.getPayload()); }
From source file:org.springframework.integration.amqp.outbound.AsyncAmqpGatewayTests.java
@Test public void testConfirmsAndReturns() throws Exception { CachingConnectionFactory ccf = new CachingConnectionFactory("localhost"); ccf.setPublisherConfirms(true);/*w ww . ja v a 2 s . c o m*/ ccf.setPublisherReturns(true); RabbitTemplate template = new RabbitTemplate(ccf); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(ccf); container.setBeanName("replyContainer"); container.setQueueNames("asyncRQ1"); container.afterPropertiesSet(); container.start(); AsyncRabbitTemplate asyncTemplate = new AsyncRabbitTemplate(template, container); asyncTemplate.setEnableConfirms(true); asyncTemplate.setMandatory(true); SimpleMessageListenerContainer receiver = new SimpleMessageListenerContainer(ccf); receiver.setBeanName("receiver"); receiver.setQueueNames("asyncQ1"); final CountDownLatch waitForAckBeforeReplying = new CountDownLatch(1); MessageListenerAdapter messageListener = new MessageListenerAdapter( (ReplyingMessageListener<String, String>) foo -> { try { waitForAckBeforeReplying.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return foo.toUpperCase(); }); receiver.setMessageListener(messageListener); receiver.afterPropertiesSet(); receiver.start(); AsyncAmqpOutboundGateway gateway = new AsyncAmqpOutboundGateway(asyncTemplate); Log logger = spy(TestUtils.getPropertyValue(gateway, "logger", Log.class)); given(logger.isDebugEnabled()).willReturn(true); final CountDownLatch replyTimeoutLatch = new CountDownLatch(1); willAnswer(invocation -> { invocation.callRealMethod(); replyTimeoutLatch.countDown(); return null; }).given(logger).debug(startsWith("Reply not required and async timeout for")); new DirectFieldAccessor(gateway).setPropertyValue("logger", logger); QueueChannel outputChannel = new QueueChannel(); outputChannel.setBeanName("output"); QueueChannel returnChannel = new QueueChannel(); returnChannel.setBeanName("returns"); QueueChannel ackChannel = new QueueChannel(); ackChannel.setBeanName("acks"); QueueChannel errorChannel = new QueueChannel(); errorChannel.setBeanName("errors"); gateway.setOutputChannel(outputChannel); gateway.setReturnChannel(returnChannel); gateway.setConfirmAckChannel(ackChannel); gateway.setConfirmNackChannel(ackChannel); gateway.setConfirmCorrelationExpressionString("#this"); gateway.setExchangeName(""); gateway.setRoutingKey("asyncQ1"); gateway.setBeanFactory(mock(BeanFactory.class)); gateway.afterPropertiesSet(); gateway.start(); Message<?> message = MessageBuilder.withPayload("foo").setErrorChannel(errorChannel).build(); gateway.handleMessage(message); Message<?> ack = ackChannel.receive(10000); assertNotNull(ack); assertEquals("foo", ack.getPayload()); assertEquals(true, ack.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM)); waitForAckBeforeReplying.countDown(); Message<?> received = outputChannel.receive(10000); assertNotNull(received); assertEquals("FOO", received.getPayload()); // timeout tests asyncTemplate.setReceiveTimeout(10); receiver.setMessageListener(message1 -> { }); // reply timeout with no requiresReply message = MessageBuilder.withPayload("bar").setErrorChannel(errorChannel).build(); gateway.handleMessage(message); assertTrue(replyTimeoutLatch.await(10, TimeUnit.SECONDS)); // reply timeout with requiresReply gateway.setRequiresReply(true); message = MessageBuilder.withPayload("baz").setErrorChannel(errorChannel).build(); gateway.handleMessage(message); received = errorChannel.receive(10000); assertThat(received, instanceOf(ErrorMessage.class)); ErrorMessage error = (ErrorMessage) received; assertThat(error.getPayload(), instanceOf(MessagingException.class)); assertThat(error.getPayload().getCause(), instanceOf(AmqpReplyTimeoutException.class)); asyncTemplate.setReceiveTimeout(30000); receiver.setMessageListener(messageListener); // error on sending result DirectChannel errorForce = new DirectChannel(); errorForce.setBeanName("errorForce"); errorForce.subscribe(message1 -> { throw new RuntimeException("intentional"); }); gateway.setOutputChannel(errorForce); message = MessageBuilder.withPayload("qux").setErrorChannel(errorChannel).build(); gateway.handleMessage(message); received = errorChannel.receive(10000); assertThat(received, instanceOf(ErrorMessage.class)); error = (ErrorMessage) received; assertThat(error.getPayload(), instanceOf(MessagingException.class)); assertEquals("QUX", ((MessagingException) error.getPayload()).getFailedMessage().getPayload()); gateway.setRoutingKey(UUID.randomUUID().toString()); message = MessageBuilder.withPayload("fiz").setErrorChannel(errorChannel).build(); gateway.handleMessage(message); Message<?> returned = returnChannel.receive(10000); assertNotNull(returned); assertEquals("fiz", returned.getPayload()); ackChannel.receive(10000); ackChannel.purge(null); asyncTemplate = mock(AsyncRabbitTemplate.class); RabbitMessageFuture future = asyncTemplate.new RabbitMessageFuture(null, null); willReturn(future).given(asyncTemplate).sendAndReceive(anyString(), anyString(), any(org.springframework.amqp.core.Message.class)); DirectFieldAccessor dfa = new DirectFieldAccessor(future); dfa.setPropertyValue("nackCause", "nacknack"); SettableListenableFuture<Boolean> confirmFuture = new SettableListenableFuture<Boolean>(); confirmFuture.set(false); dfa.setPropertyValue("confirm", confirmFuture); new DirectFieldAccessor(gateway).setPropertyValue("template", asyncTemplate); message = MessageBuilder.withPayload("buz").setErrorChannel(errorChannel).build(); gateway.handleMessage(message); ack = ackChannel.receive(10000); assertNotNull(ack); assertEquals("buz", ack.getPayload()); assertEquals("nacknack", ack.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM_NACK_CAUSE)); assertEquals(false, ack.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM)); asyncTemplate.stop(); receiver.stop(); ccf.destroy(); }
From source file:org.springframework.integration.aws.inbound.S3InboundStreamingChannelAdapterTests.java
@Test public void testS3InboundStreamingChannelAdapter() throws IOException { Message<?> message = this.s3FilesChannel.receive(10000); assertThat(message).isNotNull();//from w ww . j a v a 2s .com assertThat(message.getPayload()).isInstanceOf(InputStream.class); assertThat(message.getHeaders().get(FileHeaders.REMOTE_FILE)).isEqualTo("subdir/a.test"); InputStream inputStreamA = (InputStream) message.getPayload(); assertThat(inputStreamA).isNotNull(); assertThat(IOUtils.toString(inputStreamA)).isEqualTo("Hello"); message = this.s3FilesChannel.receive(10000); assertThat(message).isNotNull(); assertThat(message.getPayload()).isInstanceOf(InputStream.class); assertThat(message.getHeaders().get(FileHeaders.REMOTE_FILE)).isEqualTo("subdir/b.test"); InputStream inputStreamB = (InputStream) message.getPayload(); assertThat(IOUtils.toString(inputStreamB)).isEqualTo("Bye"); assertThat(this.s3FilesChannel.receive(10)).isNull(); }
From source file:org.springframework.integration.aws.inbound.SnsInboundChannelAdapter.java
@Override @SuppressWarnings("unchecked") protected void send(Object object) { Message<?> message = (Message<?>) object; Map<String, String> payload = (HashMap<String, String>) message.getPayload(); AbstractIntegrationMessageBuilder<?> messageToSendBuilder; if (this.payloadExpression != null) { messageToSendBuilder = getMessageBuilderFactory() .withPayload(this.payloadExpression.getValue(this.evaluationContext, message)) .copyHeaders(message.getHeaders()); } else {/*from w w w . j a va 2 s.c om*/ messageToSendBuilder = getMessageBuilderFactory().fromMessage(message); } String type = payload.get("Type"); if ("SubscriptionConfirmation".equals(type) || "UnsubscribeConfirmation".equals(type)) { JsonNode content = this.jackson2HttpMessageConverter.getObjectMapper().valueToTree(payload); NotificationStatus notificationStatus = this.notificationStatusResolver .resolveNotificationStatus(content); if (this.handleNotificationStatus) { messageToSendBuilder.setHeader(AwsHeaders.NOTIFICATION_STATUS, notificationStatus); } else { if ("SubscriptionConfirmation".equals(type)) { notificationStatus.confirmSubscription(); } return; } } messageToSendBuilder.setHeader(AwsHeaders.SNS_MESSAGE_TYPE, type).setHeader(AwsHeaders.MESSAGE_ID, payload.get("MessageId")); super.send(messageToSendBuilder.build()); }
From source file:org.springframework.integration.aws.outbound.S3MessageHandlerTests.java
@Test public void testCopy() throws InterruptedException { Map<String, String> payload = new HashMap<>(); payload.put("key", "mySource"); payload.put("destination", "theirBucket"); payload.put("destinationKey", "theirTarget"); this.s3ProcessChannel.send(new GenericMessage<>(payload)); Message<?> receive = this.s3ReplyChannel.receive(10000); assertThat(receive).isNotNull();// www.jav a 2s.co m assertThat(receive.getPayload()).isInstanceOf(Copy.class); Copy copy = (Copy) receive.getPayload(); assertThat(copy.getDescription()) .isEqualTo("Copying object from myBucket/mySource to theirBucket/theirTarget"); copy.waitForCompletion(); assertThat(copy.getState()).isEqualTo(Transfer.TransferState.Completed); }
From source file:org.springframework.integration.cassandra.outbound.CassandraStoringMessageHandler.java
@Override protected void handleMessageInternal(Message<?> message) throws Exception { Object payload = message.getPayload(); if (highThroughputIngest) { handleHighThroughputIngest(payload); } else if (async) { handleAsyncInsert(payload);/*from w ww . ja v a 2s . c o m*/ } else { handleSynchronousInsert(message, payload); } }
From source file:org.springframework.integration.cassandra.outbound.CassandraStoringMessageHandler.java
private void handleSynchronousInsert(Message<?> message, Object payload) { if (payload instanceof List) { @SuppressWarnings("unchecked") List<T> entities = (List<T>) payload; cassandraTemplate.insert(entities, writeOptions); } else {//from w ww . j av a 2s . c o m cassandraTemplate.insert(message.getPayload(), writeOptions); } }
From source file:org.springframework.integration.config.SourcePollingChannelAdapterFactoryBeanTests.java
@Test public void testAdviceChain() throws Exception { SourcePollingChannelAdapterFactoryBean factoryBean = new SourcePollingChannelAdapterFactoryBean(); QueueChannel outputChannel = new QueueChannel(); TestApplicationContext context = TestUtils.createTestApplicationContext(); factoryBean.setBeanFactory(context.getBeanFactory()); factoryBean.setBeanClassLoader(ClassUtils.getDefaultClassLoader()); factoryBean.setOutputChannel(outputChannel); factoryBean.setSource(() -> new GenericMessage<>("test")); PollerMetadata pollerMetadata = new PollerMetadata(); List<Advice> adviceChain = new ArrayList<Advice>(); final AtomicBoolean adviceApplied = new AtomicBoolean(false); adviceChain.add((MethodInterceptor) invocation -> { adviceApplied.set(true);//from w w w. ja v a 2 s .com return invocation.proceed(); }); pollerMetadata.setTrigger(new PeriodicTrigger(5000)); pollerMetadata.setMaxMessagesPerPoll(1); pollerMetadata.setAdviceChain(adviceChain); factoryBean.setPollerMetadata(pollerMetadata); factoryBean.setAutoStartup(true); factoryBean.afterPropertiesSet(); context.registerEndpoint("testPollingEndpoint", factoryBean.getObject()); context.refresh(); Message<?> message = outputChannel.receive(5000); assertEquals("test", message.getPayload()); assertTrue("adviceChain was not applied", adviceApplied.get()); }