@Test public void testParseWithQueues() throws Exception { SimpleMessageListenerContainer container = beanFactory.getBean("container2", SimpleMessageListenerContainer.class); Queue queue = beanFactory.getBean("bar", Queue.class); assertEquals( "[foo, " + queue.getName() + "]", Arrays.asList(container.getQueueNames()).toString()); assertTrue(TestUtils.getPropertyValue(container, "missingQueuesFatal", Boolean.class)); assertFalse(TestUtils.getPropertyValue(container, "autoDeclare", Boolean.class)); }
private void verifyFooRequestProducer(AbstractEndpoint endpoint) { List<?> requestMatchers = TestUtils.getPropertyValue( endpoint, "handler.delegate.headerMapper.requestHeaderMatcher.strategies", List.class); assertEquals(1, requestMatchers.size()); assertEquals( "foo", TestUtils.getPropertyValue(requestMatchers.get(0), "patterns", Collection.class) .iterator() .next()); }
private void verifyBarReplyConsumer(AbstractEndpoint endpoint) { List<?> replyMatchers; replyMatchers = TestUtils.getPropertyValue( endpoint, "headerMapper.replyHeaderMatcher.strategies", List.class); assertEquals(1, replyMatchers.size()); assertEquals( "bar", TestUtils.getPropertyValue(replyMatchers.get(0), "patterns", Collection.class) .iterator() .next()); }
@Test public void testPublisherConfirmReceived() throws Exception { final CountDownLatch latch = new CountDownLatch(10000); final AtomicInteger acks = new AtomicInteger(); templateWithConfirmsEnabled.setConfirmCallback( new ConfirmCallback() { @Override public void confirm(CorrelationData correlationData, boolean ack, String cause) { acks.incrementAndGet(); latch.countDown(); } }); ExecutorService exec = Executors.newCachedThreadPool(); for (int i = 0; i < 100; i++) { exec.submit( new Runnable() { @Override public void run() { try { for (int i = 0; i < 100; i++) { templateWithConfirmsEnabled.convertAndSend( ROUTE, (Object) "message", new CorrelationData("abc")); } } catch (Throwable t) { t.printStackTrace(); } } }); } exec.shutdown(); assertTrue(exec.awaitTermination(300, TimeUnit.SECONDS)); assertTrue("" + latch.getCount(), latch.await(60, TimeUnit.SECONDS)); assertNull(templateWithConfirmsEnabled.getUnconfirmed(-1)); this.templateWithConfirmsEnabled.execute( new ChannelCallback<Void>() { @Override public Void doInRabbit(Channel channel) throws Exception { Map<?, ?> listenerMap = TestUtils.getPropertyValue( ((ChannelProxy) channel).getTargetChannel(), "listenerForSeq", Map.class); int n = 0; while (n++ < 100 && listenerMap.size() > 0) { Thread.sleep(100); } assertEquals(0, listenerMap.size()); return null; } }); Log logger = spy(TestUtils.getPropertyValue(connectionFactoryWithConfirmsEnabled, "logger", Log.class)); new DirectFieldAccessor(connectionFactoryWithConfirmsEnabled) .setPropertyValue("logger", logger); cleanUp(); verify(logger, never()).error(any()); }
@Test public void testParseWithAdviceChain() throws Exception { SimpleMessageListenerContainer container = beanFactory.getBean("container3", SimpleMessageListenerContainer.class); Object adviceChain = ReflectionTestUtils.getField(container, "adviceChain"); assertNotNull(adviceChain); assertEquals(3, ((Advice[]) adviceChain).length); assertTrue(TestUtils.getPropertyValue(container, "exclusive", Boolean.class)); }
@Test public void testParseWithQueueNames() throws Exception { SimpleMessageListenerContainer container = beanFactory.getBean("container1", SimpleMessageListenerContainer.class); assertEquals(AcknowledgeMode.MANUAL, container.getAcknowledgeMode()); assertEquals(beanFactory.getBean(ConnectionFactory.class), container.getConnectionFactory()); assertEquals(MessageListenerAdapter.class, container.getMessageListener().getClass()); DirectFieldAccessor listenerAccessor = new DirectFieldAccessor(container.getMessageListener()); assertEquals( beanFactory.getBean(TestBean.class), listenerAccessor.getPropertyValue("delegate")); assertEquals("handle", listenerAccessor.getPropertyValue("defaultListenerMethod")); Queue queue = beanFactory.getBean("bar", Queue.class); assertEquals( "[foo, " + queue.getName() + "]", Arrays.asList(container.getQueueNames()).toString()); assertEquals(5, ReflectionTestUtils.getField(container, "concurrentConsumers")); assertEquals(6, ReflectionTestUtils.getField(container, "maxConcurrentConsumers")); assertEquals(1234L, ReflectionTestUtils.getField(container, "startConsumerMinInterval")); assertEquals(2345L, ReflectionTestUtils.getField(container, "stopConsumerMinInterval")); assertEquals(12, ReflectionTestUtils.getField(container, "consecutiveActiveTrigger")); assertEquals(34, ReflectionTestUtils.getField(container, "consecutiveIdleTrigger")); assertEquals(9876L, ReflectionTestUtils.getField(container, "receiveTimeout")); Map<?, ?> consumerArgs = TestUtils.getPropertyValue(container, "consumerArgs", Map.class); assertEquals(1, consumerArgs.size()); Object xPriority = consumerArgs.get("x-priority"); assertNotNull(xPriority); assertEquals(10, xPriority); assertEquals( Long.valueOf(5555), TestUtils.getPropertyValue(container, "recoveryBackOff.interval", Long.class)); assertFalse(TestUtils.getPropertyValue(container, "exclusive", Boolean.class)); assertFalse(TestUtils.getPropertyValue(container, "missingQueuesFatal", Boolean.class)); assertTrue(TestUtils.getPropertyValue(container, "autoDeclare", Boolean.class)); assertEquals(5, TestUtils.getPropertyValue(container, "declarationRetries")); assertEquals(1000L, TestUtils.getPropertyValue(container, "failedDeclarationRetryInterval")); assertEquals(30000L, TestUtils.getPropertyValue(container, "retryDeclarationInterval")); assertEquals( beanFactory.getBean("tagger"), TestUtils.getPropertyValue(container, "consumerTagStrategy")); Collection<?> group = beanFactory.getBean("containerGroup", Collection.class); assertEquals(3, group.size()); assertThat( group, Matchers.contains( beanFactory.getBean("container1"), beanFactory.getBean("testListener1"), beanFactory.getBean("testListener2"))); assertEquals(1235L, ReflectionTestUtils.getField(container, "idleEventInterval")); assertEquals("container1", container.getListenerId()); }
@After public void closeBeanFactory() throws Exception { if (this.context != null) { CachingConnectionFactory cf = this.context.getBean(CachingConnectionFactory.class); this.context.close(); assertTrue( TestUtils.getPropertyValue(cf, "deferredCloseExecutor", ThreadPoolExecutor.class) .isTerminated()); } }
@Override protected void verifyDynamicProperties(MessageBus bus, String type) { @SuppressWarnings("unchecked") List<Binding> bindings = TestUtils.getPropertyValue(bus, "messageBus.bindings", List.class); for (Binding binding : bindings) { if (binding.getEndpoint().getComponentName().equals("outbound." + type + ":x")) { assertEquals( MessageDeliveryMode.PERSISTENT, TestUtils.getPropertyValue( binding.getEndpoint(), "handler.delegate.defaultDeliveryMode", MessageDeliveryMode.class)); } else if (binding.getEndpoint().getComponentName().matches("outbound." + type + ":(y|z)")) { assertEquals( MessageDeliveryMode.NON_PERSISTENT, TestUtils.getPropertyValue( binding.getEndpoint(), "handler.delegate.defaultDeliveryMode", MessageDeliveryMode.class)); } } }
@Test public void addCustomConverter() { List<?> customMessageConverters = context.getBean("customMessageConverters", List.class); assertEquals(1, customMessageConverters.size()); ModuleTypeConversionPlugin plugin = context.getBean(ModuleTypeConversionPlugin.class); CompositeMessageConverterFactory factory = (CompositeMessageConverterFactory) TestUtils.getPropertyValue(plugin, "converterFactory"); CompositeMessageConverter converters = factory.newInstance(MimeType.valueOf("application/x-xd-foo")); assertEquals(1, converters.getConverters().size()); assertTrue(converters.getConverters().iterator().next() instanceof StubPojoToStringConverter); }
@Test public void testNackForBadExchange() throws Exception { final AtomicBoolean nack = new AtomicBoolean(true); final AtomicReference<CorrelationData> correlation = new AtomicReference<CorrelationData>(); final AtomicReference<String> reason = new AtomicReference<String>(); final CountDownLatch latch = new CountDownLatch(2); this.templateWithConfirmsEnabled.setConfirmCallback( new ConfirmCallback() { @Override public void confirm(CorrelationData correlationData, boolean ack, String cause) { nack.set(ack); correlation.set(correlationData); reason.set(cause); latch.countDown(); } }); Log logger = spy(TestUtils.getPropertyValue(connectionFactoryWithConfirmsEnabled, "logger", Log.class)); new DirectFieldAccessor(connectionFactoryWithConfirmsEnabled) .setPropertyValue("logger", logger); final AtomicReference<String> log = new AtomicReference<String>(); doAnswer( new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { log.set((String) invocation.getArguments()[0]); invocation.callRealMethod(); latch.countDown(); return null; } }) .when(logger) .error(any()); CorrelationData correlationData = new CorrelationData("bar"); String exchange = UUID.randomUUID().toString(); this.templateWithConfirmsEnabled.convertAndSend(exchange, "key", "foo", correlationData); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertFalse(nack.get()); assertEquals(correlationData.toString(), correlation.get().toString()); assertThat(reason.get(), containsString("NOT_FOUND - no exchange '" + exchange)); assertThat(log.get(), containsString("NOT_FOUND - no exchange '" + exchange)); }
@Override protected String getPubSubEndpointRouting(AbstractEndpoint endpoint) { return TestUtils.getPropertyValue( endpoint, "handler.delegate.exchangeNameExpression", SpelExpression.class) .getExpressionString(); }
private SimpleMessageListenerContainer verifyContainer(AbstractEndpoint endpoint) { SimpleMessageListenerContainer container; Advice retry; container = TestUtils.getPropertyValue( endpoint, "messageListenerContainer", SimpleMessageListenerContainer.class); assertEquals(AcknowledgeMode.NONE, container.getAcknowledgeMode()); assertThat(container.getQueueNames()[0], startsWith("foo.props.0")); assertFalse(TestUtils.getPropertyValue(container, "transactional", Boolean.class)); assertEquals(2, TestUtils.getPropertyValue(container, "concurrentConsumers")); assertEquals(3, TestUtils.getPropertyValue(container, "maxConcurrentConsumers")); assertFalse(TestUtils.getPropertyValue(container, "defaultRequeueRejected", Boolean.class)); assertEquals(20, TestUtils.getPropertyValue(container, "prefetchCount")); assertEquals(10, TestUtils.getPropertyValue(container, "txSize")); retry = TestUtils.getPropertyValue(container, "adviceChain", Advice[].class)[0]; assertEquals(23, TestUtils.getPropertyValue(retry, "retryOperations.retryPolicy.maxAttempts")); assertEquals( 2000L, TestUtils.getPropertyValue(retry, "retryOperations.backOffPolicy.initialInterval")); assertEquals( 20000L, TestUtils.getPropertyValue(retry, "retryOperations.backOffPolicy.maxInterval")); assertEquals( 5.0, TestUtils.getPropertyValue(retry, "retryOperations.backOffPolicy.multiplier")); List<?> requestMatchers = TestUtils.getPropertyValue( endpoint, "headerMapper.requestHeaderMatcher.strategies", List.class); assertEquals(1, requestMatchers.size()); assertEquals( "foo", TestUtils.getPropertyValue(requestMatchers.get(0), "patterns", Collection.class) .iterator() .next()); return container; }
@SuppressWarnings("unchecked") @Test public void testBatchingAndCompression() throws Exception { RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource()); MessageBus bus = getMessageBus(); Properties properties = new Properties(); properties.put("deliveryMode", "NON_PERSISTENT"); properties.put("batchingEnabled", "true"); properties.put("batchSize", "2"); properties.put("batchBufferLimit", "100000"); properties.put("batchTimeout", "30000"); properties.put("compress", "true"); DirectChannel output = new DirectChannel(); output.setBeanName("batchingProducer"); bus.bindProducer("batching.0", output, properties); while (template.receive("xdbus.batching.0") != null) {} Log logger = spy( TestUtils.getPropertyValue( bus, "messageBus.compressingPostProcessor.logger", Log.class)); new DirectFieldAccessor(TestUtils.getPropertyValue(bus, "messageBus.compressingPostProcessor")) .setPropertyValue("logger", logger); when(logger.isTraceEnabled()).thenReturn(true); assertEquals( Deflater.BEST_SPEED, TestUtils.getPropertyValue(bus, "messageBus.compressingPostProcessor.level")); output.send(new GenericMessage<>("foo".getBytes())); output.send(new GenericMessage<>("bar".getBytes())); Object out = spyOn("batching.0").receive(false); assertThat(out, instanceOf(byte[].class)); assertEquals( "\u0000\u0000\u0000\u0003foo\u0000\u0000\u0000\u0003bar", new String((byte[]) out)); ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class); verify(logger).trace(captor.capture()); assertThat(captor.getValue().toString(), containsString("Compressed 14 to ")); QueueChannel input = new QueueChannel(); input.setBeanName("batchingConsumer"); bus.bindConsumer("batching.0", input, null); output.send(new GenericMessage<>("foo".getBytes())); output.send(new GenericMessage<>("bar".getBytes())); Message<byte[]> in = (Message<byte[]>) input.receive(10000); assertNotNull(in); assertEquals("foo", new String(in.getPayload())); in = (Message<byte[]>) input.receive(10000); assertNotNull(in); assertEquals("bar", new String(in.getPayload())); assertNull(in.getHeaders().get(AmqpHeaders.DELIVERY_MODE)); bus.unbindProducers("batching.0"); bus.unbindConsumers("batching.0"); }
@Test public void testRequestReplyReplierProperties() throws Exception { MessageBus bus = getMessageBus(); Properties properties = new Properties(); properties.put("prefix", "foo."); properties.put("deliveryMode", "NON_PERSISTENT"); properties.put("requestHeaderPatterns", "foo"); properties.put("replyHeaderPatterns", "bar"); properties.put("ackMode", "NONE"); properties.put("backOffInitialInterval", "2000"); properties.put("backOffMaxInterval", "20000"); properties.put("backOffMultiplier", "5.0"); properties.put("concurrency", "2"); properties.put("maxAttempts", "23"); properties.put("maxConcurrency", "3"); properties.put("prefix", "foo."); properties.put("prefetch", "20"); properties.put("requeue", "false"); properties.put("txSize", "10"); bus.bindReplier("props.0", new DirectChannel(), new DirectChannel(), properties); @SuppressWarnings("unchecked") List<Binding> bindings = TestUtils.getPropertyValue(bus, "messageBus.bindings", List.class); assertEquals(2, bindings.size()); AbstractEndpoint endpoint = bindings.get(1).getEndpoint(); // producer assertEquals( "headers['amqp_replyTo']", TestUtils.getPropertyValue( endpoint, "handler.delegate.routingKeyExpression", SpelExpression.class) .getExpressionString()); MessageDeliveryMode mode = TestUtils.getPropertyValue( endpoint, "handler.delegate.defaultDeliveryMode", MessageDeliveryMode.class); assertEquals(MessageDeliveryMode.NON_PERSISTENT, mode); verifyFooRequestBarReplyProducer(endpoint); endpoint = bindings.get(0).getEndpoint(); // consumer verifyContainer(endpoint); verifyBarReplyConsumer(endpoint); properties.put("partitionKeyExpression", "'foo'"); properties.put("partitionKeyExtractorClass", "foo"); properties.put("partitionSelectorExpression", "0"); properties.put("partitionSelectorClass", "foo"); properties.put(BusProperties.NEXT_MODULE_COUNT, "1"); properties.put("partitionIndex", "0"); try { bus.bindReplier("dummy", null, null, properties); fail("Expected exception"); } catch (IllegalArgumentException e) { assertThat( e.getMessage(), allOf( containsString("RabbitMessageBus does not support consumer properties: "), containsString("partitionSelectorExpression"), containsString("partitionKeyExtractorClass"), containsString("partitionKeyExpression"), containsString("partitionSelectorClass"))); assertThat( e.getMessage(), allOf(containsString("partitionIndex"), containsString("for dummy."))); } bus.unbindConsumers("props.0"); bus.unbindProducers("props.0"); assertEquals(0, bindings.size()); }
@Test public void testProducerProperties() throws Exception { MessageBus bus = getMessageBus(); bus.bindProducer("props.0", new DirectChannel(), null); @SuppressWarnings("unchecked") List<Binding> bindings = TestUtils.getPropertyValue(bus, "messageBus.bindings", List.class); assertEquals(1, bindings.size()); AbstractEndpoint endpoint = bindings.get(0).getEndpoint(); assertEquals( "xdbus.props.0", TestUtils.getPropertyValue(endpoint, "handler.delegate.routingKey")); MessageDeliveryMode mode = TestUtils.getPropertyValue( endpoint, "handler.delegate.defaultDeliveryMode", MessageDeliveryMode.class); assertEquals(MessageDeliveryMode.PERSISTENT, mode); List<?> requestHeaders = TestUtils.getPropertyValue( endpoint, "handler.delegate.headerMapper.requestHeaderMatcher.strategies", List.class); assertEquals(2, requestHeaders.size()); bus.unbindProducers("props.0"); assertEquals(0, bindings.size()); Properties properties = new Properties(); properties.put("prefix", "foo."); properties.put("deliveryMode", "NON_PERSISTENT"); properties.put("requestHeaderPatterns", "foo"); properties.put("partitionKeyExpression", "'foo'"); properties.put("partitionKeyExtractorClass", "foo"); properties.put("partitionSelectorExpression", "0"); properties.put("partitionSelectorClass", "foo"); properties.put(BusProperties.NEXT_MODULE_COUNT, "2"); bus.bindProducer("props.0", new DirectChannel(), properties); assertEquals(1, bindings.size()); endpoint = bindings.get(0).getEndpoint(); assertEquals( "'foo.props.0-' + headers['partition']", TestUtils.getPropertyValue( endpoint, "handler.delegate.routingKeyExpression", SpelExpression.class) .getExpressionString()); mode = TestUtils.getPropertyValue( endpoint, "handler.delegate.defaultDeliveryMode", MessageDeliveryMode.class); assertEquals(MessageDeliveryMode.NON_PERSISTENT, mode); verifyFooRequestProducer(endpoint); try { bus.bindPubSubProducer("dummy", new DirectChannel(), properties); fail("Expected exception"); } catch (IllegalArgumentException e) { assertThat( e.getMessage(), allOf( containsString("RabbitMessageBus does not support producer properties: "), containsString("partitionSelectorExpression"), containsString("partitionKeyExtractorClass"), containsString("partitionKeyExpression"), containsString("partitionSelectorClass"))); assertThat(e.getMessage(), containsString("for dummy.")); } try { bus.bindProducer("queue:dummy", new DirectChannel(), properties); fail("Expected exception"); } catch (IllegalArgumentException e) { assertThat( e.getMessage(), allOf( containsString("RabbitMessageBus does not support producer properties: "), containsString("partitionSelectorExpression"), containsString("partitionKeyExtractorClass"), containsString("partitionKeyExpression"), containsString("partitionSelectorClass"))); assertThat(e.getMessage(), containsString("for queue:dummy.")); } bus.unbindProducers("props.0"); assertEquals(0, bindings.size()); }
@Test public void testConsumerProperties() throws Exception { MessageBus bus = getMessageBus(); Properties properties = new Properties(); properties.put( "transacted", "true"); // test transacted with defaults; not allowed with ackmode NONE bus.bindConsumer("props.0", new DirectChannel(), properties); @SuppressWarnings("unchecked") List<Binding> bindings = TestUtils.getPropertyValue(bus, "messageBus.bindings", List.class); assertEquals(1, bindings.size()); AbstractEndpoint endpoint = bindings.get(0).getEndpoint(); SimpleMessageListenerContainer container = TestUtils.getPropertyValue( endpoint, "messageListenerContainer", SimpleMessageListenerContainer.class); assertEquals(AcknowledgeMode.AUTO, container.getAcknowledgeMode()); assertEquals("xdbus.props.0", container.getQueueNames()[0]); assertTrue(TestUtils.getPropertyValue(container, "transactional", Boolean.class)); assertEquals(1, TestUtils.getPropertyValue(container, "concurrentConsumers")); assertNull(TestUtils.getPropertyValue(container, "maxConcurrentConsumers")); assertTrue(TestUtils.getPropertyValue(container, "defaultRequeueRejected", Boolean.class)); assertEquals(1, TestUtils.getPropertyValue(container, "prefetchCount")); assertEquals(1, TestUtils.getPropertyValue(container, "txSize")); Advice retry = TestUtils.getPropertyValue(container, "adviceChain", Advice[].class)[0]; assertEquals(3, TestUtils.getPropertyValue(retry, "retryOperations.retryPolicy.maxAttempts")); assertEquals( 1000L, TestUtils.getPropertyValue(retry, "retryOperations.backOffPolicy.initialInterval")); assertEquals( 10000L, TestUtils.getPropertyValue(retry, "retryOperations.backOffPolicy.maxInterval")); assertEquals( 2.0, TestUtils.getPropertyValue(retry, "retryOperations.backOffPolicy.multiplier")); bus.unbindConsumers("props.0"); assertEquals(0, bindings.size()); properties = new Properties(); properties.put("ackMode", "NONE"); properties.put("backOffInitialInterval", "2000"); properties.put("backOffMaxInterval", "20000"); properties.put("backOffMultiplier", "5.0"); properties.put("concurrency", "2"); properties.put("maxAttempts", "23"); properties.put("maxConcurrency", "3"); properties.put("prefix", "foo."); properties.put("prefetch", "20"); properties.put("requestHeaderPatterns", "foo"); properties.put("requeue", "false"); properties.put("txSize", "10"); properties.put("partitionIndex", 0); bus.bindConsumer("props.0", new DirectChannel(), properties); @SuppressWarnings("unchecked") List<Binding> bindingsNow = TestUtils.getPropertyValue(bus, "messageBus.bindings", List.class); assertEquals(1, bindingsNow.size()); endpoint = bindingsNow.get(0).getEndpoint(); container = verifyContainer(endpoint); assertEquals("foo.props.0", container.getQueueNames()[0]); try { bus.bindPubSubConsumer("dummy", null, properties); fail("Expected exception"); } catch (IllegalArgumentException e) { assertThat( e.getMessage(), allOf( containsString("RabbitMessageBus does not support consumer properties: "), containsString("partitionIndex"), containsString("concurrency"), containsString(" for dummy."))); } try { bus.bindConsumer("queue:dummy", null, properties); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals( "RabbitMessageBus does not support consumer property: partitionIndex for queue:dummy.", e.getMessage()); } bus.unbindConsumers("props.0"); assertEquals(0, bindingsNow.size()); }