List of usage examples for org.springframework.integration.channel QueueChannel QueueChannel
public QueueChannel()
From source file:org.springframework.integration.amqp.outbound.AsyncAmqpGatewayTests.java
@Test public void testConfirmsAndReturns() throws Exception { CachingConnectionFactory ccf = new CachingConnectionFactory("localhost"); ccf.setPublisherConfirms(true);// ww w .j a va2s. 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.channel.QueueChannelTests.java
@Test public void testSimpleSendAndReceive() throws Exception { final AtomicBoolean messageReceived = new AtomicBoolean(false); final CountDownLatch latch = new CountDownLatch(1); final QueueChannel channel = new QueueChannel(); Log logger = spy(TestUtils.getPropertyValue(channel, "logger", Log.class)); when(logger.isDebugEnabled()).thenReturn(true); when(logger.isTraceEnabled()).thenReturn(true); new DirectFieldAccessor(channel).setPropertyValue("logger", logger); new Thread(new Runnable() { @Override/*from ww w. j ava 2 s.c om*/ public void run() { Message<?> message = channel.receive(); if (message != null) { messageReceived.set(true); latch.countDown(); } } }).start(); assertFalse(messageReceived.get()); channel.send(new GenericMessage<String>("testing")); latch.await(1000, TimeUnit.MILLISECONDS); assertTrue(messageReceived.get()); ArgumentCaptor<String> preCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<String> postCaptor = ArgumentCaptor.forClass(String.class); verify(logger).trace(preCaptor.capture()); verify(logger, times(3)).debug(postCaptor.capture()); assertThat(preCaptor.getValue(), startsWith("preReceive")); assertThat(postCaptor.getValue(), startsWith("postReceive")); }
From source file:org.springframework.integration.channel.QueueChannelTests.java
@Test public void testImmediateReceive() throws Exception { final AtomicBoolean messageReceived = new AtomicBoolean(false); final QueueChannel channel = new QueueChannel(); final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); Executor singleThreadExecutor = Executors.newSingleThreadExecutor(); Runnable receiveTask1 = new Runnable() { @Override/*from w ww . ja v a2 s. c om*/ public void run() { Message<?> message = channel.receive(0); if (message != null) { messageReceived.set(true); } latch1.countDown(); } }; Runnable sendTask = new Runnable() { @Override public void run() { channel.send(new GenericMessage<String>("testing")); } }; singleThreadExecutor.execute(receiveTask1); latch1.await(); singleThreadExecutor.execute(sendTask); assertFalse(messageReceived.get()); Runnable receiveTask2 = new Runnable() { @Override public void run() { Message<?> message = channel.receive(0); if (message != null) { messageReceived.set(true); } latch2.countDown(); } }; singleThreadExecutor.execute(receiveTask2); latch2.await(); assertTrue(messageReceived.get()); }
From source file:org.springframework.integration.channel.QueueChannelTests.java
@Test public void testBlockingReceiveWithNoTimeout() throws Exception { final QueueChannel channel = new QueueChannel(); final AtomicBoolean receiveInterrupted = new AtomicBoolean(false); final CountDownLatch latch = new CountDownLatch(1); Thread t = new Thread(new Runnable() { @Override//w w w . j a v a 2 s.com public void run() { Message<?> message = channel.receive(); receiveInterrupted.set(true); assertTrue(message == null); latch.countDown(); } }); t.start(); assertFalse(receiveInterrupted.get()); t.interrupt(); latch.await(); assertTrue(receiveInterrupted.get()); }
From source file:org.springframework.integration.channel.QueueChannelTests.java
@Test public void testBlockingReceiveWithTimeout() throws Exception { final QueueChannel channel = new QueueChannel(); final AtomicBoolean receiveInterrupted = new AtomicBoolean(false); final CountDownLatch latch = new CountDownLatch(1); Thread t = new Thread(new Runnable() { @Override/* ww w .j a va2 s. c o m*/ public void run() { Message<?> message = channel.receive(10000); receiveInterrupted.set(true); assertTrue(message == null); latch.countDown(); } }); t.start(); assertFalse(receiveInterrupted.get()); t.interrupt(); latch.await(); assertTrue(receiveInterrupted.get()); }
From source file:org.springframework.integration.channel.QueueChannelTests.java
@Test public void testClearEmptyChannel() { QueueChannel channel = new QueueChannel(); List<Message<?>> clearedMessages = channel.clear(); assertNotNull(clearedMessages);/*from ww w . ja v a 2s . co m*/ assertEquals(0, clearedMessages.size()); }
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 www .ja v a2 s. c o m 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()); }
From source file:org.springframework.integration.config.SourcePollingChannelAdapterFactoryBeanTests.java
@Test public void testTransactionalAdviceChain() throws Throwable { 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);/* w w w .j av a2 s. c o m*/ return invocation.proceed(); }); pollerMetadata.setTrigger(new PeriodicTrigger(5000)); pollerMetadata.setMaxMessagesPerPoll(1); final AtomicInteger count = new AtomicInteger(); final MethodInterceptor txAdvice = mock(MethodInterceptor.class); adviceChain.add((MethodInterceptor) invocation -> { count.incrementAndGet(); return invocation.proceed(); }); when(txAdvice.invoke(any(MethodInvocation.class))).thenAnswer(invocation -> { count.incrementAndGet(); return ((MethodInvocation) invocation.getArgument(0)).proceed(); }); 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()); assertEquals(1, count.get()); assertTrue("adviceChain was not applied", adviceApplied.get()); }
From source file:org.springframework.integration.config.SourcePollingChannelAdapterFactoryBeanTests.java
@Test public void testStartSourceBeforeRunPollingTask() { TaskScheduler taskScheduler = mock(TaskScheduler.class); willAnswer(invocation -> {//w w w .j a v a 2s . com Runnable task = invocation.getArgument(0); task.run(); return null; }).given(taskScheduler).schedule(any(Runnable.class), any(Trigger.class)); SourcePollingChannelAdapter pollingChannelAdapter = new SourcePollingChannelAdapter(); pollingChannelAdapter.setTaskScheduler(taskScheduler); pollingChannelAdapter.setSource(new LifecycleMessageSource()); pollingChannelAdapter.setMaxMessagesPerPoll(1); QueueChannel outputChannel = new QueueChannel(); pollingChannelAdapter.setOutputChannel(outputChannel); pollingChannelAdapter.setBeanFactory(mock(BeanFactory.class)); pollingChannelAdapter.afterPropertiesSet(); pollingChannelAdapter.start(); Message<?> receive = outputChannel.receive(10_000); assertNotNull(receive); assertEquals(true, receive.getPayload()); pollingChannelAdapter.stop(); }
From source file:org.springframework.integration.configuration.EnableIntegrationTests.java
@Test public void testBridgeAnnotations() { GenericMessage<?> testMessage = new GenericMessage<Object>("foo"); this.bridgeInput.send(testMessage); Message<?> receive = this.bridgeOutput.receive(2000); assertNotNull(receive);/*from w ww . j a v a2 s .c o m*/ assertSame(receive, testMessage); assertNull(this.bridgeOutput.receive(10)); this.pollableBridgeInput.send(testMessage); receive = this.pollableBridgeOutput.receive(2000); assertNotNull(receive); assertSame(receive, testMessage); assertNull(this.pollableBridgeOutput.receive(10)); try { this.metaBridgeInput.send(testMessage); fail("MessageDeliveryException expected"); } catch (Exception e) { assertThat(e, Matchers.instanceOf(MessageDeliveryException.class)); assertThat(e.getMessage(), Matchers.containsString("Dispatcher has no subscribers")); } this.context .getBean("enableIntegrationTests.ContextConfiguration.metaBridgeOutput.bridgeFrom", Lifecycle.class) .start(); this.metaBridgeInput.send(testMessage); receive = this.metaBridgeOutput.receive(2000); assertNotNull(receive); assertSame(receive, testMessage); assertNull(this.metaBridgeOutput.receive(10)); this.bridgeToInput.send(testMessage); receive = this.bridgeToOutput.receive(2000); assertNotNull(receive); assertSame(receive, testMessage); assertNull(this.bridgeToOutput.receive(10)); PollableChannel replyChannel = new QueueChannel(); Message<?> bridgeMessage = MessageBuilder.fromMessage(testMessage).setReplyChannel(replyChannel).build(); this.pollableBridgeToInput.send(bridgeMessage); receive = replyChannel.receive(2000); assertNotNull(receive); assertSame(receive, bridgeMessage); assertNull(replyChannel.receive(10)); try { this.myBridgeToInput.send(testMessage); fail("MessageDeliveryException expected"); } catch (Exception e) { assertThat(e, Matchers.instanceOf(MessageDeliveryException.class)); assertThat(e.getMessage(), Matchers.containsString("Dispatcher has no subscribers")); } this.context .getBean("enableIntegrationTests.ContextConfiguration.myBridgeToInput.bridgeTo", Lifecycle.class) .start(); this.myBridgeToInput.send(bridgeMessage); receive = replyChannel.receive(2000); assertNotNull(receive); assertSame(receive, bridgeMessage); assertNull(replyChannel.receive(10)); }