diff --git a/pom.xml b/pom.xml index 017f37d2c..69428e411 100644 --- a/pom.xml +++ b/pom.xml @@ -79,10 +79,24 @@ + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java.version} + ${java.version} + -parameters + + org.apache.maven.plugins maven-checkstyle-plugin + + io.spring.javaformat + spring-javaformat-maven-plugin + diff --git a/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/admin/RabbitAdminException.java b/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/admin/RabbitAdminException.java index a9b69e1f7..179064109 100644 --- a/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/admin/RabbitAdminException.java +++ b/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/admin/RabbitAdminException.java @@ -16,9 +16,9 @@ package org.springframework.cloud.stream.binder.rabbit.admin; - /** * Exceptions thrown while interfacing with the RabbitMQ admin plugin. + * * @author Gary Russell * @since 1.2 */ diff --git a/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/admin/RabbitBindingCleaner.java b/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/admin/RabbitBindingCleaner.java index 6f56b3490..c5e7449fe 100644 --- a/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/admin/RabbitBindingCleaner.java +++ b/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/admin/RabbitBindingCleaner.java @@ -30,9 +30,10 @@ import org.springframework.cloud.stream.binder.BindingCleaner; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; - /** - * Implementation of {@link org.springframework.cloud.stream.binder.BindingCleaner} for the {@code RabbitBinder}. + * Implementation of {@link org.springframework.cloud.stream.binder.BindingCleaner} for + * the {@code RabbitBinder}. + * * @author Gary Russell * @author David Turanski * @since 1.2 @@ -47,28 +48,28 @@ public class RabbitBindingCleaner implements BindingCleaner { @Override public Map> clean(String entity, boolean isJob) { - return clean("http://localhost:15672", "guest", "guest", "/", BINDER_PREFIX, entity, isJob); - } - - public Map> clean(String adminUri, String user, String pw, String vhost, - String binderPrefix, String entity, boolean isJob) { - return doClean( - adminUri == null ? "http://localhost:15672" : adminUri, - user == null ? "guest" : user, - pw == null ? "guest" : pw, - vhost == null ? "/" : vhost, - binderPrefix == null ? BINDER_PREFIX : binderPrefix, + return clean("http://localhost:15672", "guest", "guest", "/", BINDER_PREFIX, entity, isJob); } - private Map> doClean(String adminUri, String user, String pw, String vhost, - String binderPrefix, String entity, boolean isJob) { - RestTemplate restTemplate = RabbitManagementUtils.buildRestTemplate(adminUri, user, pw); - List removedQueues = isJob - ? null + public Map> clean(String adminUri, String user, String pw, + String vhost, String binderPrefix, String entity, boolean isJob) { + return doClean(adminUri == null ? "http://localhost:15672" : adminUri, + user == null ? "guest" : user, pw == null ? "guest" : pw, + vhost == null ? "/" : vhost, + binderPrefix == null ? BINDER_PREFIX : binderPrefix, entity, isJob); + } + + private Map> doClean(String adminUri, String user, String pw, + String vhost, String binderPrefix, String entity, boolean isJob) { + RestTemplate restTemplate = RabbitManagementUtils.buildRestTemplate(adminUri, + user, pw); + List removedQueues = isJob ? null : findStreamQueues(adminUri, vhost, binderPrefix, entity, restTemplate); - List removedExchanges = findExchanges(adminUri, vhost, binderPrefix, entity, restTemplate); - // Delete the queues in reverse order to enable re-running after a partial success. + List removedExchanges = findExchanges(adminUri, vhost, binderPrefix, + entity, restTemplate); + // Delete the queues in reverse order to enable re-running after a partial + // success. // The queue search above starts with 0 and terminates on a not found. for (int i = removedQueues.size() - 1; i >= 0; i--) { String queueName = removedQueues.get(i); @@ -100,9 +101,10 @@ public class RabbitBindingCleaner implements BindingCleaner { return results; } - private List findStreamQueues(String adminUri, String vhost, String binderPrefix, String stream, - RestTemplate restTemplate) { - String queueNamePrefix = adjustPrefix(AbstractBinder.applyPrefix(binderPrefix, stream)); + private List findStreamQueues(String adminUri, String vhost, + String binderPrefix, String stream, RestTemplate restTemplate) { + String queueNamePrefix = adjustPrefix( + AbstractBinder.applyPrefix(binderPrefix, stream)); List> queues = listAllQueues(adminUri, vhost, restTemplate); List removedQueues = new ArrayList<>(); for (Map queue : queues) { @@ -115,10 +117,10 @@ public class RabbitBindingCleaner implements BindingCleaner { return removedQueues; } - private List> listAllQueues(String adminUri, String vhost, RestTemplate restTemplate) { + private List> listAllQueues(String adminUri, String vhost, + RestTemplate restTemplate) { URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") - .pathSegment("queues", "{vhost}") - .buildAndExpand(vhost).encode().toUri(); + .pathSegment("queues", "{vhost}").buildAndExpand(vhost).encode().toUri(); List> queues = restTemplate.getForObject(uri, List.class); return queues; } @@ -138,51 +140,57 @@ public class RabbitBindingCleaner implements BindingCleaner { } } - private List findExchanges(String adminUri, String vhost, String binderPrefix, String entity, - RestTemplate restTemplate) { + private List findExchanges(String adminUri, String vhost, String binderPrefix, + String entity, RestTemplate restTemplate) { List removedExchanges = new ArrayList<>(); URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api") - .pathSegment("exchanges", "{vhost}") - .buildAndExpand(vhost).encode().toUri(); + .pathSegment("exchanges", "{vhost}").buildAndExpand(vhost).encode() + .toUri(); List> exchanges = restTemplate.getForObject(uri, List.class); - String exchangeNamePrefix = adjustPrefix(AbstractBinder.applyPrefix(binderPrefix, entity)); + String exchangeNamePrefix = adjustPrefix( + AbstractBinder.applyPrefix(binderPrefix, entity)); for (Map exchange : exchanges) { String exchangeName = (String) exchange.get("name"); if (exchangeName.startsWith(exchangeNamePrefix)) { uri = UriComponentsBuilder.fromUriString(adminUri + "/api") - .pathSegment("exchanges", "{vhost}", "{name}", "bindings", "source") + .pathSegment("exchanges", "{vhost}", "{name}", "bindings", + "source") .buildAndExpand(vhost, exchangeName).encode().toUri(); - List> bindings = restTemplate.getForObject(uri, List.class); + List> bindings = restTemplate.getForObject(uri, + List.class); if (hasNoForeignBindings(bindings, exchangeNamePrefix)) { uri = UriComponentsBuilder.fromUriString(adminUri + "/api") - .pathSegment("exchanges", "{vhost}", "{name}", "bindings", "destination") + .pathSegment("exchanges", "{vhost}", "{name}", "bindings", + "destination") .buildAndExpand(vhost, exchangeName).encode().toUri(); bindings = restTemplate.getForObject(uri, List.class); if (bindings.size() == 0) { removedExchanges.add((String) exchange.get("name")); } else { - throw new RabbitAdminException("Cannot delete exchange " + exchangeName - + "; it is a destination: " + bindings); + throw new RabbitAdminException("Cannot delete exchange " + + exchangeName + "; it is a destination: " + bindings); } } else { - throw new RabbitAdminException("Cannot delete exchange " + exchangeName + "; it has bindings: " - + bindings); + throw new RabbitAdminException("Cannot delete exchange " + + exchangeName + "; it has bindings: " + bindings); } } } return removedExchanges; } - private boolean hasNoForeignBindings(List> bindings, String exchangeNamePrefix) { + private boolean hasNoForeignBindings(List> bindings, + String exchangeNamePrefix) { if (bindings.size() == 0) { return true; } boolean noForeign = true; for (Map binding : bindings) { if (!("queue".equals(binding.get("destination_type"))) - || !((String) binding.get("destination")).startsWith(exchangeNamePrefix)) { + || !((String) binding.get("destination")) + .startsWith(exchangeNamePrefix)) { noForeign = false; break; } diff --git a/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/admin/RabbitManagementUtils.java b/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/admin/RabbitManagementUtils.java index d44c62419..077663597 100644 --- a/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/admin/RabbitManagementUtils.java +++ b/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/admin/RabbitManagementUtils.java @@ -44,13 +44,16 @@ import org.springframework.web.client.RestTemplate; */ public abstract class RabbitManagementUtils { - public static RestTemplate buildRestTemplate(String adminUri, String user, String password) { + public static RestTemplate buildRestTemplate(String adminUri, String user, + String password) { BasicCredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(user, password)); - HttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); - // Set up pre-emptive basic Auth because the rabbit plugin doesn't currently support challenge/response for PUT + HttpClient httpClient = HttpClients.custom() + .setDefaultCredentialsProvider(credsProvider).build(); + // Set up pre-emptive basic Auth because the rabbit plugin doesn't currently + // support challenge/response for PUT // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local; from the apache docs... @@ -63,20 +66,24 @@ public abstract class RabbitManagementUtils { catch (URISyntaxException e) { throw new RabbitAdminException("Invalid URI", e); } - authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), basicAuth); + authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), + basicAuth); // Add AuthCache to the execution context final HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); - RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient) { + RestTemplate restTemplate = new RestTemplate( + new HttpComponentsClientHttpRequestFactory(httpClient) { - @Override - protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) { - return localContext; - } + @Override + protected HttpContext createHttpContext(HttpMethod httpMethod, + URI uri) { + return localContext; + } - }); - restTemplate.setMessageConverters(Collections.>singletonList( - new MappingJackson2HttpMessageConverter())); + }); + restTemplate + .setMessageConverters(Collections.>singletonList( + new MappingJackson2HttpMessageConverter())); return restTemplate; } diff --git a/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/properties/RabbitBindingProperties.java b/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/properties/RabbitBindingProperties.java index 70b937b28..14210a536 100644 --- a/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/properties/RabbitBindingProperties.java +++ b/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/properties/RabbitBindingProperties.java @@ -22,7 +22,7 @@ import org.springframework.cloud.stream.binder.BinderSpecificPropertiesProvider; * @author Marius Bogoevici * @author Oleg Zhurakousky */ -public class RabbitBindingProperties implements BinderSpecificPropertiesProvider{ +public class RabbitBindingProperties implements BinderSpecificPropertiesProvider { private RabbitConsumerProperties consumer = new RabbitConsumerProperties(); @@ -43,4 +43,5 @@ public class RabbitBindingProperties implements BinderSpecificPropertiesProvider public void setProducer(RabbitProducerProperties producer) { this.producer = producer; } + } diff --git a/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/properties/RabbitCommonProperties.java b/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/properties/RabbitCommonProperties.java index 787c31e97..ebbf8d79c 100644 --- a/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/properties/RabbitCommonProperties.java +++ b/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/properties/RabbitCommonProperties.java @@ -26,7 +26,7 @@ import org.springframework.amqp.core.ExchangeTypes; * @since 1.2 * */ -public abstract class RabbitCommonProperties { +public abstract class RabbitCommonProperties { public static final String DEAD_LETTER_EXCHANGE = "DLX"; @@ -66,7 +66,8 @@ public abstract class RabbitCommonProperties { private boolean bindQueue = true; /** - * routing key to bind (default # for non-partitioned, destination-instanceIndex for partitioned) + * routing key to bind (default # for non-partitioned, destination-instanceIndex for + * partitioned) */ private String bindingRoutingKey; @@ -116,7 +117,8 @@ public abstract class RabbitCommonProperties { private boolean declareDlx = true; /** - * a dead letter routing key to assign to that queue; if autoBindDlq is true, defaults to destination + * a dead letter routing key to assign to that queue; if autoBindDlq is true, defaults + * to destination */ private String deadLetterRoutingKey; @@ -151,7 +153,8 @@ public abstract class RabbitCommonProperties { private String dlqDeadLetterExchange; /** - * if a DLQ is declared, a dead letter routing key to assign to that queue; default none + * if a DLQ is declared, a dead letter routing key to assign to that queue; default + * none */ private String dlqDeadLetterRoutingKey; diff --git a/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/properties/RabbitConsumerProperties.java b/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/properties/RabbitConsumerProperties.java index 688f52cf1..0724b112a 100644 --- a/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/properties/RabbitConsumerProperties.java +++ b/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/properties/RabbitConsumerProperties.java @@ -77,7 +77,7 @@ public class RabbitConsumerProperties extends RabbitCommonProperties { /** * patterns to match which headers are mapped (inbound) */ - private String[] headerPatterns = new String[] {"*"}; + private String[] headerPatterns = new String[] { "*" }; /** * interval between reconnection attempts @@ -102,7 +102,7 @@ public class RabbitConsumerProperties extends RabbitCommonProperties { /** * interval between attempts to passively declare missing queues */ - private Long failedDeclarationRetryInterval; + private Long failedDeclarationRetryInterval; /** * Used to create the consumer tags; will be appended by '#n' where 'n' increments for diff --git a/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/properties/RabbitExtendedBindingProperties.java b/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/properties/RabbitExtendedBindingProperties.java index 4bc10df40..c2d215f9c 100644 --- a/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/properties/RabbitExtendedBindingProperties.java +++ b/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/properties/RabbitExtendedBindingProperties.java @@ -27,8 +27,8 @@ import org.springframework.cloud.stream.binder.BinderSpecificPropertiesProvider; * @author Soby Chacko */ @ConfigurationProperties("spring.cloud.stream.rabbit") -public class RabbitExtendedBindingProperties - extends AbstractExtendedBindingProperties { +public class RabbitExtendedBindingProperties extends + AbstractExtendedBindingProperties { private static final String DEFAULTS_PREFIX = "spring.cloud.stream.rabbit.default"; @@ -41,4 +41,5 @@ public class RabbitExtendedBindingProperties public Class getExtendedPropertiesEntryClass() { return RabbitBindingProperties.class; } + } diff --git a/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/properties/RabbitProducerProperties.java b/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/properties/RabbitProducerProperties.java index bfa848797..cb1f5a3b5 100644 --- a/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/properties/RabbitProducerProperties.java +++ b/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/properties/RabbitProducerProperties.java @@ -65,21 +65,24 @@ public class RabbitProducerProperties extends RabbitCommonProperties { /** * patterns to match which headers are mapped (inbound) */ - private String[] headerPatterns = new String[] {"*"}; + private String[] headerPatterns = new String[] { "*" }; /** - * when using a delayed message exchange, a SpEL expression to determine the delay to apply to messages + * when using a delayed message exchange, a SpEL expression to determine the delay to + * apply to messages */ private Expression delayExpression; /** - * a custom routing key when publishing messages; default is the destination name; suffixed by "-partition" when partitioned + * a custom routing key when publishing messages; default is the destination name; + * suffixed by "-partition" when partitioned */ private Expression routingKeyExpression; /** * the channel name to which to send publisher confirms (acks) if the connection - * factory is so configured; default 'nullChannel'; requires 'errorChannelEnabled=true' + * factory is so configured; default 'nullChannel'; requires + * 'errorChannelEnabled=true' */ private String confirmAckChannel; diff --git a/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/provisioning/RabbitExchangeQueueProvisioner.java b/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/provisioning/RabbitExchangeQueueProvisioner.java index 15a8b0898..16796bb35 100644 --- a/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/provisioning/RabbitExchangeQueueProvisioner.java +++ b/spring-cloud-stream-binder-rabbit-core/src/main/java/org/springframework/cloud/stream/binder/rabbit/provisioning/RabbitExchangeQueueProvisioner.java @@ -60,12 +60,12 @@ import org.springframework.util.StringUtils; * @author Gary Russell * @author Oleg Zhurakousky */ -public class RabbitExchangeQueueProvisioner implements ApplicationListener, - ProvisioningProvider, - ExtendedProducerProperties> { +public class RabbitExchangeQueueProvisioner + implements ApplicationListener, + ProvisioningProvider, ExtendedProducerProperties> { - private static final Base64UrlNamingStrategy ANONYMOUS_GROUP_NAME_GENERATOR - = new Base64UrlNamingStrategy("anonymous."); + private static final Base64UrlNamingStrategy ANONYMOUS_GROUP_NAME_GENERATOR = new Base64UrlNamingStrategy( + "anonymous."); /** * The delimiter between a group and index when constructing a binder @@ -90,38 +90,48 @@ public class RabbitExchangeQueueProvisioner implements ApplicationListener producerProperties) { - final String exchangeName = applyPrefix(producerProperties.getExtension().getPrefix(), name); - Exchange exchange = buildExchange(producerProperties.getExtension(), exchangeName); + ExtendedProducerProperties producerProperties) { + final String exchangeName = applyPrefix( + producerProperties.getExtension().getPrefix(), name); + Exchange exchange = buildExchange(producerProperties.getExtension(), + exchangeName); if (producerProperties.getExtension().isDeclareExchange()) { declareExchange(exchangeName, exchange); } Binding binding = null; for (String requiredGroupName : producerProperties.getRequiredGroups()) { - String baseQueueName = producerProperties.getExtension().isQueueNameGroupOnly() - ? requiredGroupName : (exchangeName + "." + requiredGroupName); + String baseQueueName = producerProperties.getExtension() + .isQueueNameGroupOnly() ? requiredGroupName + : (exchangeName + "." + requiredGroupName); if (!producerProperties.isPartitioned()) { - autoBindDLQ(baseQueueName, baseQueueName, producerProperties.getExtension()); + autoBindDLQ(baseQueueName, baseQueueName, + producerProperties.getExtension()); if (producerProperties.getExtension().isBindQueue()) { - Queue queue = new Queue(baseQueueName, true, false, false, - queueArgs(baseQueueName, producerProperties.getExtension(), false)); + Queue queue = new Queue(baseQueueName, true, false, false, queueArgs( + baseQueueName, producerProperties.getExtension(), false)); declareQueue(baseQueueName, queue); - binding = notPartitionedBinding(exchange, queue, producerProperties.getExtension()); + binding = notPartitionedBinding(exchange, queue, + producerProperties.getExtension()); } } else { - // if the stream is partitioned, create one queue for each target partition for the default group + // if the stream is partitioned, create one queue for each target + // partition for the default group for (int i = 0; i < producerProperties.getPartitionCount(); i++) { String partitionSuffix = "-" + i; String partitionQueueName = baseQueueName + partitionSuffix; - autoBindDLQ(baseQueueName, baseQueueName + partitionSuffix, producerProperties.getExtension()); + autoBindDLQ(baseQueueName, baseQueueName + partitionSuffix, + producerProperties.getExtension()); if (producerProperties.getExtension().isBindQueue()) { Queue queue = new Queue(partitionQueueName, true, false, false, - queueArgs(partitionQueueName, producerProperties.getExtension(), false)); + queueArgs(partitionQueueName, + producerProperties.getExtension(), false)); declareQueue(queue.getName(), queue); String prefix = producerProperties.getExtension().getPrefix(); - String destination = StringUtils.isEmpty(prefix) ? exchangeName : exchangeName.substring(prefix.length()); - binding = partitionedBinding(destination, exchange, queue, producerProperties.getExtension(), i); + String destination = StringUtils.isEmpty(prefix) ? exchangeName + : exchangeName.substring(prefix.length()); + binding = partitionedBinding(destination, exchange, queue, + producerProperties.getExtension(), i); } } } @@ -137,10 +147,14 @@ public class RabbitExchangeQueueProvisioner implements ApplicationListener doProvisionConsumerDestination(destination, group, properties).getName()) - .toArray(String[]::new); - consumerDestination = new RabbitConsumerDestination(StringUtils.arrayToCommaDelimitedString(provisionedDestinations), null); + String[] provisionedDestinations = Stream + .of(StringUtils.tokenizeToStringArray(name, ",", true, true)) + .map(destination -> doProvisionConsumerDestination(destination, group, + properties).getName()) + .toArray(String[]::new); + consumerDestination = new RabbitConsumerDestination( + StringUtils.arrayToCommaDelimitedString(provisionedDestinations), + null); } return consumerDestination; } @@ -148,15 +162,18 @@ public class RabbitExchangeQueueProvisioner implements ApplicationListener properties) { boolean anonymous = !StringUtils.hasText(group); - String baseQueueName; + String baseQueueName; if (properties.getExtension().isQueueNameGroupOnly()) { - baseQueueName = anonymous ? ANONYMOUS_GROUP_NAME_GENERATOR.generateName() : group; + baseQueueName = anonymous ? ANONYMOUS_GROUP_NAME_GENERATOR.generateName() + : group; } else { - baseQueueName = groupedName(name, anonymous ? ANONYMOUS_GROUP_NAME_GENERATOR.generateName() : group); + baseQueueName = groupedName(name, + anonymous ? ANONYMOUS_GROUP_NAME_GENERATOR.generateName() : group); } if (this.logger.isInfoEnabled()) { - this.logger.info("declaring queue for inbound: " + baseQueueName + ", bound to: " + name); + this.logger.info("declaring queue for inbound: " + baseQueueName + + ", bound to: " + name); } String prefix = properties.getExtension().getPrefix(); final String exchangeName = applyPrefix(prefix, name); @@ -169,7 +186,8 @@ public class RabbitExchangeQueueProvisioner implements ApplicationListener properties, - Exchange exchange, boolean partitioned, Queue queue) { + private Binding declareConsumerBindings(String name, + ExtendedConsumerProperties properties, + Exchange exchange, boolean partitioned, Queue queue) { if (partitioned) { - return partitionedBinding(name, exchange, queue, properties.getExtension(), properties.getInstanceIndex()); + return partitionedBinding(name, exchange, queue, properties.getExtension(), + properties.getInstanceIndex()); } else { return notPartitionedBinding(exchange, queue, properties.getExtension()); } } - private Binding notPartitionedBinding(Exchange exchange, Queue queue, RabbitCommonProperties extendedProperties) { + private Binding notPartitionedBinding(Exchange exchange, Queue queue, + RabbitCommonProperties extendedProperties) { String routingKey = extendedProperties.getBindingRoutingKey(); if (routingKey == null) { routingKey = "#"; } if (exchange instanceof TopicExchange) { - Binding binding = BindingBuilder.bind(queue) - .to((TopicExchange) exchange) + Binding binding = BindingBuilder.bind(queue).to((TopicExchange) exchange) .with(routingKey); declareBinding(queue.getName(), binding); return binding; } else if (exchange instanceof DirectExchange) { - Binding binding = BindingBuilder.bind(queue) - .to((DirectExchange) exchange) + Binding binding = BindingBuilder.bind(queue).to((DirectExchange) exchange) .with(routingKey); declareBinding(queue.getName(), binding); return binding; } else if (exchange instanceof FanoutExchange) { - Binding binding = BindingBuilder.bind(queue) - .to((FanoutExchange) exchange); + Binding binding = BindingBuilder.bind(queue).to((FanoutExchange) exchange); declareBinding(queue.getName(), binding); return binding; } else { - throw new ProvisioningException("Cannot bind to a " + exchange.getType() + " exchange"); + throw new ProvisioningException( + "Cannot bind to a " + exchange.getType() + " exchange"); } } /** - * If so requested, declare the DLX/DLQ and bind it. The DLQ is bound to the DLX with a routing key of the original - * queue name because we use default exchange routing by queue name for the original message. - * @param baseQueueName The base name for the queue (including the binder prefix, if any). - * @param routingKey The routing key for the queue. + * If so requested, declare the DLX/DLQ and bind it. The DLQ is bound to the DLX with + * a routing key of the original queue name because we use default exchange routing by + * queue name for the original message. + * @param baseQueueName The base name for the queue (including the binder prefix, if + * any). + * @param routingKey The routing key for the queue. * @param properties the properties. */ - private void autoBindDLQ(final String baseQueueName, String routingKey, RabbitCommonProperties properties) { + private void autoBindDLQ(final String baseQueueName, String routingKey, + RabbitCommonProperties properties) { boolean autoBindDlq = properties.isAutoBindDlq(); if (this.logger.isDebugEnabled()) { - this.logger.debug("autoBindDLQ=" + autoBindDlq - + " for: " + baseQueueName); + this.logger.debug("autoBindDLQ=" + autoBindDlq + " for: " + baseQueueName); } if (autoBindDlq) { String dlqName; @@ -298,27 +320,29 @@ public class RabbitExchangeQueueProvisioner implements ApplicationListener queueArgs(String queueName, RabbitCommonProperties properties, boolean isDlq) { + private Map queueArgs(String queueName, + RabbitCommonProperties properties, boolean isDlq) { Map args = new HashMap<>(); if (!isDlq) { if (properties.isAutoBindDlq()) { @@ -392,21 +416,27 @@ public class RabbitExchangeQueueProvisioner implements ApplicationListener args, RabbitCommonProperties properties, boolean isDlq) { + private void additionalArgs(Map args, + RabbitCommonProperties properties, boolean isDlq) { Integer expires = isDlq ? properties.getDlqExpires() : properties.getExpires(); - Integer maxLength = isDlq ? properties.getDlqMaxLength() : properties.getMaxLength(); - Integer maxLengthBytes = isDlq ? properties.getDlqMaxLengthBytes() : properties.getMaxLengthBytes(); - Integer maxPriority = isDlq ? properties.getDlqMaxPriority() : properties.getMaxPriority(); + Integer maxLength = isDlq ? properties.getDlqMaxLength() + : properties.getMaxLength(); + Integer maxLengthBytes = isDlq ? properties.getDlqMaxLengthBytes() + : properties.getMaxLengthBytes(); + Integer maxPriority = isDlq ? properties.getDlqMaxPriority() + : properties.getMaxPriority(); Integer ttl = isDlq ? properties.getDlqTtl() : properties.getTtl(); boolean lazy = isDlq ? properties.isDlqLazy() : properties.isLazy(); - String overflow = isDlq ? properties.getDlqOverflowBehavior() : properties.getOverflowBehavior(); + String overflow = isDlq ? properties.getDlqOverflowBehavior() + : properties.getOverflowBehavior(); if (expires != null) { args.put("x-expires", expires); } @@ -430,14 +460,15 @@ public class RabbitExchangeQueueProvisioner implements ApplicationListener consumerProperties) { synchronized (this.autoDeclareContext) { - Stream.of(StringUtils.tokenizeToStringArray(destination.getName(), ",", true, true)).forEach(name -> { - name = name.trim(); - removeSingleton(name + ".binding"); - removeSingleton(name); - String dlq = name + ".dlq"; - removeSingleton(dlq + ".binding"); - removeSingleton(dlq); - }); + Stream.of(StringUtils.tokenizeToStringArray(destination.getName(), ",", true, + true)).forEach(name -> { + name = name.trim(); + removeSingleton(name + ".binding"); + removeSingleton(name); + String dlq = name + ".dlq"; + removeSingleton(dlq + ".binding"); + removeSingleton(dlq); + }); } } private void removeSingleton(String name) { if (this.autoDeclareContext.containsBean(name)) { - ConfigurableListableBeanFactory beanFactory = this.autoDeclareContext.getBeanFactory(); + ConfigurableListableBeanFactory beanFactory = this.autoDeclareContext + .getBeanFactory(); if (beanFactory instanceof DefaultListableBeanFactory) { ((DefaultListableBeanFactory) beanFactory).destroySingleton(name); } @@ -556,16 +593,16 @@ public class RabbitExchangeQueueProvisioner implements ApplicationListener= 0) { os.write(c); diff --git a/spring-cloud-stream-binder-rabbit/src/main/java/org/springframework/cloud/stream/binder/rabbit/RabbitExpressionEvaluatingInterceptor.java b/spring-cloud-stream-binder-rabbit/src/main/java/org/springframework/cloud/stream/binder/rabbit/RabbitExpressionEvaluatingInterceptor.java index 2d8efe2ee..aa39c617e 100644 --- a/spring-cloud-stream-binder-rabbit/src/main/java/org/springframework/cloud/stream/binder/rabbit/RabbitExpressionEvaluatingInterceptor.java +++ b/spring-cloud-stream-binder-rabbit/src/main/java/org/springframework/cloud/stream/binder/rabbit/RabbitExpressionEvaluatingInterceptor.java @@ -49,14 +49,14 @@ public class RabbitExpressionEvaluatingInterceptor implements ChannelInterceptor private final EvaluationContext evaluationContext; /** - * Construct an instance with the provided expressions and evaluation context. - * At least one expression muse be non-null. + * Construct an instance with the provided expressions and evaluation context. At + * least one expression muse be non-null. * @param routingKeyExpression the routing key expresssion. * @param delayExpression the delay expression. * @param evaluationContext the evaluation context. */ - public RabbitExpressionEvaluatingInterceptor(Expression routingKeyExpression, Expression delayExpression, - EvaluationContext evaluationContext) { + public RabbitExpressionEvaluatingInterceptor(Expression routingKeyExpression, + Expression delayExpression, EvaluationContext evaluationContext) { Assert.isTrue(routingKeyExpression != null || delayExpression != null, "At least one expression is required"); Assert.notNull(evaluationContext, "the 'evaluationContext' cannot be null"); @@ -83,7 +83,8 @@ public class RabbitExpressionEvaluatingInterceptor implements ChannelInterceptor this.routingKeyExpression.getValue(this.evaluationContext, message)); } if (this.delayExpression != null) { - builder.setHeader(DELAY_HEADER, this.delayExpression.getValue(this.evaluationContext, message)); + builder.setHeader(DELAY_HEADER, + this.delayExpression.getValue(this.evaluationContext, message)); } return builder.build(); } diff --git a/spring-cloud-stream-binder-rabbit/src/main/java/org/springframework/cloud/stream/binder/rabbit/RabbitMessageChannelBinder.java b/spring-cloud-stream-binder-rabbit/src/main/java/org/springframework/cloud/stream/binder/rabbit/RabbitMessageChannelBinder.java index 80d41ed3e..5bc7c25bb 100644 --- a/spring-cloud-stream-binder-rabbit/src/main/java/org/springframework/cloud/stream/binder/rabbit/RabbitMessageChannelBinder.java +++ b/spring-cloud-stream-binder-rabbit/src/main/java/org/springframework/cloud/stream/binder/rabbit/RabbitMessageChannelBinder.java @@ -118,30 +118,28 @@ import com.rabbitmq.client.Envelope; * @author Soby Chacko * @author Oleg Zhurakousky */ -public class RabbitMessageChannelBinder - extends AbstractMessageChannelBinder, - ExtendedProducerProperties, RabbitExchangeQueueProvisioner> - implements ExtendedPropertiesBinder, - DisposableBean { +public class RabbitMessageChannelBinder extends + AbstractMessageChannelBinder, ExtendedProducerProperties, RabbitExchangeQueueProvisioner> + implements + ExtendedPropertiesBinder, + DisposableBean { - private static final SimplePassthroughMessageConverter passThoughConverter = - new SimplePassthroughMessageConverter(); + private static final SimplePassthroughMessageConverter passThoughConverter = new SimplePassthroughMessageConverter(); - private static final AmqpMessageHeaderErrorMessageStrategy errorMessageStrategy = - new AmqpMessageHeaderErrorMessageStrategy(); + private static final AmqpMessageHeaderErrorMessageStrategy errorMessageStrategy = new AmqpMessageHeaderErrorMessageStrategy(); - private static final MessagePropertiesConverter inboundMessagePropertiesConverter = - new DefaultMessagePropertiesConverter() { + private static final MessagePropertiesConverter inboundMessagePropertiesConverter = new DefaultMessagePropertiesConverter() { - @Override - public MessageProperties toMessageProperties(AMQP.BasicProperties source, Envelope envelope, - String charset) { - MessageProperties properties = super.toMessageProperties(source, envelope, charset); - properties.setDeliveryMode(null); - return properties; - } + @Override + public MessageProperties toMessageProperties(AMQP.BasicProperties source, + Envelope envelope, String charset) { + MessageProperties properties = super.toMessageProperties(source, envelope, + charset); + properties.setDeliveryMode(null); + return properties; + } - }; + }; private final RabbitProperties rabbitProperties; @@ -161,12 +159,14 @@ public class RabbitMessageChannelBinder private RabbitExtendedBindingProperties extendedBindingProperties = new RabbitExtendedBindingProperties(); - public RabbitMessageChannelBinder(ConnectionFactory connectionFactory, RabbitProperties rabbitProperties, + public RabbitMessageChannelBinder(ConnectionFactory connectionFactory, + RabbitProperties rabbitProperties, RabbitExchangeQueueProvisioner provisioningProvider) { this(connectionFactory, rabbitProperties, provisioningProvider, null); } - public RabbitMessageChannelBinder(ConnectionFactory connectionFactory, RabbitProperties rabbitProperties, + public RabbitMessageChannelBinder(ConnectionFactory connectionFactory, + RabbitProperties rabbitProperties, RabbitExchangeQueueProvisioner provisioningProvider, ListenerContainerCustomizer containerCustomizer) { super(new String[0], provisioningProvider, containerCustomizer); @@ -181,16 +181,19 @@ public class RabbitMessageChannelBinder * {@link DelegatingDecompressingPostProcessor} with its default delegates. * @param decompressingPostProcessor the post processor. */ - public void setDecompressingPostProcessor(MessagePostProcessor decompressingPostProcessor) { + public void setDecompressingPostProcessor( + MessagePostProcessor decompressingPostProcessor) { this.decompressingPostProcessor = decompressingPostProcessor; } /** - * Set a {@link org.springframework.amqp.core.MessagePostProcessor} to compress messages. - * Defaults to a {@link org.springframework.amqp.support.postprocessor.GZipPostProcessor}. + * Set a {@link org.springframework.amqp.core.MessagePostProcessor} to compress + * messages. Defaults to a + * {@link org.springframework.amqp.support.postprocessor.GZipPostProcessor}. * @param compressingPostProcessor the post processor. */ - public void setCompressingPostProcessor(MessagePostProcessor compressingPostProcessor) { + public void setCompressingPostProcessor( + MessagePostProcessor compressingPostProcessor) { this.compressingPostProcessor = compressingPostProcessor; } @@ -203,7 +206,8 @@ public class RabbitMessageChannelBinder this.clustered = nodes.length > 1; } - public void setExtendedBindingProperties(RabbitExtendedBindingProperties extendedBindingProperties) { + public void setExtendedBindingProperties( + RabbitExtendedBindingProperties extendedBindingProperties) { this.extendedBindingProperties = extendedBindingProperties; } @@ -211,16 +215,21 @@ public class RabbitMessageChannelBinder public void onInit() throws Exception { super.onInit(); if (this.clustered) { - String[] addresses = StringUtils.commaDelimitedListToStringArray(this.rabbitProperties.getAddresses()); + String[] addresses = StringUtils.commaDelimitedListToStringArray( + this.rabbitProperties.getAddresses()); - Assert.state(addresses.length == this.adminAddresses.length - && addresses.length == this.nodes.length, + Assert.state( + addresses.length == this.adminAddresses.length + && addresses.length == this.nodes.length, "'addresses', 'adminAddresses', and 'nodes' properties must have equal length"); - this.connectionFactory = new LocalizedQueueConnectionFactory(this.connectionFactory, addresses, - this.adminAddresses, this.nodes, this.rabbitProperties.getVirtualHost(), - this.rabbitProperties.getUsername(), this.rabbitProperties.getPassword(), - this.rabbitProperties.getSsl().isEnabled(), this.rabbitProperties.getSsl().getKeyStore(), + this.connectionFactory = new LocalizedQueueConnectionFactory( + this.connectionFactory, addresses, this.adminAddresses, this.nodes, + this.rabbitProperties.getVirtualHost(), + this.rabbitProperties.getUsername(), + this.rabbitProperties.getPassword(), + this.rabbitProperties.getSsl().isEnabled(), + this.rabbitProperties.getSsl().getKeyStore(), this.rabbitProperties.getSsl().getTrustStore(), this.rabbitProperties.getSsl().getKeyStorePassword(), this.rabbitProperties.getSsl().getTrustStorePassword()); @@ -258,18 +267,24 @@ public class RabbitMessageChannelBinder } @Override - protected MessageHandler createProducerMessageHandler(final ProducerDestination producerDestination, - ExtendedProducerProperties producerProperties, MessageChannel errorChannel) { - Assert.state(!HeaderMode.embeddedHeaders.equals(producerProperties.getHeaderMode()), + protected MessageHandler createProducerMessageHandler( + final ProducerDestination producerDestination, + ExtendedProducerProperties producerProperties, + MessageChannel errorChannel) { + Assert.state( + !HeaderMode.embeddedHeaders.equals(producerProperties.getHeaderMode()), "the RabbitMQ binder does not support embedded headers since RabbitMQ supports headers natively"); String prefix = producerProperties.getExtension().getPrefix(); String exchangeName = producerDestination.getName(); - String destination = StringUtils.isEmpty(prefix) ? exchangeName : exchangeName.substring(prefix.length()); + String destination = StringUtils.isEmpty(prefix) ? exchangeName + : exchangeName.substring(prefix.length()); final AmqpOutboundEndpoint endpoint = new AmqpOutboundEndpoint( - buildRabbitTemplate(producerProperties.getExtension(), errorChannel != null)); + buildRabbitTemplate(producerProperties.getExtension(), + errorChannel != null)); endpoint.setExchangeName(producerDestination.getName()); RabbitProducerProperties extendedProperties = producerProperties.getExtension(); - boolean expressionInterceptorNeeded = expressionInterceptorNeeded(extendedProperties); + boolean expressionInterceptorNeeded = expressionInterceptorNeeded( + extendedProperties); Expression routingKeyExpression = extendedProperties.getRoutingKeyExpression(); if (!producerProperties.isPartitioned()) { if (routingKeyExpression == null) { @@ -278,7 +293,8 @@ public class RabbitMessageChannelBinder else { if (expressionInterceptorNeeded) { endpoint.setRoutingKeyExpressionString("headers['" - + RabbitExpressionEvaluatingInterceptor.ROUTING_KEY_HEADER + "']"); + + RabbitExpressionEvaluatingInterceptor.ROUTING_KEY_HEADER + + "']"); } else { endpoint.setRoutingKeyExpression(routingKeyExpression); @@ -287,16 +303,19 @@ public class RabbitMessageChannelBinder } else { if (routingKeyExpression == null) { - endpoint.setRoutingKeyExpression(buildPartitionRoutingExpression(destination, false)); + endpoint.setRoutingKeyExpression( + buildPartitionRoutingExpression(destination, false)); } else { if (expressionInterceptorNeeded) { - endpoint.setRoutingKeyExpression(buildPartitionRoutingExpression("headers['" - + RabbitExpressionEvaluatingInterceptor.ROUTING_KEY_HEADER + "']", true)); + endpoint.setRoutingKeyExpression( + buildPartitionRoutingExpression("headers['" + + RabbitExpressionEvaluatingInterceptor.ROUTING_KEY_HEADER + + "']", true)); } else { - endpoint.setRoutingKeyExpression(buildPartitionRoutingExpression(routingKeyExpression.getExpressionString(), - true)); + endpoint.setRoutingKeyExpression(buildPartitionRoutingExpression( + routingKeyExpression.getExpressionString(), true)); } } } @@ -310,10 +329,12 @@ public class RabbitMessageChannelBinder } } DefaultAmqpHeaderMapper mapper = DefaultAmqpHeaderMapper.outboundMapper(); - List headerPatterns = new ArrayList<>(extendedProperties.getHeaderPatterns().length + 1); + List headerPatterns = new ArrayList<>( + extendedProperties.getHeaderPatterns().length + 1); headerPatterns.add("!" + BinderHeaders.PARTITION_HEADER); headerPatterns.addAll(Arrays.asList(extendedProperties.getHeaderPatterns())); - mapper.setRequestHeaderNames(headerPatterns.toArray(new String[headerPatterns.size()])); + mapper.setRequestHeaderNames( + headerPatterns.toArray(new String[headerPatterns.size()])); endpoint.setHeaderMapper(mapper); endpoint.setDefaultDeliveryMode(extendedProperties.getDeliveryMode()); endpoint.setBeanFactory(this.getBeanFactory()); @@ -321,13 +342,15 @@ public class RabbitMessageChannelBinder checkConnectionFactoryIsErrorCapable(); endpoint.setReturnChannel(errorChannel); endpoint.setConfirmNackChannel(errorChannel); - String ackChannelBeanName = StringUtils.hasText(extendedProperties.getConfirmAckChannel()) - ? extendedProperties.getConfirmAckChannel() - : IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME; + String ackChannelBeanName = StringUtils + .hasText(extendedProperties.getConfirmAckChannel()) + ? extendedProperties.getConfirmAckChannel() + : IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME; if (!ackChannelBeanName.equals(IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME) && !getApplicationContext().containsBean(ackChannelBeanName)) { GenericApplicationContext context = (GenericApplicationContext) getApplicationContext(); - context.registerBean(ackChannelBeanName, DirectChannel.class, () -> new DirectChannel()); + context.registerBean(ackChannelBeanName, DirectChannel.class, + () -> new DirectChannel()); } endpoint.setConfirmAckChannelName(ackChannelBeanName); endpoint.setConfirmCorrelationExpressionString("#root"); @@ -337,110 +360,134 @@ public class RabbitMessageChannelBinder return endpoint; } - @Override protected void postProcessOutputChannel(MessageChannel outputChannel, ExtendedProducerProperties producerProperties) { RabbitProducerProperties extendedProperties = producerProperties.getExtension(); if (expressionInterceptorNeeded(extendedProperties)) { ((AbstractMessageChannel) outputChannel).addInterceptor(0, - new RabbitExpressionEvaluatingInterceptor(extendedProperties.getRoutingKeyExpression(), - extendedProperties.getDelayExpression(), getEvaluationContext())); + new RabbitExpressionEvaluatingInterceptor( + extendedProperties.getRoutingKeyExpression(), + extendedProperties.getDelayExpression(), + getEvaluationContext())); } } - private boolean expressionInterceptorNeeded(RabbitProducerProperties extendedProperties) { + private boolean expressionInterceptorNeeded( + RabbitProducerProperties extendedProperties) { return extendedProperties.getRoutingKeyExpression() != null - && extendedProperties.getRoutingKeyExpression().getExpressionString().contains("payload") - || (extendedProperties.getDelayExpression() != null - && extendedProperties.getDelayExpression().getExpressionString().contains("payload")); + && extendedProperties.getRoutingKeyExpression().getExpressionString() + .contains("payload") + || (extendedProperties.getDelayExpression() != null && extendedProperties + .getDelayExpression().getExpressionString().contains("payload")); } private void checkConnectionFactoryIsErrorCapable() { if (!(this.connectionFactory instanceof CachingConnectionFactory)) { - logger.warn("Unknown connection factory type, cannot determine error capabilities: " - + this.connectionFactory.getClass()); + logger.warn( + "Unknown connection factory type, cannot determine error capabilities: " + + this.connectionFactory.getClass()); } else { CachingConnectionFactory ccf = (CachingConnectionFactory) this.connectionFactory; if (!ccf.isPublisherConfirms() && !ccf.isPublisherReturns()) { - logger.warn("Producer error channel is enabled, but the connection factory is not configured for " - + "returns or confirms; the error channel will receive no messages"); + logger.warn( + "Producer error channel is enabled, but the connection factory is not configured for " + + "returns or confirms; the error channel will receive no messages"); } else if (!ccf.isPublisherConfirms()) { - logger.info("Producer error channel is enabled, but the connection factory is only configured to " - + "handle returned messages; negative acks will not be reported"); + logger.info( + "Producer error channel is enabled, but the connection factory is only configured to " + + "handle returned messages; negative acks will not be reported"); } else if (!ccf.isPublisherReturns()) { - logger.info("Producer error channel is enabled, but the connection factory is only configured to " - + "handle negatively acked messages; returned messages will not be reported"); + logger.info( + "Producer error channel is enabled, but the connection factory is only configured to " + + "handle negatively acked messages; returned messages will not be reported"); } } } - private Expression buildPartitionRoutingExpression(String expressionRoot, boolean rootIsExpression) { + private Expression buildPartitionRoutingExpression(String expressionRoot, + boolean rootIsExpression) { String partitionRoutingExpression = rootIsExpression - ? expressionRoot + " + '-' + headers['" + BinderHeaders.PARTITION_HEADER + "']" - : "'" + expressionRoot + "-' + headers['" + BinderHeaders.PARTITION_HEADER + "']"; + ? expressionRoot + " + '-' + headers['" + BinderHeaders.PARTITION_HEADER + + "']" + : "'" + expressionRoot + "-' + headers['" + BinderHeaders.PARTITION_HEADER + + "']"; return new SpelExpressionParser().parseExpression(partitionRoutingExpression); } @Override - protected MessageProducer createConsumerEndpoint(ConsumerDestination consumerDestination, String group, + protected MessageProducer createConsumerEndpoint( + ConsumerDestination consumerDestination, String group, ExtendedConsumerProperties properties) { Assert.state(!HeaderMode.embeddedHeaders.equals(properties.getHeaderMode()), "the RabbitMQ binder does not support embedded headers since RabbitMQ supports headers natively"); String destination = consumerDestination.getName(); - boolean directContainer = properties.getExtension().getContainerType().equals(ContainerType.DIRECT); + boolean directContainer = properties.getExtension().getContainerType() + .equals(ContainerType.DIRECT); AbstractMessageListenerContainer listenerContainer = directContainer ? new DirectMessageListenerContainer(this.connectionFactory) : new SimpleMessageListenerContainer(this.connectionFactory); - listenerContainer.setAcknowledgeMode(properties.getExtension().getAcknowledgeMode()); + listenerContainer + .setAcknowledgeMode(properties.getExtension().getAcknowledgeMode()); listenerContainer.setChannelTransacted(properties.getExtension().isTransacted()); - listenerContainer.setDefaultRequeueRejected(properties.getExtension().isRequeueRejected()); + listenerContainer + .setDefaultRequeueRejected(properties.getExtension().isRequeueRejected()); int concurrency = properties.getConcurrency(); concurrency = concurrency > 0 ? concurrency : 1; if (directContainer) { - setDMLCProperties(properties, (DirectMessageListenerContainer) listenerContainer, concurrency); + setDMLCProperties(properties, + (DirectMessageListenerContainer) listenerContainer, concurrency); } else { - setSMLCProperties(properties, (SimpleMessageListenerContainer) listenerContainer, concurrency); + setSMLCProperties(properties, + (SimpleMessageListenerContainer) listenerContainer, concurrency); } listenerContainer.setPrefetchCount(properties.getExtension().getPrefetch()); - listenerContainer.setRecoveryInterval(properties.getExtension().getRecoveryInterval()); - listenerContainer.setTaskExecutor(new SimpleAsyncTaskExecutor(consumerDestination.getName() + "-")); + listenerContainer + .setRecoveryInterval(properties.getExtension().getRecoveryInterval()); + listenerContainer.setTaskExecutor( + new SimpleAsyncTaskExecutor(consumerDestination.getName() + "-")); String[] queues = StringUtils.tokenizeToStringArray(destination, ",", true, true); listenerContainer.setQueueNames(queues); listenerContainer.setAfterReceivePostProcessors(this.decompressingPostProcessor); listenerContainer.setMessagePropertiesConverter( RabbitMessageChannelBinder.inboundMessagePropertiesConverter); listenerContainer.setExclusive(properties.getExtension().isExclusive()); - listenerContainer.setMissingQueuesFatal(properties.getExtension().getMissingQueuesFatal()); + listenerContainer + .setMissingQueuesFatal(properties.getExtension().getMissingQueuesFatal()); if (properties.getExtension().getFailedDeclarationRetryInterval() != null) { listenerContainer.setFailedDeclarationRetryInterval( properties.getExtension().getFailedDeclarationRetryInterval()); } if (getApplicationEventPublisher() != null) { - listenerContainer.setApplicationEventPublisher(getApplicationEventPublisher()); + listenerContainer + .setApplicationEventPublisher(getApplicationEventPublisher()); } else if (getApplicationContext() != null) { listenerContainer.setApplicationEventPublisher(getApplicationContext()); } - getContainerCustomizer().configure(listenerContainer, consumerDestination.getName(), group); + getContainerCustomizer().configure(listenerContainer, + consumerDestination.getName(), group); if (StringUtils.hasText(properties.getExtension().getConsumerTagPrefix())) { final AtomicInteger index = new AtomicInteger(); - listenerContainer.setConsumerTagStrategy(q -> - properties.getExtension().getConsumerTagPrefix() + "#" + index.getAndIncrement()); + listenerContainer.setConsumerTagStrategy( + q -> properties.getExtension().getConsumerTagPrefix() + "#" + + index.getAndIncrement()); } listenerContainer.afterPropertiesSet(); - AmqpInboundChannelAdapter adapter = new AmqpInboundChannelAdapter(listenerContainer); + AmqpInboundChannelAdapter adapter = new AmqpInboundChannelAdapter( + listenerContainer); adapter.setBeanFactory(this.getBeanFactory()); adapter.setBeanName("inbound." + destination); DefaultAmqpHeaderMapper mapper = DefaultAmqpHeaderMapper.inboundMapper(); mapper.setRequestHeaderNames(properties.getExtension().getHeaderPatterns()); adapter.setHeaderMapper(mapper); - ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure(consumerDestination, group, properties); + ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure( + consumerDestination, group, properties); if (properties.getMaxAttempts() > 1) { adapter.setRetryTemplate(buildRetryTemplate(properties)); adapter.setRecoveryCallback(errorInfrastructure.getRecoverer()); @@ -453,7 +500,8 @@ public class RabbitMessageChannelBinder return adapter; } - private void setSMLCProperties(ExtendedConsumerProperties properties, + private void setSMLCProperties( + ExtendedConsumerProperties properties, SimpleMessageListenerContainer listenerContainer, int concurrency) { listenerContainer.setConcurrentConsumers(concurrency); @@ -463,42 +511,51 @@ public class RabbitMessageChannelBinder } listenerContainer.setTxSize(properties.getExtension().getTxSize()); if (properties.getExtension().getQueueDeclarationRetries() != null) { - listenerContainer.setDeclarationRetries(properties.getExtension().getQueueDeclarationRetries()); + listenerContainer.setDeclarationRetries( + properties.getExtension().getQueueDeclarationRetries()); } } - private void setDMLCProperties(ExtendedConsumerProperties properties, + private void setDMLCProperties( + ExtendedConsumerProperties properties, DirectMessageListenerContainer listenerContainer, int concurrency) { listenerContainer.setConsumersPerQueue(concurrency); if (properties.getExtension().getMaxConcurrency() > concurrency) { - this.logger.warn("maxConcurrency is not supported with a direct container type"); + this.logger + .warn("maxConcurrency is not supported with a direct container type"); } if (properties.getExtension().getTxSize() > 1) { this.logger.warn("txSize is not supported with a direct container type"); } if (properties.getExtension().getQueueDeclarationRetries() != null) { - this.logger.warn("queueDeclarationRetries is not supported with a direct container type"); + this.logger.warn( + "queueDeclarationRetries is not supported with a direct container type"); } } @Override - protected PolledConsumerResources createPolledConsumerResources(String name, String group, ConsumerDestination destination, + protected PolledConsumerResources createPolledConsumerResources(String name, + String group, ConsumerDestination destination, ExtendedConsumerProperties consumerProperties) { Assert.isTrue(!consumerProperties.isMultiplex(), "The Spring Integration polled MessageSource does not currently support muiltiple queues"); - AmqpMessageSource source = new AmqpMessageSource(this.connectionFactory, destination.getName()); + AmqpMessageSource source = new AmqpMessageSource(this.connectionFactory, + destination.getName()); source.setRawMessageHeader(true); - return new PolledConsumerResources(source, - registerErrorInfrastructure(destination, group, consumerProperties, true)); + return new PolledConsumerResources(source, registerErrorInfrastructure( + destination, group, consumerProperties, true)); } @Override protected void postProcessPollableSource(DefaultPollableMessageSource bindingTarget) { bindingTarget.setAttributesProvider((accessor, message) -> { - Object rawMessage = message.getHeaders().get(AmqpMessageHeaderErrorMessageStrategy.AMQP_RAW_MESSAGE); + Object rawMessage = message.getHeaders() + .get(AmqpMessageHeaderErrorMessageStrategy.AMQP_RAW_MESSAGE); if (rawMessage != null) { - accessor.setAttribute(AmqpMessageHeaderErrorMessageStrategy.AMQP_RAW_MESSAGE, rawMessage); + accessor.setAttribute( + AmqpMessageHeaderErrorMessageStrategy.AMQP_RAW_MESSAGE, + rawMessage); } }); } @@ -509,7 +566,8 @@ public class RabbitMessageChannelBinder } @Override - protected MessageHandler getErrorMessageHandler(ConsumerDestination destination, String group, + protected MessageHandler getErrorMessageHandler(ConsumerDestination destination, + String group, final ExtendedConsumerProperties properties) { if (properties.getExtension().isRepublishToDlq()) { return new MessageHandler() { @@ -521,21 +579,26 @@ public class RabbitMessageChannelBinder this.template.setUsePublisherConnection(true); } - private final String exchange = deadLetterExchangeName(properties.getExtension()); + private final String exchange = deadLetterExchangeName( + properties.getExtension()); - private final String routingKey = properties.getExtension().getDeadLetterRoutingKey(); + private final String routingKey = properties.getExtension() + .getDeadLetterRoutingKey(); - private final int frameMaxHeadroom = properties.getExtension().getFrameMaxHeadroom(); + private final int frameMaxHeadroom = properties.getExtension() + .getFrameMaxHeadroom(); private int maxStackTraceLength = -1; @Override - public void handleMessage(org.springframework.messaging.Message message) throws MessagingException { + public void handleMessage( + org.springframework.messaging.Message message) + throws MessagingException { Message amqpMessage = (Message) message.getHeaders() .get(AmqpMessageHeaderErrorMessageStrategy.AMQP_RAW_MESSAGE); if (!(message instanceof ErrorMessage)) { - logger.error("Expected an ErrorMessage, not a " + message.getClass().toString() + " for: " - + message); + logger.error("Expected an ErrorMessage, not a " + + message.getClass().toString() + " for: " + message); } else if (amqpMessage == null) { logger.error("No raw message header in " + message); @@ -548,34 +611,44 @@ public class RabbitMessageChannelBinder } return; } - MessageProperties messageProperties = amqpMessage.getMessageProperties(); + MessageProperties messageProperties = amqpMessage + .getMessageProperties(); Map headers = messageProperties.getHeaders(); String stackTraceAsString = getStackTraceAsString(cause); if (this.maxStackTraceLength < 0) { int rabbitMaxStackTraceLength = RabbitUtils .getMaxFrame(this.template.getConnectionFactory()); if (rabbitMaxStackTraceLength > 0) { - //maxStackTraceLength -= this.frameMaxHeadroom; - this.maxStackTraceLength = rabbitMaxStackTraceLength - this.frameMaxHeadroom; + // maxStackTraceLength -= this.frameMaxHeadroom; + this.maxStackTraceLength = rabbitMaxStackTraceLength + - this.frameMaxHeadroom; } } - if (this.maxStackTraceLength > 0 && stackTraceAsString.length() > this.maxStackTraceLength) { - stackTraceAsString = stackTraceAsString.substring(0, this.maxStackTraceLength); - logger.warn("Stack trace in republished message header truncated due to frame_max limitations; " - + "consider increasing frame_max on the broker or reduce the stack trace depth", cause); + if (this.maxStackTraceLength > 0 && stackTraceAsString + .length() > this.maxStackTraceLength) { + stackTraceAsString = stackTraceAsString.substring(0, + this.maxStackTraceLength); + logger.warn( + "Stack trace in republished message header truncated due to frame_max limitations; " + + "consider increasing frame_max on the broker or reduce the stack trace depth", + cause); } - headers.put(RepublishMessageRecoverer.X_EXCEPTION_STACKTRACE, stackTraceAsString); + headers.put(RepublishMessageRecoverer.X_EXCEPTION_STACKTRACE, + stackTraceAsString); headers.put(RepublishMessageRecoverer.X_EXCEPTION_MESSAGE, - cause.getCause() != null ? cause.getCause().getMessage() : cause.getMessage()); + cause.getCause() != null ? cause.getCause().getMessage() + : cause.getMessage()); headers.put(RepublishMessageRecoverer.X_ORIGINAL_EXCHANGE, messageProperties.getReceivedExchange()); headers.put(RepublishMessageRecoverer.X_ORIGINAL_ROUTING_KEY, messageProperties.getReceivedRoutingKey()); if (properties.getExtension().getRepublishDeliveyMode() != null) { - messageProperties.setDeliveryMode(properties.getExtension().getRepublishDeliveyMode()); + messageProperties.setDeliveryMode( + properties.getExtension().getRepublishDeliveyMode()); } this.template.send(this.exchange, - this.routingKey != null ? this.routingKey : messageProperties.getConsumerQueue(), + this.routingKey != null ? this.routingKey + : messageProperties.getConsumerQueue(), amqpMessage); } } @@ -589,8 +662,9 @@ public class RabbitMessageChannelBinder */ private boolean shouldRepublish(Throwable throwable) { Throwable cause = throwable; - while (cause != null && !(cause instanceof AmqpRejectAndDontRequeueException) - && !(cause instanceof ImmediateAcknowledgeAmqpException)) { + while (cause != null + && !(cause instanceof AmqpRejectAndDontRequeueException) + && !(cause instanceof ImmediateAcknowledgeAmqpException)) { cause = cause.getCause(); } return !(cause instanceof ImmediateAcknowledgeAmqpException); @@ -603,29 +677,35 @@ public class RabbitMessageChannelBinder private final RejectAndDontRequeueRecoverer recoverer = new RejectAndDontRequeueRecoverer(); @Override - public void handleMessage(org.springframework.messaging.Message message) throws MessagingException { + public void handleMessage( + org.springframework.messaging.Message message) + throws MessagingException { Message amqpMessage = (Message) message.getHeaders() .get(AmqpMessageHeaderErrorMessageStrategy.AMQP_RAW_MESSAGE); /* - * NOTE: The following IF and subsequent ELSE IF should never happen under normal interaction and - * it should always go to the last ELSE - * However, given that this is a handler subscribing to the public channel and that we can't control what - * type of Message may be sent to that channel (user decides to send a Message manually) the 'IF/ELSE IF' provides - * a safety net to handle any message properly. + * NOTE: The following IF and subsequent ELSE IF should never happen + * under normal interaction and it should always go to the last ELSE + * However, given that this is a handler subscribing to the public + * channel and that we can't control what type of Message may be sent + * to that channel (user decides to send a Message manually) the + * 'IF/ELSE IF' provides a safety net to handle any message properly. */ if (!(message instanceof ErrorMessage)) { - logger.error("Expected an ErrorMessage, not a " + message.getClass().toString() + " for: " - + message); - throw new ListenerExecutionFailedException("Unexpected error message " + message, + logger.error("Expected an ErrorMessage, not a " + + message.getClass().toString() + " for: " + message); + throw new ListenerExecutionFailedException( + "Unexpected error message " + message, new AmqpRejectAndDontRequeueException(""), null); } else if (amqpMessage == null) { logger.error("No raw message header in " + message); - throw new ListenerExecutionFailedException("Unexpected error message " + message, + throw new ListenerExecutionFailedException( + "Unexpected error message " + message, new AmqpRejectAndDontRequeueException(""), amqpMessage); } else { - this.recoverer.recover(amqpMessage, (Throwable) message.getPayload()); + this.recoverer.recover(amqpMessage, + (Throwable) message.getPayload()); } } @@ -636,21 +716,22 @@ public class RabbitMessageChannelBinder } } - @Override - protected MessageHandler getPolledConsumerErrorMessageHandler(ConsumerDestination destination, String group, + protected MessageHandler getPolledConsumerErrorMessageHandler( + ConsumerDestination destination, String group, ExtendedConsumerProperties properties) { MessageHandler handler = getErrorMessageHandler(destination, group, properties); if (handler != null) { return handler; } - final MessageHandler superHandler = super.getErrorMessageHandler(destination, group, properties); + final MessageHandler superHandler = super.getErrorMessageHandler(destination, + group, properties); return message -> { Message amqpMessage = (Message) message.getHeaders() .get(AmqpMessageHeaderErrorMessageStrategy.AMQP_RAW_MESSAGE); if (!(message instanceof ErrorMessage)) { - logger.error("Expected an ErrorMessage, not a " + message.getClass().toString() + " for: " - + message); + logger.error("Expected an ErrorMessage, not a " + + message.getClass().toString() + " for: " + message); } else if (amqpMessage == null) { if (superHandler != null) { @@ -659,8 +740,10 @@ public class RabbitMessageChannelBinder } else { if (message.getPayload() instanceof MessagingException) { - AcknowledgmentCallback ack = StaticMessageHeaderAccessor.getAcknowledgmentCallback( - ((MessagingException) message.getPayload()).getFailedMessage()); + AcknowledgmentCallback ack = StaticMessageHeaderAccessor + .getAcknowledgmentCallback( + ((MessagingException) message.getPayload()) + .getFailedMessage()); if (ack != null) { if (properties.getExtension().isRequeueRejected()) { ack.acknowledge(Status.REQUEUE); @@ -682,7 +765,8 @@ public class RabbitMessageChannelBinder private String deadLetterExchangeName(RabbitCommonProperties properties) { if (properties.getDeadLetterExchange() == null) { - return applyPrefix(properties.getPrefix(), RabbitCommonProperties.DEAD_LETTER_EXCHANGE); + return applyPrefix(properties.getPrefix(), + RabbitCommonProperties.DEAD_LETTER_EXCHANGE); } else { return properties.getDeadLetterExchange(); @@ -690,20 +774,23 @@ public class RabbitMessageChannelBinder } @Override - protected void afterUnbindConsumer(ConsumerDestination consumerDestination, String group, + protected void afterUnbindConsumer(ConsumerDestination consumerDestination, + String group, ExtendedConsumerProperties consumerProperties) { - provisioningProvider.cleanAutoDeclareContext(consumerDestination, consumerProperties); + provisioningProvider.cleanAutoDeclareContext(consumerDestination, + consumerProperties); } - private RabbitTemplate buildRabbitTemplate(RabbitProducerProperties properties, boolean mandatory) { + private RabbitTemplate buildRabbitTemplate(RabbitProducerProperties properties, + boolean mandatory) { RabbitTemplate rabbitTemplate; if (properties.isBatchingEnabled()) { BatchingStrategy batchingStrategy = new SimpleBatchingStrategy( - properties.getBatchSize(), - properties.getBatchBufferLimit(), + properties.getBatchSize(), properties.getBatchBufferLimit(), properties.getBatchTimeout()); rabbitTemplate = new BatchingRabbitTemplate(batchingStrategy, - getApplicationContext().getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, + getApplicationContext().getBean( + IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, TaskScheduler.class)); } else { @@ -717,7 +804,8 @@ public class RabbitMessageChannelBinder rabbitTemplate.setBeforePublishPostProcessors(this.compressingPostProcessor); } rabbitTemplate.setMandatory(mandatory); // returned messages - if (rabbitProperties != null && rabbitProperties.getTemplate().getRetry().isEnabled()) { + if (rabbitProperties != null + && rabbitProperties.getTemplate().getRetry().isEnabled()) { Retry retry = rabbitProperties.getTemplate().getRetry(); RetryPolicy retryPolicy = new SimpleRetryPolicy(retry.getMaxAttempts()); ExponentialBackOffPolicy backOff = new ExponentialBackOffPolicy(); @@ -740,7 +828,8 @@ public class RabbitMessageChannelBinder return stringWriter.getBuffer().toString(); } - private static final class SimplePassthroughMessageConverter extends AbstractMessageConverter { + private static final class SimplePassthroughMessageConverter + extends AbstractMessageConverter { private static final SimpleMessageConverter converter = new SimpleMessageConverter(); @@ -749,7 +838,8 @@ public class RabbitMessageChannelBinder } @Override - protected Message createMessage(Object object, MessageProperties messageProperties) { + protected Message createMessage(Object object, + MessageProperties messageProperties) { if (object instanceof byte[]) { return new Message((byte[]) object, messageProperties); } diff --git a/spring-cloud-stream-binder-rabbit/src/main/java/org/springframework/cloud/stream/binder/rabbit/config/ExtendedBindingHandlerMappingsProviderConfiguration.java b/spring-cloud-stream-binder-rabbit/src/main/java/org/springframework/cloud/stream/binder/rabbit/config/ExtendedBindingHandlerMappingsProviderConfiguration.java index 467f8fcd6..7bd9d4a3b 100644 --- a/spring-cloud-stream-binder-rabbit/src/main/java/org/springframework/cloud/stream/binder/rabbit/config/ExtendedBindingHandlerMappingsProviderConfiguration.java +++ b/spring-cloud-stream-binder-rabbit/src/main/java/org/springframework/cloud/stream/binder/rabbit/config/ExtendedBindingHandlerMappingsProviderConfiguration.java @@ -25,20 +25,21 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** - * * @author Oleg Zhurakousky * */ @Configuration -public class ExtendedBindingHandlerMappingsProviderConfiguration { +public class ExtendedBindingHandlerMappingsProviderConfiguration { @Bean public MappingsProvider rabbitExtendedPropertiesDefaultMappingsProvider() { return () -> { Map mappings = new HashMap<>(); - mappings.put(ConfigurationPropertyName.of("spring.cloud.stream.rabbit.bindings"), + mappings.put( + ConfigurationPropertyName.of("spring.cloud.stream.rabbit.bindings"), ConfigurationPropertyName.of("spring.cloud.stream.rabbit.default")); return mappings; }; } + } diff --git a/spring-cloud-stream-binder-rabbit/src/main/java/org/springframework/cloud/stream/binder/rabbit/config/RabbitMessageChannelBinderConfiguration.java b/spring-cloud-stream-binder-rabbit/src/main/java/org/springframework/cloud/stream/binder/rabbit/config/RabbitMessageChannelBinderConfiguration.java index 8fd0ab6cf..bd18afb97 100644 --- a/spring-cloud-stream-binder-rabbit/src/main/java/org/springframework/cloud/stream/binder/rabbit/config/RabbitMessageChannelBinderConfiguration.java +++ b/spring-cloud-stream-binder-rabbit/src/main/java/org/springframework/cloud/stream/binder/rabbit/config/RabbitMessageChannelBinderConfiguration.java @@ -52,7 +52,8 @@ import org.springframework.lang.Nullable; */ @Configuration @Import({ PropertyPlaceholderAutoConfiguration.class }) -@EnableConfigurationProperties({ RabbitBinderConfigurationProperties.class, RabbitExtendedBindingProperties.class }) +@EnableConfigurationProperties({ RabbitBinderConfigurationProperties.class, + RabbitExtendedBindingProperties.class }) public class RabbitMessageChannelBinderConfiguration { @Autowired @@ -68,10 +69,14 @@ public class RabbitMessageChannelBinderConfiguration { private RabbitExtendedBindingProperties rabbitExtendedBindingProperties; @Bean - RabbitMessageChannelBinder rabbitMessageChannelBinder(@Nullable ListenerContainerCustomizer listenerContainerCustomizer) throws Exception { - RabbitMessageChannelBinder binder = new RabbitMessageChannelBinder(this.rabbitConnectionFactory, - this.rabbitProperties, provisioningProvider(), listenerContainerCustomizer); - binder.setAdminAddresses(this.rabbitBinderConfigurationProperties.getAdminAddresses()); + RabbitMessageChannelBinder rabbitMessageChannelBinder( + @Nullable ListenerContainerCustomizer listenerContainerCustomizer) + throws Exception { + RabbitMessageChannelBinder binder = new RabbitMessageChannelBinder( + this.rabbitConnectionFactory, this.rabbitProperties, + provisioningProvider(), listenerContainerCustomizer); + binder.setAdminAddresses( + this.rabbitBinderConfigurationProperties.getAdminAddresses()); binder.setCompressingPostProcessor(gZipPostProcessor()); binder.setDecompressingPostProcessor(deCompressingPostProcessor()); binder.setNodes(this.rabbitBinderConfigurationProperties.getNodes()); @@ -87,7 +92,8 @@ public class RabbitMessageChannelBinderConfiguration { @Bean MessagePostProcessor gZipPostProcessor() { GZipPostProcessor gZipPostProcessor = new GZipPostProcessor(); - gZipPostProcessor.setLevel(this.rabbitBinderConfigurationProperties.getCompressionLevel()); + gZipPostProcessor + .setLevel(this.rabbitBinderConfigurationProperties.getCompressionLevel()); return gZipPostProcessor; } @@ -101,8 +107,8 @@ public class RabbitMessageChannelBinderConfiguration { @ConditionalOnProperty("spring.cloud.stream.rabbit.binder.connection-name-prefix") public ConnectionNameStrategy connectionNamer(CachingConnectionFactory cf) { final AtomicInteger nameIncrementer = new AtomicInteger(); - ConnectionNameStrategy namer = f -> this.rabbitBinderConfigurationProperties.getConnectionNamePrefix() - + "#" + nameIncrementer.getAndIncrement(); + ConnectionNameStrategy namer = f -> this.rabbitBinderConfigurationProperties + .getConnectionNamePrefix() + "#" + nameIncrementer.getAndIncrement(); // TODO: this can be removed when Boot 2.0.1 wires it in cf.setConnectionNameStrategy(namer); return namer; diff --git a/spring-cloud-stream-binder-rabbit/src/main/java/org/springframework/cloud/stream/binder/rabbit/config/RabbitServiceAutoConfiguration.java b/spring-cloud-stream-binder-rabbit/src/main/java/org/springframework/cloud/stream/binder/rabbit/config/RabbitServiceAutoConfiguration.java index 3b8bd9151..93b7f4e44 100644 --- a/spring-cloud-stream-binder-rabbit/src/main/java/org/springframework/cloud/stream/binder/rabbit/config/RabbitServiceAutoConfiguration.java +++ b/spring-cloud-stream-binder-rabbit/src/main/java/org/springframework/cloud/stream/binder/rabbit/config/RabbitServiceAutoConfiguration.java @@ -68,8 +68,8 @@ public class RabbitServiceAutoConfiguration { protected static class CloudProfile { /** - * Configuration to be used when the cloud profile is set, and Cloud Connectors are found - * on the classpath. + * Configuration to be used when the cloud profile is set, and Cloud Connectors + * are found on the classpath. */ @Configuration @ConditionalOnClass(Cloud.class) @@ -82,8 +82,8 @@ public class RabbitServiceAutoConfiguration { } /** - * Active only if {@code spring.cloud.stream.override-cloud-connectors} is not set to - * {@code true}. + * Active only if {@code spring.cloud.stream.override-cloud-connectors} is not + * set to {@code true}. */ @Configuration @ConditionalOnProperty(value = "spring.cloud.stream.override-cloud-connectors", havingValue = "false", matchIfMissing = true) @@ -94,7 +94,8 @@ public class RabbitServiceAutoConfiguration { protected static class UseCloudConnectors { /** - * Creates a {@link ConnectionFactory} using the singleton service connector. + * Creates a {@link ConnectionFactory} using the singleton service + * connector. * @param cloud {@link Cloud} instance to be used for accessing services. * @param connectorConfigObjectProvider the {@link ObjectProvider} for the * {@link RabbitConnectionFactoryConfig}. @@ -107,10 +108,12 @@ public class RabbitServiceAutoConfiguration { ConfigurableApplicationContext applicationContext, RabbitProperties rabbitProperties) throws Exception { - ConnectionFactory connectionFactory = cloud.getSingletonServiceConnector(ConnectionFactory.class, - connectorConfigObjectProvider.getIfUnique()); + ConnectionFactory connectionFactory = cloud + .getSingletonServiceConnector(ConnectionFactory.class, + connectorConfigObjectProvider.getIfUnique()); - configureCachingConnectionFactory((CachingConnectionFactory) connectionFactory, + configureCachingConnectionFactory( + (CachingConnectionFactory) connectionFactory, applicationContext, rabbitProperties); return connectionFactory; @@ -121,11 +124,13 @@ public class RabbitServiceAutoConfiguration { RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) { return new RabbitTemplate(connectionFactory); } + } /** - * Configuration to be used if {@code spring.cloud.stream.override-cloud-connectors} is set - * to {@code true}. Defers to Spring Boot auto-configuration. + * Configuration to be used if + * {@code spring.cloud.stream.override-cloud-connectors} is set to + * {@code true}. Defers to Spring Boot auto-configuration. */ @Configuration @ConditionalOnProperty("spring.cloud.stream.override-cloud-connectors") @@ -153,6 +158,7 @@ public class RabbitServiceAutoConfiguration { @Profile("!cloud") @Import(RabbitAutoConfiguration.class) protected static class NoCloudProfile { + } @Configuration @@ -166,8 +172,10 @@ public class RabbitServiceAutoConfiguration { } - static void configureCachingConnectionFactory(CachingConnectionFactory connectionFactory, - ConfigurableApplicationContext applicationContext, RabbitProperties rabbitProperties) throws Exception { + static void configureCachingConnectionFactory( + CachingConnectionFactory connectionFactory, + ConfigurableApplicationContext applicationContext, + RabbitProperties rabbitProperties) throws Exception { if (StringUtils.hasText(rabbitProperties.getAddresses())) { connectionFactory.setAddresses(rabbitProperties.determineAddresses()); @@ -176,18 +184,20 @@ public class RabbitServiceAutoConfiguration { connectionFactory.setPublisherConfirms(rabbitProperties.isPublisherConfirms()); connectionFactory.setPublisherReturns(rabbitProperties.isPublisherReturns()); if (rabbitProperties.getCache().getChannel().getSize() != null) { - connectionFactory.setChannelCacheSize(rabbitProperties.getCache().getChannel().getSize()); + connectionFactory.setChannelCacheSize( + rabbitProperties.getCache().getChannel().getSize()); } if (rabbitProperties.getCache().getConnection().getMode() != null) { - connectionFactory.setCacheMode(rabbitProperties.getCache().getConnection().getMode()); + connectionFactory + .setCacheMode(rabbitProperties.getCache().getConnection().getMode()); } if (rabbitProperties.getCache().getConnection().getSize() != null) { connectionFactory.setConnectionCacheSize( rabbitProperties.getCache().getConnection().getSize()); } if (rabbitProperties.getCache().getChannel().getCheckoutTimeout() != null) { - connectionFactory.setChannelCheckoutTimeout( - rabbitProperties.getCache().getChannel().getCheckoutTimeout().toMillis()); + connectionFactory.setChannelCheckoutTimeout(rabbitProperties.getCache() + .getChannel().getCheckoutTimeout().toMillis()); } connectionFactory.setApplicationContext(applicationContext); applicationContext.addApplicationListener(connectionFactory); diff --git a/spring-cloud-stream-binder-rabbit/src/test/java/org/springframework/cloud/stream/binder/rabbit/LocalizedQueueConnectionFactoryIntegrationTests.java b/spring-cloud-stream-binder-rabbit/src/test/java/org/springframework/cloud/stream/binder/rabbit/LocalizedQueueConnectionFactoryIntegrationTests.java index 06ceff18a..012d5f65b 100644 --- a/spring-cloud-stream-binder-rabbit/src/test/java/org/springframework/cloud/stream/binder/rabbit/LocalizedQueueConnectionFactoryIntegrationTests.java +++ b/spring-cloud-stream-binder-rabbit/src/test/java/org/springframework/cloud/stream/binder/rabbit/LocalizedQueueConnectionFactoryIntegrationTests.java @@ -32,9 +32,7 @@ import org.springframework.cloud.stream.binder.test.junit.rabbit.RabbitTestSuppo import static org.assertj.core.api.Assertions.assertThat; - /** - * * @author Gary Russell */ public class LocalizedQueueConnectionFactoryIntegrationTests { @@ -48,13 +46,15 @@ public class LocalizedQueueConnectionFactoryIntegrationTests { public void setup() { ConnectionFactory defaultConnectionFactory = rabbitAvailableRule.getResource(); String[] addresses = new String[] { "localhost:9999", "localhost:5672" }; - String[] adminAddresses = new String[] { "http://localhost:15672", "http://localhost:15672" }; + String[] adminAddresses = new String[] { "http://localhost:15672", + "http://localhost:15672" }; String[] nodes = new String[] { "foo@bar", "rabbit@localhost" }; String vhost = "/"; String username = "guest"; String password = "guest"; - this.lqcf = new LocalizedQueueConnectionFactory(defaultConnectionFactory, addresses, - adminAddresses, nodes, vhost, username, password, false, null, null, null, null); + this.lqcf = new LocalizedQueueConnectionFactory(defaultConnectionFactory, + addresses, adminAddresses, nodes, vhost, username, password, false, null, + null, null, null); } @Test @@ -62,7 +62,8 @@ public class LocalizedQueueConnectionFactoryIntegrationTests { RabbitAdmin admin = new RabbitAdmin(this.lqcf); Queue queue = new Queue(UUID.randomUUID().toString(), false, false, true); admin.declareQueue(queue); - ConnectionFactory targetConnectionFactory = this.lqcf.getTargetConnectionFactory("[" + queue.getName() + "]"); + ConnectionFactory targetConnectionFactory = this.lqcf + .getTargetConnectionFactory("[" + queue.getName() + "]"); RabbitTemplate template = new RabbitTemplate(targetConnectionFactory); template.convertAndSend("", queue.getName(), "foo"); assertThat(template.receiveAndConvert(queue.getName())).isEqualTo("foo"); diff --git a/spring-cloud-stream-binder-rabbit/src/test/java/org/springframework/cloud/stream/binder/rabbit/RabbitBinderCleanerTests.java b/spring-cloud-stream-binder-rabbit/src/test/java/org/springframework/cloud/stream/binder/rabbit/RabbitBinderCleanerTests.java index 1100d314f..f1000d621 100644 --- a/spring-cloud-stream-binder-rabbit/src/test/java/org/springframework/cloud/stream/binder/rabbit/RabbitBinderCleanerTests.java +++ b/spring-cloud-stream-binder-rabbit/src/test/java/org/springframework/cloud/stream/binder/rabbit/RabbitBinderCleanerTests.java @@ -59,64 +59,74 @@ public class RabbitBinderCleanerTests { @Test public void testCleanStream() { final RabbitBindingCleaner cleaner = new RabbitBindingCleaner(); - final RestTemplate template = RabbitManagementUtils.buildRestTemplate("http://localhost:15672", "guest", - "guest"); + final RestTemplate template = RabbitManagementUtils + .buildRestTemplate("http://localhost:15672", "guest", "guest"); final String stream1 = UUID.randomUUID().toString(); String stream2 = stream1 + "-1"; String firstQueue = null; CachingConnectionFactory connectionFactory = rabbitWithMgmtEnabled.getResource(); RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory); for (int i = 0; i < 5; i++) { - String queue1Name = AbstractBinder.applyPrefix(BINDER_PREFIX, stream1 + ".default." + i); - String queue2Name = AbstractBinder.applyPrefix(BINDER_PREFIX, stream2 + ".default." + i); + String queue1Name = AbstractBinder.applyPrefix(BINDER_PREFIX, + stream1 + ".default." + i); + String queue2Name = AbstractBinder.applyPrefix(BINDER_PREFIX, + stream2 + ".default." + i); if (firstQueue == null) { firstQueue = queue1Name; } - URI uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues") - .pathSegment("{vhost}", "{queue}") - .buildAndExpand("/", queue1Name) + URI uri = UriComponentsBuilder + .fromUriString("http://localhost:15672/api/queues") + .pathSegment("{vhost}", "{queue}").buildAndExpand("/", queue1Name) + .encode().toUri(); + template.put(uri, new AmqpQueue(false, true)); + uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues") + .pathSegment("{vhost}", "{queue}").buildAndExpand("/", queue2Name) .encode().toUri(); template.put(uri, new AmqpQueue(false, true)); uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues") .pathSegment("{vhost}", "{queue}") - .buildAndExpand("/", queue2Name) + .buildAndExpand("/", AbstractBinder.constructDLQName(queue1Name)) .encode().toUri(); template.put(uri, new AmqpQueue(false, true)); - uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues") - .pathSegment("{vhost}", "{queue}") - .buildAndExpand("/", AbstractBinder.constructDLQName(queue1Name)).encode().toUri(); - template.put(uri, new AmqpQueue(false, true)); TopicExchange exchange = new TopicExchange(queue1Name); rabbitAdmin.declareExchange(exchange); - rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(queue1Name)).to(exchange).with(queue1Name)); + rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(queue1Name)) + .to(exchange).with(queue1Name)); exchange = new TopicExchange(queue2Name); rabbitAdmin.declareExchange(exchange); - rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(queue2Name)).to(exchange).with(queue2Name)); + rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(queue2Name)) + .to(exchange).with(queue2Name)); } final TopicExchange topic1 = new TopicExchange( AbstractBinder.applyPrefix(BINDER_PREFIX, stream1 + ".foo.bar")); rabbitAdmin.declareExchange(topic1); - rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(firstQueue)).to(topic1).with("#")); + rabbitAdmin.declareBinding( + BindingBuilder.bind(new Queue(firstQueue)).to(topic1).with("#")); String foreignQueue = UUID.randomUUID().toString(); rabbitAdmin.declareQueue(new Queue(foreignQueue)); - rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(foreignQueue)).to(topic1).with("#")); + rabbitAdmin.declareBinding( + BindingBuilder.bind(new Queue(foreignQueue)).to(topic1).with("#")); final TopicExchange topic2 = new TopicExchange( AbstractBinder.applyPrefix(BINDER_PREFIX, stream2 + ".foo.bar")); rabbitAdmin.declareExchange(topic2); - rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(firstQueue)).to(topic2).with("#")); + rabbitAdmin.declareBinding( + BindingBuilder.bind(new Queue(firstQueue)).to(topic2).with("#")); new RabbitTemplate(connectionFactory).execute(new ChannelCallback() { @Override public Void doInRabbit(Channel channel) throws Exception { - String queueName = AbstractBinder.applyPrefix(BINDER_PREFIX, stream1 + ".default." + 4); - String consumerTag = channel.basicConsume(queueName, new DefaultConsumer(channel)); + String queueName = AbstractBinder.applyPrefix(BINDER_PREFIX, + stream1 + ".default." + 4); + String consumerTag = channel.basicConsume(queueName, + new DefaultConsumer(channel)); try { waitForConsumerStateNot(queueName, 0); cleaner.clean(stream1, false); fail("Expected exception"); } catch (RabbitAdminException e) { - assertThat(e).hasMessageContaining("Queue " + queueName + " is in use"); + assertThat(e) + .hasMessageContaining("Queue " + queueName + " is in use"); } channel.basicCancel(consumerTag); waitForConsumerStateNot(queueName, 1); @@ -131,14 +141,17 @@ public class RabbitBinderCleanerTests { return null; } - private void waitForConsumerStateNot(String queueName, int state) throws InterruptedException { + private void waitForConsumerStateNot(String queueName, int state) + throws InterruptedException { int n = 0; - URI uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues").pathSegment( - "{vhost}", "{queue}") - .buildAndExpand("/", queueName).encode().toUri(); + URI uri = UriComponentsBuilder + .fromUriString("http://localhost:15672/api/queues") + .pathSegment("{vhost}", "{queue}").buildAndExpand("/", queueName) + .encode().toUri(); Object consumers = null; - while (n++ < 100 && (consumers == null || consumers.equals(Integer.valueOf(state)))) { + while (n++ < 100 && (consumers == null + || consumers.equals(Integer.valueOf(state)))) { Map queueInfo = template.getForObject(uri, Map.class); consumers = queueInfo.get("consumers"); if (consumers == null || consumers.equals(Integer.valueOf(state))) { @@ -147,7 +160,8 @@ public class RabbitBinderCleanerTests { } assertThat(consumers).isNotNull(); - assertThat(n).withFailMessage("Consumer state remained at " + state + " after 10 seconds") + assertThat(n).withFailMessage( + "Consumer state remained at " + state + " after 10 seconds") .isLessThan(100); } @@ -162,8 +176,10 @@ public class RabbitBinderCleanerTests { // should *not* clean stream2 assertThat(cleanedQueues).hasSize(10); for (int i = 0; i < 5; i++) { - assertThat(cleanedQueues.get(i * 2)).isEqualTo(BINDER_PREFIX + stream1 + ".default." + i); - assertThat(cleanedQueues.get(i * 2 + 1)).isEqualTo(BINDER_PREFIX + stream1 + ".default." + i + ".dlq"); + assertThat(cleanedQueues.get(i * 2)) + .isEqualTo(BINDER_PREFIX + stream1 + ".default." + i); + assertThat(cleanedQueues.get(i * 2 + 1)) + .isEqualTo(BINDER_PREFIX + stream1 + ".default." + i + ".dlq"); } List cleanedExchanges = cleanedMap.get("exchanges"); assertThat(cleanedExchanges).hasSize(6); @@ -174,7 +190,8 @@ public class RabbitBinderCleanerTests { cleanedQueues = cleanedMap.get("queues"); assertThat(cleanedQueues).hasSize(5); for (int i = 0; i < 5; i++) { - assertThat(cleanedQueues.get(i)).isEqualTo(BINDER_PREFIX + stream2 + ".default." + i); + assertThat(cleanedQueues.get(i)) + .isEqualTo(BINDER_PREFIX + stream2 + ".default." + i); } cleanedExchanges = cleanedMap.get("exchanges"); assertThat(cleanedExchanges).hasSize(6); @@ -191,23 +208,19 @@ public class RabbitBinderCleanerTests { this.durable = durable; } - @JsonProperty("auto_delete") protected boolean isAutoDelete() { return autoDelete; } - protected void setAutoDelete(boolean autoDelete) { this.autoDelete = autoDelete; } - protected boolean isDurable() { return durable; } - protected void setDurable(boolean durable) { this.durable = durable; } diff --git a/spring-cloud-stream-binder-rabbit/src/test/java/org/springframework/cloud/stream/binder/rabbit/RabbitBinderTests.java b/spring-cloud-stream-binder-rabbit/src/test/java/org/springframework/cloud/stream/binder/rabbit/RabbitBinderTests.java index 732249684..731d3ee98 100644 --- a/spring-cloud-stream-binder-rabbit/src/test/java/org/springframework/cloud/stream/binder/rabbit/RabbitBinderTests.java +++ b/spring-cloud-stream-binder-rabbit/src/test/java/org/springframework/cloud/stream/binder/rabbit/RabbitBinderTests.java @@ -128,11 +128,13 @@ import static org.mockito.Mockito.when; public class RabbitBinderTests extends PartitionCapableBinderTests, ExtendedProducerProperties> { - private final String CLASS_UNDER_TEST_NAME = RabbitMessageChannelBinder.class.getSimpleName(); + private final String CLASS_UNDER_TEST_NAME = RabbitMessageChannelBinder.class + .getSimpleName(); public static final String TEST_PREFIX = "bindertest."; - private static final String BIG_EXCEPTION_MESSAGE = new String(new byte[10_000]).replaceAll("\u0000", "x"); + private static final String BIG_EXCEPTION_MESSAGE = new String(new byte[10_000]) + .replaceAll("\u0000", "x"); private int maxStackTraceSize; @@ -148,7 +150,8 @@ public class RabbitBinderTests extends RabbitProperties rabbitProperties = new RabbitProperties(); rabbitProperties.setPublisherConfirms(true); rabbitProperties.setPublisherReturns(true); - this.testBinder = new RabbitTestBinder(rabbitAvailableRule.getResource(), rabbitProperties); + this.testBinder = new RabbitTestBinder(rabbitAvailableRule.getResource(), + rabbitProperties); } return this.testBinder; } @@ -163,7 +166,8 @@ public class RabbitBinderTests extends ExtendedProducerProperties props = new ExtendedProducerProperties<>( new RabbitProducerProperties()); if (testName.getMethodName().equals("testPartitionedModuleSpEL")) { - props.getExtension().setRoutingKeyExpression(spelExpressionParser.parseExpression("'part.0'")); + props.getExtension().setRoutingKeyExpression( + spelExpressionParser.parseExpression("'part.0'")); } return props; } @@ -179,23 +183,31 @@ public class RabbitBinderTests extends final AtomicReference event = new AtomicReference<>(); binder.getApplicationContext().addApplicationListener( (ApplicationListener) e -> event.set(e)); - DirectChannel moduleOutputChannel = createBindableChannel("output", new BindingProperties()); - DirectChannel moduleInputChannel = createBindableChannel("input", new BindingProperties()); - Binding producerBinding = binder.bindProducer("bad.0", moduleOutputChannel, - createProducerProperties()); - assertThat(TestUtils.getPropertyValue(producerBinding, "lifecycle.headersMappedLast", Boolean.class)) - .isTrue(); - assertThat(TestUtils.getPropertyValue(producerBinding, "lifecycle.amqpTemplate.messageConverter") - .getClass().getName()).contains("Passthrough"); + DirectChannel moduleOutputChannel = createBindableChannel("output", + new BindingProperties()); + DirectChannel moduleInputChannel = createBindableChannel("input", + new BindingProperties()); + Binding producerBinding = binder.bindProducer("bad.0", + moduleOutputChannel, createProducerProperties()); + assertThat(TestUtils.getPropertyValue(producerBinding, + "lifecycle.headersMappedLast", Boolean.class)).isTrue(); + assertThat( + TestUtils + .getPropertyValue(producerBinding, + "lifecycle.amqpTemplate.messageConverter") + .getClass().getName()).contains("Passthrough"); ExtendedConsumerProperties consumerProps = createConsumerProperties(); consumerProps.getExtension().setContainerType(ContainerType.DIRECT); - Binding consumerBinding = binder.bindConsumer("bad.0", "test", moduleInputChannel, - consumerProps); - assertThat(TestUtils.getPropertyValue(consumerBinding, "lifecycle.messageConverter").getClass().getName()) - .contains("Passthrough"); - assertThat(TestUtils.getPropertyValue(consumerBinding, "lifecycle.messageListenerContainer")) - .isInstanceOf(DirectMessageListenerContainer.class); - Message message = MessageBuilder.withPayload("bad".getBytes()).setHeader(MessageHeaders.CONTENT_TYPE, "foo/bar").build(); + Binding consumerBinding = binder.bindConsumer("bad.0", "test", + moduleInputChannel, consumerProps); + assertThat( + TestUtils.getPropertyValue(consumerBinding, "lifecycle.messageConverter") + .getClass().getName()).contains("Passthrough"); + assertThat(TestUtils.getPropertyValue(consumerBinding, + "lifecycle.messageListenerContainer")) + .isInstanceOf(DirectMessageListenerContainer.class); + Message message = MessageBuilder.withPayload("bad".getBytes()) + .setHeader(MessageHeaders.CONTENT_TYPE, "foo/bar").build(); final CountDownLatch latch = new CountDownLatch(3); moduleInputChannel.subscribe(new MessageHandler() { @@ -219,13 +231,16 @@ public class RabbitBinderTests extends ccf.setPublisherReturns(true); ccf.setPublisherConfirms(true); ccf.resetConnection(); - DirectChannel moduleOutputChannel = createBindableChannel("output", new BindingProperties()); + DirectChannel moduleOutputChannel = createBindableChannel("output", + new BindingProperties()); ExtendedProducerProperties producerProps = createProducerProperties(); producerProps.setErrorChannelEnabled(true); - Binding producerBinding = binder.bindProducer("ec.0", moduleOutputChannel, producerProps); - final Message message = MessageBuilder.withPayload("bad".getBytes()).setHeader(MessageHeaders.CONTENT_TYPE, "foo/bar") - .build(); - SubscribableChannel ec = binder.getApplicationContext().getBean("ec.0.errors", SubscribableChannel.class); + Binding producerBinding = binder.bindProducer("ec.0", + moduleOutputChannel, producerProps); + final Message message = MessageBuilder.withPayload("bad".getBytes()) + .setHeader(MessageHeaders.CONTENT_TYPE, "foo/bar").build(); + SubscribableChannel ec = binder.getApplicationContext().getBean("ec.0.errors", + SubscribableChannel.class); final AtomicReference> errorMessage = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(2); ec.subscribe(new MessageHandler() { @@ -237,8 +252,9 @@ public class RabbitBinderTests extends } }); - SubscribableChannel globalEc = binder.getApplicationContext() - .getBean(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME, SubscribableChannel.class); + SubscribableChannel globalEc = binder.getApplicationContext().getBean( + IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME, + SubscribableChannel.class); globalEc.subscribe(new MessageHandler() { @Override @@ -250,15 +266,17 @@ public class RabbitBinderTests extends moduleOutputChannel.send(message); assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(errorMessage.get()).isInstanceOf(ErrorMessage.class); - assertThat(errorMessage.get().getPayload()).isInstanceOf(ReturnedAmqpMessageException.class); - ReturnedAmqpMessageException exception = (ReturnedAmqpMessageException) errorMessage.get().getPayload(); + assertThat(errorMessage.get().getPayload()) + .isInstanceOf(ReturnedAmqpMessageException.class); + ReturnedAmqpMessageException exception = (ReturnedAmqpMessageException) errorMessage + .get().getPayload(); assertThat(exception.getReplyCode()).isEqualTo(312); assertThat(exception.getReplyText()).isEqualTo("NO_ROUTE"); - AmqpOutboundEndpoint endpoint = TestUtils.getPropertyValue(producerBinding, "lifecycle", - AmqpOutboundEndpoint.class); - assertThat(TestUtils.getPropertyValue(endpoint, "confirmCorrelationExpression.expression")) - .isEqualTo("#root"); + AmqpOutboundEndpoint endpoint = TestUtils.getPropertyValue(producerBinding, + "lifecycle", AmqpOutboundEndpoint.class); + assertThat(TestUtils.getPropertyValue(endpoint, + "confirmCorrelationExpression.expression")).isEqualTo("#root"); class WrapperAccessor extends AmqpOutboundEndpoint { public WrapperAccessor(AmqpTemplate amqpTemplate) { @@ -266,17 +284,21 @@ public class RabbitBinderTests extends } public CorrelationDataWrapper getWrapper() throws Exception { - Constructor constructor = CorrelationDataWrapper.class.getDeclaredConstructor( - String.class, Object.class, Message.class); + Constructor constructor = CorrelationDataWrapper.class + .getDeclaredConstructor(String.class, Object.class, + Message.class); ReflectionUtils.makeAccessible(constructor); return constructor.newInstance(null, message, message); } } - endpoint.confirm(new WrapperAccessor(mock(AmqpTemplate.class)).getWrapper(), false, "Mock NACK"); + endpoint.confirm(new WrapperAccessor(mock(AmqpTemplate.class)).getWrapper(), + false, "Mock NACK"); assertThat(errorMessage.get()).isInstanceOf(ErrorMessage.class); - assertThat(errorMessage.get().getPayload()).isInstanceOf(NackedAmqpMessageException.class); - NackedAmqpMessageException nack = (NackedAmqpMessageException) errorMessage.get().getPayload(); + assertThat(errorMessage.get().getPayload()) + .isInstanceOf(NackedAmqpMessageException.class); + NackedAmqpMessageException nack = (NackedAmqpMessageException) errorMessage.get() + .getPayload(); assertThat(nack.getNackReason()).isEqualTo("Mock NACK"); assertThat(nack.getCorrelationData()).isEqualTo(message); assertThat(nack.getFailedMessage()).isEqualTo(message); @@ -290,18 +312,22 @@ public class RabbitBinderTests extends ccf.setPublisherReturns(true); ccf.setPublisherConfirms(true); ccf.resetConnection(); - DirectChannel moduleOutputChannel = createBindableChannel("output", new BindingProperties()); + DirectChannel moduleOutputChannel = createBindableChannel("output", + new BindingProperties()); ExtendedProducerProperties producerProps = createProducerProperties(); producerProps.setErrorChannelEnabled(true); producerProps.getExtension().setConfirmAckChannel("acksChannel"); - Binding producerBinding = binder.bindProducer("acks.0", moduleOutputChannel, producerProps); - final Message message = MessageBuilder.withPayload("acksMessage".getBytes()).build(); + Binding producerBinding = binder.bindProducer("acks.0", + moduleOutputChannel, producerProps); + final Message message = MessageBuilder.withPayload("acksMessage".getBytes()) + .build(); final AtomicReference> confirm = new AtomicReference<>(); final CountDownLatch confirmLatch = new CountDownLatch(1); - binder.getApplicationContext().getBean("acksChannel", DirectChannel.class).subscribe(m -> { - confirm.set(m); - confirmLatch.countDown(); - }); + binder.getApplicationContext().getBean("acksChannel", DirectChannel.class) + .subscribe(m -> { + confirm.set(m); + confirmLatch.countDown(); + }); moduleOutputChannel.send(message); assertThat(confirmLatch.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(confirm.get().getPayload()).isEqualTo("acksMessage".getBytes()); @@ -321,25 +347,40 @@ public class RabbitBinderTests extends Binding consumerBinding = binder.bindConsumer("props.0", null, createBindableChannel("input", new BindingProperties()), properties); Lifecycle endpoint = extractEndpoint(consumerBinding); - SimpleMessageListenerContainer container = TestUtils.getPropertyValue(endpoint, "messageListenerContainer", - SimpleMessageListenerContainer.class); + SimpleMessageListenerContainer container = TestUtils.getPropertyValue(endpoint, + "messageListenerContainer", SimpleMessageListenerContainer.class); assertThat(container.getAcknowledgeMode()).isEqualTo(AcknowledgeMode.AUTO); - assertThat(container.getQueueNames()[0]).startsWith(properties.getExtension().getPrefix()); - assertThat(TestUtils.getPropertyValue(container, "transactional", Boolean.class)).isTrue(); - assertThat(TestUtils.getPropertyValue(container, "exclusive", Boolean.class)).isTrue(); - assertThat(TestUtils.getPropertyValue(container, "concurrentConsumers")).isEqualTo(1); - assertThat(TestUtils.getPropertyValue(container, "maxConcurrentConsumers")).isNull(); - assertThat(TestUtils.getPropertyValue(container, "defaultRequeueRejected", Boolean.class)).isTrue(); + assertThat(container.getQueueNames()[0]) + .startsWith(properties.getExtension().getPrefix()); + assertThat(TestUtils.getPropertyValue(container, "transactional", Boolean.class)) + .isTrue(); + assertThat(TestUtils.getPropertyValue(container, "exclusive", Boolean.class)) + .isTrue(); + assertThat(TestUtils.getPropertyValue(container, "concurrentConsumers")) + .isEqualTo(1); + assertThat(TestUtils.getPropertyValue(container, "maxConcurrentConsumers")) + .isNull(); + assertThat(TestUtils.getPropertyValue(container, "defaultRequeueRejected", + Boolean.class)).isTrue(); assertThat(TestUtils.getPropertyValue(container, "prefetchCount")).isEqualTo(1); assertThat(TestUtils.getPropertyValue(container, "txSize")).isEqualTo(1); - assertThat(TestUtils.getPropertyValue(container, "missingQueuesFatal", Boolean.class)).isTrue(); - assertThat(TestUtils.getPropertyValue(container, "failedDeclarationRetryInterval")).isEqualTo(1500L); - assertThat(TestUtils.getPropertyValue(container, "declarationRetries")).isEqualTo(23); - RetryTemplate retry = TestUtils.getPropertyValue(endpoint, "retryTemplate", RetryTemplate.class); - assertThat(TestUtils.getPropertyValue(retry, "retryPolicy.maxAttempts")).isEqualTo(3); - assertThat(TestUtils.getPropertyValue(retry, "backOffPolicy.initialInterval")).isEqualTo(1000L); - assertThat(TestUtils.getPropertyValue(retry, "backOffPolicy.maxInterval")).isEqualTo(10000L); - assertThat(TestUtils.getPropertyValue(retry, "backOffPolicy.multiplier")).isEqualTo(2.0); + assertThat(TestUtils.getPropertyValue(container, "missingQueuesFatal", + Boolean.class)).isTrue(); + assertThat( + TestUtils.getPropertyValue(container, "failedDeclarationRetryInterval")) + .isEqualTo(1500L); + assertThat(TestUtils.getPropertyValue(container, "declarationRetries")) + .isEqualTo(23); + RetryTemplate retry = TestUtils.getPropertyValue(endpoint, "retryTemplate", + RetryTemplate.class); + assertThat(TestUtils.getPropertyValue(retry, "retryPolicy.maxAttempts")) + .isEqualTo(3); + assertThat(TestUtils.getPropertyValue(retry, "backOffPolicy.initialInterval")) + .isEqualTo(1000L); + assertThat(TestUtils.getPropertyValue(retry, "backOffPolicy.maxInterval")) + .isEqualTo(10000L); + assertThat(TestUtils.getPropertyValue(retry, "backOffPolicy.multiplier")) + .isEqualTo(2.0); consumerBinding.unbind(); assertThat(endpoint.isRunning()).isFalse(); @@ -356,8 +397,8 @@ public class RabbitBinderTests extends properties.getExtension().setHeaderPatterns(new String[] { "foo" }); properties.getExtension().setTxSize(10); properties.setInstanceIndex(0); - consumerBinding = binder.bindConsumer("props.0", "test", createBindableChannel("input", new BindingProperties()), - properties); + consumerBinding = binder.bindConsumer("props.0", "test", + createBindableChannel("input", new BindingProperties()), properties); endpoint = extractEndpoint(consumerBinding); container = verifyContainer(endpoint); @@ -383,18 +424,20 @@ public class RabbitBinderTests extends properties.getExtension().setDeclareExchange(false); properties.getExtension().setBindQueue(false); - Binding consumerBinding = binder.bindConsumer("propsUser1", "infra", - createBindableChannel("input", new BindingProperties()), properties); + Binding consumerBinding = binder.bindConsumer("propsUser1", + "infra", createBindableChannel("input", new BindingProperties()), + properties); Lifecycle endpoint = extractEndpoint(consumerBinding); - SimpleMessageListenerContainer container = TestUtils.getPropertyValue(endpoint, "messageListenerContainer", - SimpleMessageListenerContainer.class); - assertThat(TestUtils.getPropertyValue(container, "missingQueuesFatal", Boolean.class)).isFalse(); + SimpleMessageListenerContainer container = TestUtils.getPropertyValue(endpoint, + "messageListenerContainer", SimpleMessageListenerContainer.class); + assertThat(TestUtils.getPropertyValue(container, "missingQueuesFatal", + Boolean.class)).isFalse(); assertThat(container.isRunning()).isTrue(); consumerBinding.unbind(); assertThat(container.isRunning()).isFalse(); - org.springframework.amqp.rabbit.core.RabbitManagementTemplate rmt = - new org.springframework.amqp.rabbit.core.RabbitManagementTemplate(); - List bindings = rmt.getBindingsForExchange("/", exchange.getName()); + org.springframework.amqp.rabbit.core.RabbitManagementTemplate rmt = new org.springframework.amqp.rabbit.core.RabbitManagementTemplate(); + List bindings = rmt + .getBindingsForExchange("/", exchange.getName()); assertThat(bindings.size()).isEqualTo(1); } @@ -408,8 +451,8 @@ public class RabbitBinderTests extends Binding consumerBinding = binder.bindConsumer("amq.topic", null, createBindableChannel("input", new BindingProperties()), properties); Lifecycle endpoint = extractEndpoint(consumerBinding); - SimpleMessageListenerContainer container = TestUtils.getPropertyValue(endpoint, "messageListenerContainer", - SimpleMessageListenerContainer.class); + SimpleMessageListenerContainer container = TestUtils.getPropertyValue(endpoint, + "messageListenerContainer", SimpleMessageListenerContainer.class); String queueName = container.getQueueNames()[0]; assertThat(queueName).startsWith("anonymous."); assertThat(container.isRunning()).isTrue(); @@ -419,27 +462,29 @@ public class RabbitBinderTests extends @SuppressWarnings("deprecation") @Test - public void testConsumerPropertiesWithUserInfrastructureCustomExchangeAndRK() throws Exception { + public void testConsumerPropertiesWithUserInfrastructureCustomExchangeAndRK() + throws Exception { RabbitTestBinder binder = getBinder(); ExtendedConsumerProperties properties = createConsumerProperties(); properties.getExtension().setExchangeType(ExchangeTypes.DIRECT); properties.getExtension().setBindingRoutingKey("foo"); properties.getExtension().setQueueNameGroupOnly(true); -// properties.getExtension().setDelayedExchange(true); // requires delayed message exchange plugin; tested locally + // properties.getExtension().setDelayedExchange(true); // requires delayed message + // exchange plugin; tested locally String group = "infra"; Binding consumerBinding = binder.bindConsumer("propsUser2", group, createBindableChannel("input", new BindingProperties()), properties); Lifecycle endpoint = extractEndpoint(consumerBinding); - SimpleMessageListenerContainer container = TestUtils.getPropertyValue(endpoint, "messageListenerContainer", - SimpleMessageListenerContainer.class); + SimpleMessageListenerContainer container = TestUtils.getPropertyValue(endpoint, + "messageListenerContainer", SimpleMessageListenerContainer.class); assertThat(container.isRunning()).isTrue(); consumerBinding.unbind(); assertThat(container.isRunning()).isFalse(); assertThat(container.getQueueNames()[0]).isEqualTo(group); - org.springframework.amqp.rabbit.core.RabbitManagementTemplate rmt = - new org.springframework.amqp.rabbit.core.RabbitManagementTemplate(); - List bindings = rmt.getBindingsForExchange("/", "propsUser2"); + org.springframework.amqp.rabbit.core.RabbitManagementTemplate rmt = new org.springframework.amqp.rabbit.core.RabbitManagementTemplate(); + List bindings = rmt + .getBindingsForExchange("/", "propsUser2"); int n = 0; while (n++ < 100 && bindings == null || bindings.size() < 1) { Thread.sleep(100); @@ -450,11 +495,12 @@ public class RabbitBinderTests extends assertThat(bindings.get(0).getDestination()).isEqualTo(group); assertThat(bindings.get(0).getRoutingKey()).isEqualTo("foo"); -// // TODO: AMQP-696 -// // Exchange exchange = rmt.getExchange("propsUser2"); -// ExchangeInfo ei = rmt.getClient().getExchange("/", "propsUser2"); // requires delayed message exchange plugin -// assertThat(ei.getType()).isEqualTo("x-delayed-message"); -// assertThat(ei.getArguments().get("x-delayed-type")).isEqualTo("direct"); + // // TODO: AMQP-696 + // // Exchange exchange = rmt.getExchange("propsUser2"); + // ExchangeInfo ei = rmt.getClient().getExchange("/", "propsUser2"); // requires + // delayed message exchange plugin + // assertThat(ei.getType()).isEqualTo("x-delayed-message"); + // assertThat(ei.getArguments().get("x-delayed-type")).isEqualTo("direct"); Exchange exchange = rmt.getExchange("propsUser2"); while (n++ < 100 && exchange == null) { @@ -468,7 +514,8 @@ public class RabbitBinderTests extends @SuppressWarnings("deprecation") @Test - public void testConsumerPropertiesWithUserInfrastructureCustomQueueArgs() throws Exception { + public void testConsumerPropertiesWithUserInfrastructureCustomQueueArgs() + throws Exception { RabbitTestBinder binder = getBinder(); ExtendedConsumerProperties properties = createConsumerProperties(); RabbitConsumerProperties extProps = properties.getExtension(); @@ -500,15 +547,16 @@ public class RabbitBinderTests extends extProps.setConsumerTagPrefix("testConsumerTag"); extProps.setExclusive(true); - Binding consumerBinding = binder.bindConsumer("propsUser3", "infra", - createBindableChannel("input", new BindingProperties()), properties); + Binding consumerBinding = binder.bindConsumer("propsUser3", + "infra", createBindableChannel("input", new BindingProperties()), + properties); Lifecycle endpoint = extractEndpoint(consumerBinding); - SimpleMessageListenerContainer container = TestUtils.getPropertyValue(endpoint, "messageListenerContainer", - SimpleMessageListenerContainer.class); + SimpleMessageListenerContainer container = TestUtils.getPropertyValue(endpoint, + "messageListenerContainer", SimpleMessageListenerContainer.class); assertThat(container.isRunning()).isTrue(); - org.springframework.amqp.rabbit.core.RabbitManagementTemplate rmt = - new org.springframework.amqp.rabbit.core.RabbitManagementTemplate(); - List bindings = rmt.getBindingsForExchange("/", "propsUser3"); + org.springframework.amqp.rabbit.core.RabbitManagementTemplate rmt = new org.springframework.amqp.rabbit.core.RabbitManagementTemplate(); + List bindings = rmt + .getBindingsForExchange("/", "propsUser3"); int n = 0; while (n++ < 100 && bindings == null || bindings.size() < 1) { Thread.sleep(100); @@ -589,54 +637,64 @@ public class RabbitBinderTests extends createBindableChannel("input", new BindingProperties()), createProducerProperties()); Lifecycle endpoint = extractEndpoint(producerBinding); - MessageDeliveryMode mode = TestUtils.getPropertyValue(endpoint, "defaultDeliveryMode", - MessageDeliveryMode.class); + MessageDeliveryMode mode = TestUtils.getPropertyValue(endpoint, + "defaultDeliveryMode", MessageDeliveryMode.class); assertThat(mode).isEqualTo(MessageDeliveryMode.PERSISTENT); List requestHeaders = TestUtils.getPropertyValue(endpoint, "headerMapper.requestHeaderMatcher.matchers", List.class); assertThat(requestHeaders).hasSize(2); producerBinding.unbind(); assertThat(endpoint.isRunning()).isFalse(); - assertThat(TestUtils.getPropertyValue(endpoint, "amqpTemplate.transactional", Boolean.class)) - .isFalse(); + assertThat(TestUtils.getPropertyValue(endpoint, "amqpTemplate.transactional", + Boolean.class)).isFalse(); ExtendedProducerProperties producerProperties = createProducerProperties(); producerProperties.getExtension().setPrefix("foo."); - producerProperties.getExtension().setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT); + producerProperties.getExtension() + .setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT); producerProperties.getExtension().setHeaderPatterns(new String[] { "foo" }); - producerProperties.setPartitionKeyExpression(spelExpressionParser.parseExpression("'foo'")); - producerProperties.setPartitionKeyExtractorClass(TestPartitionKeyExtractorClass.class); - producerProperties.setPartitionSelectorExpression(spelExpressionParser.parseExpression("0")); + producerProperties + .setPartitionKeyExpression(spelExpressionParser.parseExpression("'foo'")); + producerProperties + .setPartitionKeyExtractorClass(TestPartitionKeyExtractorClass.class); + producerProperties.setPartitionSelectorExpression( + spelExpressionParser.parseExpression("0")); producerProperties.setPartitionSelectorClass(TestPartitionSelectorClass.class); producerProperties.setPartitionCount(1); producerProperties.getExtension().setTransacted(true); - producerProperties.getExtension().setDelayExpression(spelExpressionParser.parseExpression("42")); + producerProperties.getExtension() + .setDelayExpression(spelExpressionParser.parseExpression("42")); producerProperties.setRequiredGroups("prodPropsRequired"); - BindingProperties producerBindingProperties = createProducerBindingProperties(producerProperties); - DirectChannel channel = createBindableChannel("output", producerBindingProperties); + BindingProperties producerBindingProperties = createProducerBindingProperties( + producerProperties); + DirectChannel channel = createBindableChannel("output", + producerBindingProperties); producerBinding = binder.bindProducer("props.0", channel, producerProperties); - ConnectionFactory producerConnectionFactory = - TestUtils.getPropertyValue(producerBinding, "lifecycle.amqpTemplate.connectionFactory", - ConnectionFactory.class); + ConnectionFactory producerConnectionFactory = TestUtils.getPropertyValue( + producerBinding, "lifecycle.amqpTemplate.connectionFactory", + ConnectionFactory.class); assertThat(this.rabbitAvailableRule.getResource()) .isSameAs(producerConnectionFactory); endpoint = extractEndpoint(producerBinding); - assertThat(getEndpointRouting(endpoint)) - .isEqualTo("'props.0-' + headers['" + BinderHeaders.PARTITION_HEADER + "']"); - assertThat(TestUtils.getPropertyValue(endpoint, "delayExpression", SpelExpression.class) + assertThat(getEndpointRouting(endpoint)).isEqualTo( + "'props.0-' + headers['" + BinderHeaders.PARTITION_HEADER + "']"); + assertThat(TestUtils + .getPropertyValue(endpoint, "delayExpression", SpelExpression.class) .getExpressionString()).isEqualTo("42"); - mode = TestUtils.getPropertyValue(endpoint, "defaultDeliveryMode", MessageDeliveryMode.class); + mode = TestUtils.getPropertyValue(endpoint, "defaultDeliveryMode", + MessageDeliveryMode.class); assertThat(mode).isEqualTo(MessageDeliveryMode.NON_PERSISTENT); - assertThat(TestUtils.getPropertyValue(endpoint, "amqpTemplate.transactional", Boolean.class)) - .isTrue(); + assertThat(TestUtils.getPropertyValue(endpoint, "amqpTemplate.transactional", + Boolean.class)).isTrue(); verifyFooRequestProducer(endpoint); channel.send(new GenericMessage<>("foo")); - org.springframework.amqp.core.Message received = new RabbitTemplate(this.rabbitAvailableRule.getResource()) - .receive("foo.props.0.prodPropsRequired-0", 10_000); + org.springframework.amqp.core.Message received = new RabbitTemplate( + this.rabbitAvailableRule.getResource()) + .receive("foo.props.0.prodPropsRequired-0", 10_000); assertThat(received).isNotNull(); assertThat(received.getMessageProperties().getReceivedDelay()).isEqualTo(42); @@ -655,7 +713,8 @@ public class RabbitBinderTests extends consumerProperties.getExtension().setAutoBindDlq(true); consumerProperties.getExtension().setDurableSubscription(true); consumerProperties.setMaxAttempts(1); // disable retry - DirectChannel moduleInputChannel = createBindableChannel("input", createConsumerBindingProperties(consumerProperties)); + DirectChannel moduleInputChannel = createBindableChannel("input", + createConsumerBindingProperties(consumerProperties)); moduleInputChannel.setBeanName("durableTest"); moduleInputChannel.subscribe(new MessageHandler() { @@ -665,15 +724,17 @@ public class RabbitBinderTests extends } }); - Binding consumerBinding = binder.bindConsumer("durabletest.0", "tgroup", moduleInputChannel, - consumerProperties); + Binding consumerBinding = binder.bindConsumer("durabletest.0", + "tgroup", moduleInputChannel, consumerProperties); - RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource()); + RabbitTemplate template = new RabbitTemplate( + this.rabbitAvailableRule.getResource()); template.convertAndSend(TEST_PREFIX + "durabletest.0", "", "foo"); int n = 0; while (n++ < 100) { - Object deadLetter = template.receiveAndConvert(TEST_PREFIX + "durabletest.0.tgroup.dlq"); + Object deadLetter = template + .receiveAndConvert(TEST_PREFIX + "durabletest.0.tgroup.dlq"); if (deadLetter != null) { assertThat(deadLetter).isEqualTo("foo"); break; @@ -683,7 +744,8 @@ public class RabbitBinderTests extends assertThat(n).isLessThan(100); consumerBinding.unbind(); - assertThat(admin.getQueueProperties(TEST_PREFIX + "durabletest.0.tgroup.dlq")).isNotNull(); + assertThat(admin.getQueueProperties(TEST_PREFIX + "durabletest.0.tgroup.dlq")) + .isNotNull(); } @Test @@ -696,8 +758,10 @@ public class RabbitBinderTests extends consumerProperties.getExtension().setAutoBindDlq(true); consumerProperties.getExtension().setDurableSubscription(false); consumerProperties.setMaxAttempts(1); // disable retry - BindingProperties bindingProperties = createConsumerBindingProperties(consumerProperties); - DirectChannel moduleInputChannel = createBindableChannel("input", bindingProperties); + BindingProperties bindingProperties = createConsumerBindingProperties( + consumerProperties); + DirectChannel moduleInputChannel = createBindableChannel("input", + bindingProperties); moduleInputChannel.setBeanName("nondurabletest"); moduleInputChannel.subscribe(new MessageHandler() { @@ -707,11 +771,12 @@ public class RabbitBinderTests extends } }); - Binding consumerBinding = binder.bindConsumer("nondurabletest.0", "tgroup", moduleInputChannel, - consumerProperties); + Binding consumerBinding = binder.bindConsumer("nondurabletest.0", + "tgroup", moduleInputChannel, consumerProperties); consumerBinding.unbind(); - assertThat(admin.getQueueProperties(TEST_PREFIX + "nondurabletest.0.dlq")).isNull(); + assertThat(admin.getQueueProperties(TEST_PREFIX + "nondurabletest.0.dlq")) + .isNull(); } @Test @@ -722,8 +787,10 @@ public class RabbitBinderTests extends consumerProperties.getExtension().setAutoBindDlq(true); consumerProperties.setMaxAttempts(1); // disable retry consumerProperties.getExtension().setDurableSubscription(true); - BindingProperties bindingProperties = createConsumerBindingProperties(consumerProperties); - DirectChannel moduleInputChannel = createBindableChannel("input", bindingProperties); + BindingProperties bindingProperties = createConsumerBindingProperties( + consumerProperties); + DirectChannel moduleInputChannel = createBindableChannel("input", + bindingProperties); moduleInputChannel.setBeanName("dlqTest"); moduleInputChannel.subscribe(new MessageHandler() { @@ -734,18 +801,21 @@ public class RabbitBinderTests extends }); consumerProperties.setMultiplex(true); - Binding consumerBinding = binder.bindConsumer("dlqtest,dlqtest2", "default", - moduleInputChannel, consumerProperties); - AbstractMessageListenerContainer container = TestUtils.getPropertyValue(consumerBinding, - "lifecycle.messageListenerContainer", AbstractMessageListenerContainer.class); + Binding consumerBinding = binder.bindConsumer("dlqtest,dlqtest2", + "default", moduleInputChannel, consumerProperties); + AbstractMessageListenerContainer container = TestUtils.getPropertyValue( + consumerBinding, "lifecycle.messageListenerContainer", + AbstractMessageListenerContainer.class); assertThat(container.getQueueNames().length).isEqualTo(2); - RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource()); + RabbitTemplate template = new RabbitTemplate( + this.rabbitAvailableRule.getResource()); template.convertAndSend("", TEST_PREFIX + "dlqtest.default", "foo"); int n = 0; while (n++ < 100) { - Object deadLetter = template.receiveAndConvert(TEST_PREFIX + "dlqtest.default.dlq"); + Object deadLetter = template + .receiveAndConvert(TEST_PREFIX + "dlqtest.default.dlq"); if (deadLetter != null) { assertThat(deadLetter).isEqualTo("foo"); break; @@ -758,7 +828,8 @@ public class RabbitBinderTests extends n = 0; while (n++ < 100) { - Object deadLetter = template.receiveAndConvert(TEST_PREFIX + "dlqtest2.default.dlq"); + Object deadLetter = template + .receiveAndConvert(TEST_PREFIX + "dlqtest2.default.dlq"); if (deadLetter != null) { assertThat(deadLetter).isEqualTo("bar"); break; @@ -769,11 +840,14 @@ public class RabbitBinderTests extends consumerBinding.unbind(); - ApplicationContext context = TestUtils.getPropertyValue(binder, "binder.provisioningProvider.autoDeclareContext", + ApplicationContext context = TestUtils.getPropertyValue(binder, + "binder.provisioningProvider.autoDeclareContext", ApplicationContext.class); - assertThat(context.containsBean(TEST_PREFIX + "dlqtest.default.binding")).isFalse(); + assertThat(context.containsBean(TEST_PREFIX + "dlqtest.default.binding")) + .isFalse(); assertThat(context.containsBean(TEST_PREFIX + "dlqtest.default")).isFalse(); - assertThat(context.containsBean(TEST_PREFIX + "dlqtest.default.dlq.binding")).isFalse(); + assertThat(context.containsBean(TEST_PREFIX + "dlqtest.default.dlq.binding")) + .isFalse(); assertThat(context.containsBean(TEST_PREFIX + "dlqtest.default.dlq")).isFalse(); } @@ -787,17 +861,21 @@ public class RabbitBinderTests extends properties.setMaxAttempts(1); // disable retry properties.setPartitioned(true); properties.setInstanceIndex(0); - DirectChannel input0 = createBindableChannel("input", createConsumerBindingProperties(properties)); + DirectChannel input0 = createBindableChannel("input", + createConsumerBindingProperties(properties)); input0.setBeanName("test.input0DLQ"); - Binding input0Binding = binder.bindConsumer("partDLQ.0", "dlqPartGrp", input0, properties); - Binding defaultConsumerBinding1 = binder.bindConsumer("partDLQ.0", "default", - new QueueChannel(), properties); + Binding input0Binding = binder.bindConsumer("partDLQ.0", + "dlqPartGrp", input0, properties); + Binding defaultConsumerBinding1 = binder.bindConsumer("partDLQ.0", + "default", new QueueChannel(), properties); properties.setInstanceIndex(1); - DirectChannel input1 = createBindableChannel("input1", createConsumerBindingProperties(properties)); + DirectChannel input1 = createBindableChannel("input1", + createConsumerBindingProperties(properties)); input1.setBeanName("test.input1DLQ"); - Binding input1Binding = binder.bindConsumer("partDLQ.0", "dlqPartGrp", input1, properties); - Binding defaultConsumerBinding2 = binder.bindConsumer("partDLQ.0", "default", - new QueueChannel(), properties); + Binding input1Binding = binder.bindConsumer("partDLQ.0", + "dlqPartGrp", input1, properties); + Binding defaultConsumerBinding2 = binder.bindConsumer("partDLQ.0", + "default", new QueueChannel(), properties); ExtendedProducerProperties producerProperties = createProducerProperties(); producerProperties.getExtension().setPrefix("bindertest."); @@ -805,10 +883,12 @@ public class RabbitBinderTests extends producerProperties.setPartitionKeyExtractorClass(PartitionTestSupport.class); producerProperties.setPartitionSelectorClass(PartitionTestSupport.class); producerProperties.setPartitionCount(2); - BindingProperties bindingProperties = createProducerBindingProperties(producerProperties); + BindingProperties bindingProperties = createProducerBindingProperties( + producerProperties); DirectChannel output = createBindableChannel("output", bindingProperties); output.setBeanName("test.output"); - Binding outputBinding = binder.bindProducer("partDLQ.0", output, producerProperties); + Binding outputBinding = binder.bindProducer("partDLQ.0", output, + producerProperties); final CountDownLatch latch0 = new CountDownLatch(1); input0.subscribe(new MessageHandler() { @@ -844,7 +924,8 @@ public class RabbitBinderTests extends output.send(new GenericMessage<>(1)); - RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource()); + RabbitTemplate template = new RabbitTemplate( + this.rabbitAvailableRule.getResource()); template.setReceiveTimeout(10000); String streamDLQName = "bindertest.partDLQ.0.dlqPartGrp.dlq"; @@ -853,14 +934,16 @@ public class RabbitBinderTests extends assertThat(received).isNotNull(); assertThat(received.getMessageProperties().getReceivedRoutingKey()) .isEqualTo("bindertest.partDLQ.0.dlqPartGrp-1"); - assertThat(received.getMessageProperties().getHeaders()).doesNotContainKey(BinderHeaders.PARTITION_HEADER); + assertThat(received.getMessageProperties().getHeaders()) + .doesNotContainKey(BinderHeaders.PARTITION_HEADER); output.send(new GenericMessage<>(0)); received = template.receive(streamDLQName); assertThat(received).isNotNull(); assertThat(received.getMessageProperties().getReceivedRoutingKey()) .isEqualTo("bindertest.partDLQ.0.dlqPartGrp-0"); - assertThat(received.getMessageProperties().getHeaders()).doesNotContainKey(BinderHeaders.PARTITION_HEADER); + assertThat(received.getMessageProperties().getHeaders()) + .doesNotContainKey(BinderHeaders.PARTITION_HEADER); input0Binding.unbind(); input1Binding.unbind(); @@ -870,37 +953,45 @@ public class RabbitBinderTests extends } @Test - public void testAutoBindDLQPartitionedConsumerFirstWithRepublishNoRetry() throws Exception { + public void testAutoBindDLQPartitionedConsumerFirstWithRepublishNoRetry() + throws Exception { testAutoBindDLQPartionedConsumerFirstWithRepublishGuts(false); } @Test - public void testAutoBindDLQPartitionedConsumerFirstWithRepublishWithRetry() throws Exception { + public void testAutoBindDLQPartitionedConsumerFirstWithRepublishWithRetry() + throws Exception { testAutoBindDLQPartionedConsumerFirstWithRepublishGuts(true); } @SuppressWarnings("deprecation") - private void testAutoBindDLQPartionedConsumerFirstWithRepublishGuts(final boolean withRetry) throws Exception { + private void testAutoBindDLQPartionedConsumerFirstWithRepublishGuts( + final boolean withRetry) throws Exception { RabbitTestBinder binder = getBinder(); ExtendedConsumerProperties properties = createConsumerProperties(); properties.getExtension().setPrefix("bindertest."); properties.getExtension().setAutoBindDlq(true); properties.getExtension().setRepublishToDlq(true); - properties.getExtension().setRepublishDeliveyMode(MessageDeliveryMode.NON_PERSISTENT); + properties.getExtension() + .setRepublishDeliveyMode(MessageDeliveryMode.NON_PERSISTENT); properties.setMaxAttempts(withRetry ? 2 : 1); properties.setPartitioned(true); properties.setInstanceIndex(0); - DirectChannel input0 = createBindableChannel("input", createConsumerBindingProperties(properties)); + DirectChannel input0 = createBindableChannel("input", + createConsumerBindingProperties(properties)); input0.setBeanName("test.input0DLQ"); - Binding input0Binding = binder.bindConsumer("partPubDLQ.0", "dlqPartGrp", input0, properties); - Binding defaultConsumerBinding1 = binder.bindConsumer("partPubDLQ.0", "default", - new QueueChannel(), properties); + Binding input0Binding = binder.bindConsumer("partPubDLQ.0", + "dlqPartGrp", input0, properties); + Binding defaultConsumerBinding1 = binder + .bindConsumer("partPubDLQ.0", "default", new QueueChannel(), properties); properties.setInstanceIndex(1); - DirectChannel input1 = createBindableChannel("input1", createConsumerBindingProperties(properties)); + DirectChannel input1 = createBindableChannel("input1", + createConsumerBindingProperties(properties)); input1.setBeanName("test.input1DLQ"); - Binding input1Binding = binder.bindConsumer("partPubDLQ.0", "dlqPartGrp", input1, properties); - Binding defaultConsumerBinding2 = binder.bindConsumer("partPubDLQ.0", "default", - new QueueChannel(), properties); + Binding input1Binding = binder.bindConsumer("partPubDLQ.0", + "dlqPartGrp", input1, properties); + Binding defaultConsumerBinding2 = binder + .bindConsumer("partPubDLQ.0", "default", new QueueChannel(), properties); ExtendedProducerProperties producerProperties = createProducerProperties(); producerProperties.getExtension().setPrefix("bindertest."); @@ -908,10 +999,12 @@ public class RabbitBinderTests extends producerProperties.setPartitionKeyExtractorClass(PartitionTestSupport.class); producerProperties.setPartitionSelectorClass(PartitionTestSupport.class); producerProperties.setPartitionCount(2); - BindingProperties bindingProperties = createProducerBindingProperties(producerProperties); + BindingProperties bindingProperties = createProducerBindingProperties( + producerProperties); DirectChannel output = createBindableChannel("output", bindingProperties); output.setBeanName("test.output"); - Binding outputBinding = binder.bindProducer("partPubDLQ.0", output, producerProperties); + Binding outputBinding = binder.bindProducer("partPubDLQ.0", + output, producerProperties); final CountDownLatch latch0 = new CountDownLatch(1); input0.subscribe(new MessageHandler() { @@ -939,11 +1032,12 @@ public class RabbitBinderTests extends }); - ApplicationContext context = TestUtils.getPropertyValue(binder.getBinder(), "applicationContext", - ApplicationContext.class); - SubscribableChannel boundErrorChannel = context - .getBean("bindertest.partPubDLQ.0.dlqPartGrp-0.errors", SubscribableChannel.class); - SubscribableChannel globalErrorChannel = context.getBean("errorChannel", SubscribableChannel.class); + ApplicationContext context = TestUtils.getPropertyValue(binder.getBinder(), + "applicationContext", ApplicationContext.class); + SubscribableChannel boundErrorChannel = context.getBean( + "bindertest.partPubDLQ.0.dlqPartGrp-0.errors", SubscribableChannel.class); + SubscribableChannel globalErrorChannel = context.getBean("errorChannel", + SubscribableChannel.class); final AtomicReference> boundErrorChannelMessage = new AtomicReference<>(); final AtomicReference> globalErrorChannelMessage = new AtomicReference<>(); final AtomicBoolean hasRecovererInCallStack = new AtomicBoolean(!withRetry); @@ -952,8 +1046,10 @@ public class RabbitBinderTests extends @Override public void handleMessage(Message message) throws MessagingException { boundErrorChannelMessage.set(message); - String stackTrace = Arrays.toString(new RuntimeException().getStackTrace()); - hasRecovererInCallStack.set(stackTrace.contains("ErrorMessageSendingRecoverer")); + String stackTrace = Arrays + .toString(new RuntimeException().getStackTrace()); + hasRecovererInCallStack + .set(stackTrace.contains("ErrorMessageSendingRecoverer")); } }); @@ -974,27 +1070,33 @@ public class RabbitBinderTests extends output.send(new GenericMessage<>(1)); - RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource()); + RabbitTemplate template = new RabbitTemplate( + this.rabbitAvailableRule.getResource()); template.setReceiveTimeout(10000); String streamDLQName = "bindertest.partPubDLQ.0.dlqPartGrp.dlq"; org.springframework.amqp.core.Message received = template.receive(streamDLQName); assertThat(received).isNotNull(); - assertThat(received.getMessageProperties().getHeaders().get("x-original-routingKey")) - .isEqualTo("partPubDLQ.0-1"); - assertThat(received.getMessageProperties().getHeaders()).doesNotContainKey(BinderHeaders.PARTITION_HEADER); + assertThat( + received.getMessageProperties().getHeaders().get("x-original-routingKey")) + .isEqualTo("partPubDLQ.0-1"); + assertThat(received.getMessageProperties().getHeaders()) + .doesNotContainKey(BinderHeaders.PARTITION_HEADER); assertThat(received.getMessageProperties().getReceivedDeliveryMode()) .isEqualTo(MessageDeliveryMode.NON_PERSISTENT); output.send(new GenericMessage<>(0)); received = template.receive(streamDLQName); assertThat(received).isNotNull(); - assertThat(received.getMessageProperties().getHeaders().get("x-original-routingKey")) - .isEqualTo("partPubDLQ.0-0"); - assertThat(received.getMessageProperties().getHeaders()).doesNotContainKey(BinderHeaders.PARTITION_HEADER); + assertThat( + received.getMessageProperties().getHeaders().get("x-original-routingKey")) + .isEqualTo("partPubDLQ.0-0"); + assertThat(received.getMessageProperties().getHeaders()) + .doesNotContainKey(BinderHeaders.PARTITION_HEADER); - // verify we got a message on the dedicated error channel and the global (via bridge) + // verify we got a message on the dedicated error channel and the global (via + // bridge) assertThat(boundErrorChannelMessage.get()).isNotNull(); assertThat(globalErrorChannelMessage.get()).isNotNull(); assertThat(hasRecovererInCallStack.get()).isEqualTo(withRetry); @@ -1018,9 +1120,11 @@ public class RabbitBinderTests extends properties.setPartitionKeyExtractorClass(PartitionTestSupport.class); properties.setPartitionSelectorClass(PartitionTestSupport.class); properties.setPartitionCount(2); - DirectChannel output = createBindableChannel("output", createProducerBindingProperties(properties)); + DirectChannel output = createBindableChannel("output", + createProducerBindingProperties(properties)); output.setBeanName("test.output"); - Binding outputBinding = binder.bindProducer("partDLQ.1", output, properties); + Binding outputBinding = binder.bindProducer("partDLQ.1", output, + properties); ExtendedConsumerProperties consumerProperties = createConsumerProperties(); consumerProperties.getExtension().setPrefix("bindertest."); @@ -1028,19 +1132,21 @@ public class RabbitBinderTests extends consumerProperties.setMaxAttempts(1); // disable retry consumerProperties.setPartitioned(true); consumerProperties.setInstanceIndex(0); - DirectChannel input0 = createBindableChannel("input", createConsumerBindingProperties(consumerProperties)); + DirectChannel input0 = createBindableChannel("input", + createConsumerBindingProperties(consumerProperties)); input0.setBeanName("test.input0DLQ"); - Binding input0Binding = binder.bindConsumer("partDLQ.1", "dlqPartGrp", input0, - consumerProperties); - Binding defaultConsumerBinding1 = binder.bindConsumer("partDLQ.1", "defaultConsumer", - new QueueChannel(), consumerProperties); + Binding input0Binding = binder.bindConsumer("partDLQ.1", + "dlqPartGrp", input0, consumerProperties); + Binding defaultConsumerBinding1 = binder.bindConsumer("partDLQ.1", + "defaultConsumer", new QueueChannel(), consumerProperties); consumerProperties.setInstanceIndex(1); - DirectChannel input1 = createBindableChannel("input1", createConsumerBindingProperties(consumerProperties)); + DirectChannel input1 = createBindableChannel("input1", + createConsumerBindingProperties(consumerProperties)); input1.setBeanName("test.input1DLQ"); - Binding input1Binding = binder.bindConsumer("partDLQ.1", "dlqPartGrp", input1, - consumerProperties); - Binding defaultConsumerBinding2 = binder.bindConsumer("partDLQ.1", "defaultConsumer", - new QueueChannel(), consumerProperties); + Binding input1Binding = binder.bindConsumer("partDLQ.1", + "dlqPartGrp", input1, consumerProperties); + Binding defaultConsumerBinding2 = binder.bindConsumer("partDLQ.1", + "defaultConsumer", new QueueChannel(), consumerProperties); final CountDownLatch latch0 = new CountDownLatch(1); input0.subscribe(new MessageHandler() { @@ -1076,7 +1182,8 @@ public class RabbitBinderTests extends output.send(new GenericMessage(1)); - RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource()); + RabbitTemplate template = new RabbitTemplate( + this.rabbitAvailableRule.getResource()); template.setReceiveTimeout(10000); String streamDLQName = "bindertest.partDLQ.1.dlqPartGrp.dlq"; @@ -1085,15 +1192,18 @@ public class RabbitBinderTests extends assertThat(received).isNotNull(); assertThat(received.getMessageProperties().getReceivedRoutingKey()) .isEqualTo("bindertest.partDLQ.1.dlqPartGrp-1"); - assertThat(received.getMessageProperties().getHeaders()).doesNotContainKey(BinderHeaders.PARTITION_HEADER); - assertThat(received.getMessageProperties().getReceivedDeliveryMode()).isEqualTo(MessageDeliveryMode.PERSISTENT); + assertThat(received.getMessageProperties().getHeaders()) + .doesNotContainKey(BinderHeaders.PARTITION_HEADER); + assertThat(received.getMessageProperties().getReceivedDeliveryMode()) + .isEqualTo(MessageDeliveryMode.PERSISTENT); output.send(new GenericMessage(0)); received = template.receive(streamDLQName); assertThat(received).isNotNull(); assertThat(received.getMessageProperties().getReceivedRoutingKey()) - .isEqualTo("bindertest.partDLQ.1.dlqPartGrp-0"); - assertThat(received.getMessageProperties().getHeaders()).doesNotContainKey(BinderHeaders.PARTITION_HEADER); + .isEqualTo("bindertest.partDLQ.1.dlqPartGrp-0"); + assertThat(received.getMessageProperties().getHeaders()) + .doesNotContainKey(BinderHeaders.PARTITION_HEADER); input0Binding.unbind(); input1Binding.unbind(); @@ -1104,7 +1214,8 @@ public class RabbitBinderTests extends @Test public void testAutoBindDLQwithRepublish() throws Exception { - this.maxStackTraceSize = RabbitUtils.getMaxFrame(rabbitAvailableRule.getResource()) - 20_000; + this.maxStackTraceSize = RabbitUtils + .getMaxFrame(rabbitAvailableRule.getResource()) - 20_000; assertThat(this.maxStackTraceSize).isGreaterThan(0); RabbitTestBinder binder = getBinder(); @@ -1114,10 +1225,13 @@ public class RabbitBinderTests extends consumerProperties.getExtension().setRepublishToDlq(true); consumerProperties.setMaxAttempts(1); // disable retry consumerProperties.getExtension().setDurableSubscription(true); - DirectChannel moduleInputChannel = createBindableChannel("input", createConsumerBindingProperties(consumerProperties)); + DirectChannel moduleInputChannel = createBindableChannel("input", + createConsumerBindingProperties(consumerProperties)); moduleInputChannel.setBeanName("dlqPubTest"); - RuntimeException exception = bigCause(new RuntimeException(BIG_EXCEPTION_MESSAGE)); - assertThat(getStackTraceAsString(exception).length()).isGreaterThan(this.maxStackTraceSize); + RuntimeException exception = bigCause( + new RuntimeException(BIG_EXCEPTION_MESSAGE)); + assertThat(getStackTraceAsString(exception).length()) + .isGreaterThan(this.maxStackTraceSize); AtomicBoolean dontRepublish = new AtomicBoolean(); moduleInputChannel.subscribe(new MessageHandler() { @@ -1131,27 +1245,32 @@ public class RabbitBinderTests extends }); consumerProperties.setMultiplex(true); - Binding consumerBinding = binder.bindConsumer("foo.dlqpubtest,foo.dlqpubtest2", "foo", - moduleInputChannel, consumerProperties); + Binding consumerBinding = binder.bindConsumer( + "foo.dlqpubtest,foo.dlqpubtest2", "foo", moduleInputChannel, + consumerProperties); - RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource()); + RabbitTemplate template = new RabbitTemplate( + this.rabbitAvailableRule.getResource()); template.convertAndSend("", TEST_PREFIX + "foo.dlqpubtest.foo", "foo"); template.setReceiveTimeout(10_000); - org.springframework.amqp.core.Message deadLetter = template.receive(TEST_PREFIX + "foo.dlqpubtest.foo.dlq"); + org.springframework.amqp.core.Message deadLetter = template + .receive(TEST_PREFIX + "foo.dlqpubtest.foo.dlq"); assertThat(deadLetter).isNotNull(); assertThat(new String(deadLetter.getBody())).isEqualTo("foo"); assertThat(deadLetter.getMessageProperties().getHeaders()) .containsKey((RepublishMessageRecoverer.X_EXCEPTION_STACKTRACE)); assertThat(((LongString) deadLetter.getMessageProperties().getHeaders() - .get(RepublishMessageRecoverer.X_EXCEPTION_STACKTRACE)).length()).isEqualTo(this.maxStackTraceSize); + .get(RepublishMessageRecoverer.X_EXCEPTION_STACKTRACE)).length()) + .isEqualTo(this.maxStackTraceSize); template.convertAndSend("", TEST_PREFIX + "foo.dlqpubtest2.foo", "bar"); deadLetter = template.receive(TEST_PREFIX + "foo.dlqpubtest2.foo.dlq"); assertThat(deadLetter).isNotNull(); assertThat(new String(deadLetter.getBody())).isEqualTo("bar"); - assertThat(deadLetter.getMessageProperties().getHeaders()).containsKey(("x-exception-stacktrace")); + assertThat(deadLetter.getMessageProperties().getHeaders()) + .containsKey(("x-exception-stacktrace")); dontRepublish.set(true); template.convertAndSend("", TEST_PREFIX + "foo.dlqpubtest2.foo", "baz"); @@ -1166,7 +1285,8 @@ public class RabbitBinderTests extends public void testBatchingAndCompression() throws Exception { RabbitTestBinder binder = getBinder(); ExtendedProducerProperties producerProperties = createProducerProperties(); - producerProperties.getExtension().setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT); + producerProperties.getExtension() + .setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT); producerProperties.getExtension().setBatchingEnabled(true); producerProperties.getExtension().setBatchSize(2); producerProperties.getExtension().setBatchBufferLimit(100000); @@ -1174,24 +1294,29 @@ public class RabbitBinderTests extends producerProperties.getExtension().setCompress(true); producerProperties.setRequiredGroups("default"); - DirectChannel output = createBindableChannel("output", createProducerBindingProperties(producerProperties)); + DirectChannel output = createBindableChannel("output", + createProducerBindingProperties(producerProperties)); output.setBeanName("batchingProducer"); - Binding producerBinding = binder.bindProducer("batching.0", output, producerProperties); + Binding 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); + 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); + 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"); + assertThat(new String((byte[]) out)) + .isEqualTo("\u0000\u0000\u0000\u0003foo\u0000\u0000\u0000\u0003bar"); ArgumentCaptor captor = ArgumentCaptor.forClass(Object.class); verify(logger).trace(captor.capture()); @@ -1199,8 +1324,8 @@ public class RabbitBinderTests extends QueueChannel input = new QueueChannel(); input.setBeanName("batchingConsumer"); - Binding consumerBinding = binder.bindConsumer("batching.0", "test", input, - createConsumerProperties()); + Binding consumerBinding = binder.bindConsumer("batching.0", + "test", input, createConsumerProperties()); output.send(new GenericMessage<>("foo".getBytes())); output.send(new GenericMessage<>("bar".getBytes())); @@ -1224,10 +1349,11 @@ public class RabbitBinderTests extends @Test public void testLateBinding() throws Exception { RabbitTestSupport.RabbitProxy proxy = new RabbitTestSupport.RabbitProxy(); - CachingConnectionFactory cf = new CachingConnectionFactory("localhost", proxy.getPort()); + CachingConnectionFactory cf = new CachingConnectionFactory("localhost", + proxy.getPort()); - RabbitMessageChannelBinder rabbitBinder = new RabbitMessageChannelBinder(cf, new RabbitProperties(), - new RabbitExchangeQueueProvisioner(cf)); + RabbitMessageChannelBinder rabbitBinder = new RabbitMessageChannelBinder(cf, + new RabbitProperties(), new RabbitExchangeQueueProvisioner(cf)); RabbitTestBinder binder = new RabbitTestBinder(cf, rabbitBinder); ExtendedProducerProperties producerProperties = createProducerProperties(); @@ -1235,22 +1361,27 @@ public class RabbitBinderTests extends producerProperties.getExtension().setAutoBindDlq(true); producerProperties.getExtension().setTransacted(true); - MessageChannel moduleOutputChannel = createBindableChannel("output", createProducerBindingProperties(producerProperties)); - Binding late0ProducerBinding = binder.bindProducer("late.0", moduleOutputChannel, producerProperties); + MessageChannel moduleOutputChannel = createBindableChannel("output", + createProducerBindingProperties(producerProperties)); + Binding late0ProducerBinding = binder.bindProducer("late.0", + moduleOutputChannel, producerProperties); QueueChannel moduleInputChannel = new QueueChannel(); ExtendedConsumerProperties rabbitConsumerProperties = createConsumerProperties(); rabbitConsumerProperties.getExtension().setPrefix("latebinder."); - Binding late0ConsumerBinding = binder.bindConsumer("late.0", "test", moduleInputChannel, - rabbitConsumerProperties); + Binding late0ConsumerBinding = binder.bindConsumer("late.0", + "test", moduleInputChannel, rabbitConsumerProperties); - producerProperties.setPartitionKeyExpression(spelExpressionParser.parseExpression("payload.equals('0') ? 0 : 1")); - producerProperties.setPartitionSelectorExpression(spelExpressionParser.parseExpression("hashCode()")); + producerProperties.setPartitionKeyExpression( + spelExpressionParser.parseExpression("payload.equals('0') ? 0 : 1")); + producerProperties.setPartitionSelectorExpression( + spelExpressionParser.parseExpression("hashCode()")); producerProperties.setPartitionCount(2); - MessageChannel partOutputChannel = createBindableChannel("output", createProducerBindingProperties(producerProperties)); - Binding partlate0ProducerBinding = binder.bindProducer("partlate.0", partOutputChannel, - producerProperties); + MessageChannel partOutputChannel = createBindableChannel("output", + createProducerBindingProperties(producerProperties)); + Binding partlate0ProducerBinding = binder + .bindProducer("partlate.0", partOutputChannel, producerProperties); QueueChannel partInputChannel0 = new QueueChannel(); QueueChannel partInputChannel1 = new QueueChannel(); @@ -1259,50 +1390,57 @@ public class RabbitBinderTests extends partLateConsumerProperties.getExtension().setPrefix("latebinder."); partLateConsumerProperties.setPartitioned(true); partLateConsumerProperties.setInstanceIndex(0); - Binding partlate0Consumer0Binding = binder.bindConsumer("partlate.0", "test", partInputChannel0, - partLateConsumerProperties); + Binding partlate0Consumer0Binding = binder.bindConsumer( + "partlate.0", "test", partInputChannel0, partLateConsumerProperties); partLateConsumerProperties.setInstanceIndex(1); - Binding partlate0Consumer1Binding = binder.bindConsumer("partlate.0", "test", partInputChannel1, - partLateConsumerProperties); + Binding partlate0Consumer1Binding = binder.bindConsumer( + "partlate.0", "test", partInputChannel1, partLateConsumerProperties); ExtendedProducerProperties noDlqProducerProperties = createProducerProperties(); noDlqProducerProperties.getExtension().setPrefix("latebinder."); MessageChannel noDLQOutputChannel = createBindableChannel("output", createProducerBindingProperties(noDlqProducerProperties)); - Binding noDlqProducerBinding = binder.bindProducer("lateNoDLQ.0", noDLQOutputChannel, - noDlqProducerProperties); + Binding noDlqProducerBinding = binder.bindProducer("lateNoDLQ.0", + noDLQOutputChannel, noDlqProducerProperties); QueueChannel noDLQInputChannel = new QueueChannel(); ExtendedConsumerProperties noDlqConsumerProperties = createConsumerProperties(); noDlqConsumerProperties.getExtension().setPrefix("latebinder."); - Binding noDlqConsumerBinding = binder.bindConsumer("lateNoDLQ.0", "test", noDLQInputChannel, - noDlqConsumerProperties); + Binding noDlqConsumerBinding = binder.bindConsumer("lateNoDLQ.0", + "test", noDLQInputChannel, noDlqConsumerProperties); - MessageChannel outputChannel = createBindableChannel("output", createProducerBindingProperties(noDlqProducerProperties)); - Binding pubSubProducerBinding = binder.bindProducer("latePubSub", outputChannel, - noDlqProducerProperties); + MessageChannel outputChannel = createBindableChannel("output", + createProducerBindingProperties(noDlqProducerProperties)); + Binding pubSubProducerBinding = binder.bindProducer("latePubSub", + outputChannel, noDlqProducerProperties); QueueChannel pubSubInputChannel = new QueueChannel(); noDlqConsumerProperties.getExtension().setDurableSubscription(false); - Binding nonDurableConsumerBinding = binder.bindConsumer("latePubSub", "lategroup", - pubSubInputChannel, noDlqConsumerProperties); + Binding nonDurableConsumerBinding = binder.bindConsumer( + "latePubSub", "lategroup", pubSubInputChannel, noDlqConsumerProperties); QueueChannel durablePubSubInputChannel = new QueueChannel(); noDlqConsumerProperties.getExtension().setDurableSubscription(true); - Binding durableConsumerBinding = binder.bindConsumer("latePubSub", "lateDurableGroup", - durablePubSubInputChannel, noDlqConsumerProperties); + Binding durableConsumerBinding = binder.bindConsumer("latePubSub", + "lateDurableGroup", durablePubSubInputChannel, noDlqConsumerProperties); proxy.start(); - moduleOutputChannel.send(MessageBuilder.withPayload("foo").setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN).build()); + moduleOutputChannel.send(MessageBuilder.withPayload("foo") + .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN) + .build()); Message message = moduleInputChannel.receive(10000); assertThat(message).isNotNull(); assertThat(message.getPayload()).isNotNull(); - noDLQOutputChannel.send(MessageBuilder.withPayload("bar").setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN).build()); + noDLQOutputChannel.send(MessageBuilder.withPayload("bar") + .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN) + .build()); message = noDLQInputChannel.receive(10000); assertThat(message); assertThat(message.getPayload()).isEqualTo("bar".getBytes()); - outputChannel.send(MessageBuilder.withPayload("baz").setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN).build()); + outputChannel.send(MessageBuilder.withPayload("baz") + .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN) + .build()); message = pubSubInputChannel.receive(10000); assertThat(message); assertThat(message.getPayload()).isEqualTo("baz".getBytes()); @@ -1310,8 +1448,12 @@ public class RabbitBinderTests extends assertThat(message).isNotNull(); assertThat(message.getPayload()).isEqualTo("baz".getBytes()); - partOutputChannel.send(MessageBuilder.withPayload("0").setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN).build()); - partOutputChannel.send(MessageBuilder.withPayload("1").setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN).build()); + partOutputChannel.send(MessageBuilder.withPayload("0") + .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN) + .build()); + partOutputChannel.send(MessageBuilder.withPayload("1") + .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN) + .build()); message = partInputChannel0.receive(10000); assertThat(message).isNotNull(); assertThat(message.getPayload()).isEqualTo("0".getBytes()); @@ -1343,10 +1485,11 @@ public class RabbitBinderTests extends RabbitTestBinder binder = getBinder(); ConfigurableApplicationContext context = binder.getApplicationContext(); ConfigurableListableBeanFactory bf = context.getBeanFactory(); - bf.registerSingleton("testBadUserDeclarationsFatal", new Queue("testBadUserDeclarationsFatal", false)); + bf.registerSingleton("testBadUserDeclarationsFatal", + new Queue("testBadUserDeclarationsFatal", false)); bf.registerSingleton("binder", binder); - RabbitExchangeQueueProvisioner provisioner = TestUtils.getPropertyValue(binder, "binder.provisioningProvider", - RabbitExchangeQueueProvisioner.class); + RabbitExchangeQueueProvisioner provisioner = TestUtils.getPropertyValue(binder, + "binder.provisioningProvider", RabbitExchangeQueueProvisioner.class); bf.initializeBean(provisioner, "provisioner"); bf.registerSingleton("provisioner", provisioner); context.addApplicationListener(provisioner); @@ -1360,7 +1503,9 @@ public class RabbitBinderTests extends // the mis-configured queue should be fatal Binding binding = null; try { - binding = binder.bindConsumer("input", "baddecls", this.createBindableChannel("input", new BindingProperties()), createConsumerProperties()); + binding = binder.bindConsumer("input", "baddecls", + this.createBindableChannel("input", new BindingProperties()), + createConsumerProperties()); fail("Expected exception"); } catch (BinderException e) { @@ -1378,16 +1523,20 @@ public class RabbitBinderTests extends public void testRoutingKeyExpression() throws Exception { RabbitTestBinder binder = getBinder(); ExtendedProducerProperties producerProperties = createProducerProperties(); - producerProperties.getExtension().setRoutingKeyExpression(spelExpressionParser.parseExpression("payload.field")); + producerProperties.getExtension().setRoutingKeyExpression( + spelExpressionParser.parseExpression("payload.field")); - DirectChannel output = createBindableChannel("output", createProducerBindingProperties(producerProperties)); + DirectChannel output = createBindableChannel("output", + createProducerBindingProperties(producerProperties)); output.setBeanName("rkeProducer"); - Binding producerBinding = binder.bindProducer("rke", output, producerProperties); + Binding producerBinding = binder.bindProducer("rke", output, + producerProperties); RabbitAdmin admin = new RabbitAdmin(this.rabbitAvailableRule.getResource()); Queue queue = new AnonymousQueue(); TopicExchange exchange = new TopicExchange("rke"); - org.springframework.amqp.core.Binding binding = BindingBuilder.bind(queue).to(exchange).with("rkeTest"); + org.springframework.amqp.core.Binding binding = BindingBuilder.bind(queue) + .to(exchange).with("rkeTest"); admin.declareQueue(queue); admin.declareBinding(binding); @@ -1395,8 +1544,9 @@ public class RabbitBinderTests extends @Override public Message preSend(Message message, MessageChannel channel) { - assertThat(message.getHeaders().get(RabbitExpressionEvaluatingInterceptor.ROUTING_KEY_HEADER)) - .isEqualTo("rkeTest"); + assertThat(message.getHeaders() + .get(RabbitExpressionEvaluatingInterceptor.ROUTING_KEY_HEADER)) + .isEqualTo("rkeTest"); return message; } @@ -1406,7 +1556,8 @@ public class RabbitBinderTests extends Object out = spyOn(queue.getName()).receive(false); assertThat(out).isInstanceOf(byte[].class); - assertThat(new String((byte[]) out, StandardCharsets.UTF_8)).isEqualTo("{\"field\":\"rkeTest\"}"); + assertThat(new String((byte[]) out, StandardCharsets.UTF_8)) + .isEqualTo("{\"field\":\"rkeTest\"}"); producerBinding.unbind(); } @@ -1415,21 +1566,25 @@ public class RabbitBinderTests extends public void testRoutingKeyExpressionPartitionedAndDelay() throws Exception { RabbitTestBinder binder = getBinder(); ExtendedProducerProperties producerProperties = createProducerProperties(); - producerProperties.getExtension().setRoutingKeyExpression(spelExpressionParser.parseExpression("payload.field")); + producerProperties.getExtension().setRoutingKeyExpression( + spelExpressionParser.parseExpression("payload.field")); // requires delayed message exchange plugin; tested locally -// producerProperties.getExtension().setDelayedExchange(true); - producerProperties.getExtension().setDelayExpression(spelExpressionParser.parseExpression("1000")); + // producerProperties.getExtension().setDelayedExchange(true); + producerProperties.getExtension() + .setDelayExpression(spelExpressionParser.parseExpression("1000")); producerProperties.setPartitionKeyExpression(new ValueExpression<>(0)); - DirectChannel output = createBindableChannel("output", createProducerBindingProperties(producerProperties)); + DirectChannel output = createBindableChannel("output", + createProducerBindingProperties(producerProperties)); output.setBeanName("rkeProducer"); - Binding producerBinding = binder.bindProducer("rkep", output, producerProperties); + Binding producerBinding = binder.bindProducer("rkep", output, + producerProperties); RabbitAdmin admin = new RabbitAdmin(this.rabbitAvailableRule.getResource()); Queue queue = new AnonymousQueue(); TopicExchange exchange = new TopicExchange("rkep"); - org.springframework.amqp.core.Binding binding = - BindingBuilder.bind(queue).to(exchange).with("rkepTest-0"); + org.springframework.amqp.core.Binding binding = BindingBuilder.bind(queue) + .to(exchange).with("rkepTest-0"); admin.declareQueue(queue); admin.declareBinding(binding); @@ -1437,10 +1592,12 @@ public class RabbitBinderTests extends @Override public Message preSend(Message message, MessageChannel channel) { - assertThat(message.getHeaders().get(RabbitExpressionEvaluatingInterceptor.ROUTING_KEY_HEADER)) - .isEqualTo("rkepTest"); - assertThat(message.getHeaders().get(RabbitExpressionEvaluatingInterceptor.DELAY_HEADER)) - .isEqualTo(1000); + assertThat(message.getHeaders() + .get(RabbitExpressionEvaluatingInterceptor.ROUTING_KEY_HEADER)) + .isEqualTo("rkepTest"); + assertThat(message.getHeaders() + .get(RabbitExpressionEvaluatingInterceptor.DELAY_HEADER)) + .isEqualTo(1000); return message; } @@ -1450,7 +1607,8 @@ public class RabbitBinderTests extends Object out = spyOn(queue.getName()).receive(false); assertThat(out).isInstanceOf(byte[].class); - assertThat(new String((byte[]) out, StandardCharsets.UTF_8)).isEqualTo("{\"field\":\"rkepTest\"}"); + assertThat(new String((byte[]) out, StandardCharsets.UTF_8)) + .isEqualTo("{\"field\":\"rkepTest\"}"); producerBinding.unbind(); } @@ -1458,10 +1616,12 @@ public class RabbitBinderTests extends @Test public void testPolledConsumer() throws Exception { RabbitTestBinder binder = getBinder(); - PollableSource inboundBindTarget = new DefaultPollableMessageSource(this.messageConverter); - Binding> binding = binder.bindPollableConsumer("pollable", "group", - inboundBindTarget, createConsumerProperties()); - RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource()); + PollableSource inboundBindTarget = new DefaultPollableMessageSource( + this.messageConverter); + Binding> binding = binder.bindPollableConsumer( + "pollable", "group", inboundBindTarget, createConsumerProperties()); + RabbitTemplate template = new RabbitTemplate( + this.rabbitAvailableRule.getResource()); template.convertAndSend("pollable.group", "testPollable"); boolean polled = inboundBindTarget.poll(m -> { assertThat(m.getPayload()).isEqualTo("testPollable"); @@ -1479,11 +1639,13 @@ public class RabbitBinderTests extends @Test public void testPolledConsumerRequeue() throws Exception { RabbitTestBinder binder = getBinder(); - PollableSource inboundBindTarget = new DefaultPollableMessageSource(this.messageConverter); + PollableSource inboundBindTarget = new DefaultPollableMessageSource( + this.messageConverter); ExtendedConsumerProperties properties = createConsumerProperties(); - Binding> binding = binder.bindPollableConsumer("pollableRequeue", "group", - inboundBindTarget, properties); - RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource()); + Binding> binding = binder.bindPollableConsumer( + "pollableRequeue", "group", inboundBindTarget, properties); + RabbitTemplate template = new RabbitTemplate( + this.rabbitAvailableRule.getResource()); template.convertAndSend("pollableRequeue.group", "testPollable"); try { boolean polled = false; @@ -1508,14 +1670,16 @@ public class RabbitBinderTests extends @Test public void testPolledConsumerWithDlq() throws Exception { RabbitTestBinder binder = getBinder(); - PollableSource inboundBindTarget = new DefaultPollableMessageSource(this.messageConverter); + PollableSource inboundBindTarget = new DefaultPollableMessageSource( + this.messageConverter); ExtendedConsumerProperties properties = createConsumerProperties(); properties.setMaxAttempts(2); properties.setBackOffInitialInterval(0); properties.getExtension().setAutoBindDlq(true); - Binding> binding = binder.bindPollableConsumer("pollableDlq", "group", - inboundBindTarget, properties); - RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource()); + Binding> binding = binder.bindPollableConsumer( + "pollableDlq", "group", inboundBindTarget, properties); + RabbitTemplate template = new RabbitTemplate( + this.rabbitAvailableRule.getResource()); template.convertAndSend("pollableDlq.group", "testPollable"); try { int n = 0; @@ -1527,10 +1691,12 @@ public class RabbitBinderTests extends } } catch (MessageHandlingException e) { - assertThat(e.getCause().getCause().getCause().getCause().getCause().getMessage()) - .isEqualTo("test DLQ"); + assertThat( + e.getCause().getCause().getCause().getCause().getCause().getMessage()) + .isEqualTo("test DLQ"); } - org.springframework.amqp.core.Message deadLetter = template.receive("pollableDlq.group.dlq", 10_000); + org.springframework.amqp.core.Message deadLetter = template + .receive("pollableDlq.group.dlq", 10_000); assertThat(deadLetter).isNotNull(); binding.unbind(); } @@ -1538,14 +1704,16 @@ public class RabbitBinderTests extends @Test public void testPolledConsumerWithDlqNoRetry() throws Exception { RabbitTestBinder binder = getBinder(); - PollableSource inboundBindTarget = new DefaultPollableMessageSource(this.messageConverter); + PollableSource inboundBindTarget = new DefaultPollableMessageSource( + this.messageConverter); ExtendedConsumerProperties properties = createConsumerProperties(); properties.setMaxAttempts(1); -// properties.getExtension().setRequeueRejected(true); // loops, correctly + // properties.getExtension().setRequeueRejected(true); // loops, correctly properties.getExtension().setAutoBindDlq(true); - Binding> binding = binder.bindPollableConsumer("pollableDlqNoRetry", "group", - inboundBindTarget, properties); - RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource()); + Binding> binding = binder.bindPollableConsumer( + "pollableDlqNoRetry", "group", inboundBindTarget, properties); + RabbitTemplate template = new RabbitTemplate( + this.rabbitAvailableRule.getResource()); template.convertAndSend("pollableDlqNoRetry.group", "testPollable"); try { int n = 0; @@ -1559,7 +1727,8 @@ public class RabbitBinderTests extends catch (MessageHandlingException e) { assertThat(e.getCause().getMessage()).isEqualTo("test DLQ"); } - org.springframework.amqp.core.Message deadLetter = template.receive("pollableDlqNoRetry.group.dlq", 10_000); + org.springframework.amqp.core.Message deadLetter = template + .receive("pollableDlqNoRetry.group.dlq", 10_000); assertThat(deadLetter).isNotNull(); binding.unbind(); } @@ -1567,15 +1736,17 @@ public class RabbitBinderTests extends @Test public void testPolledConsumerWithDlqRePub() throws Exception { RabbitTestBinder binder = getBinder(); - PollableSource inboundBindTarget = new DefaultPollableMessageSource(this.messageConverter); + PollableSource inboundBindTarget = new DefaultPollableMessageSource( + this.messageConverter); ExtendedConsumerProperties properties = createConsumerProperties(); properties.setMaxAttempts(2); properties.setBackOffInitialInterval(0); properties.getExtension().setAutoBindDlq(true); properties.getExtension().setRepublishToDlq(true); - Binding> binding = binder.bindPollableConsumer("pollableDlqRePub", "group", - inboundBindTarget, properties); - RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource()); + Binding> binding = binder.bindPollableConsumer( + "pollableDlqRePub", "group", inboundBindTarget, properties); + RabbitTemplate template = new RabbitTemplate( + this.rabbitAvailableRule.getResource()); template.convertAndSend("pollableDlqRePub.group", "testPollable"); boolean polled = false; int n = 0; @@ -1586,7 +1757,8 @@ public class RabbitBinderTests extends }); } assertThat(polled).isTrue(); - org.springframework.amqp.core.Message deadLetter = template.receive("pollableDlqRePub.group.dlq", 10_000); + org.springframework.amqp.core.Message deadLetter = template + .receive("pollableDlqRePub.group.dlq", 10_000); assertThat(deadLetter).isNotNull(); binding.unbind(); } @@ -1598,22 +1770,32 @@ public class RabbitBinderTests extends SimpleMessageListenerContainer.class); assertThat(container.getAcknowledgeMode()).isEqualTo(AcknowledgeMode.NONE); assertThat(container.getQueueNames()[0]).startsWith("foo.props.0"); - assertThat(TestUtils.getPropertyValue(container, "transactional", Boolean.class)).isFalse(); - assertThat(TestUtils.getPropertyValue(container, "concurrentConsumers")).isEqualTo(2); - assertThat(TestUtils.getPropertyValue(container, "maxConcurrentConsumers")).isEqualTo(3); - assertThat(TestUtils.getPropertyValue(container, "defaultRequeueRejected", Boolean.class)).isFalse(); + assertThat(TestUtils.getPropertyValue(container, "transactional", Boolean.class)) + .isFalse(); + assertThat(TestUtils.getPropertyValue(container, "concurrentConsumers")) + .isEqualTo(2); + assertThat(TestUtils.getPropertyValue(container, "maxConcurrentConsumers")) + .isEqualTo(3); + assertThat(TestUtils.getPropertyValue(container, "defaultRequeueRejected", + Boolean.class)).isFalse(); assertThat(TestUtils.getPropertyValue(container, "prefetchCount")).isEqualTo(20); assertThat(TestUtils.getPropertyValue(container, "txSize")).isEqualTo(10); - retry = TestUtils.getPropertyValue(endpoint, "retryTemplate", RetryTemplate.class); - assertThat(TestUtils.getPropertyValue(retry, "retryPolicy.maxAttempts")).isEqualTo(23); - assertThat(TestUtils.getPropertyValue(retry, "backOffPolicy.initialInterval")).isEqualTo(2000L); - assertThat(TestUtils.getPropertyValue(retry, "backOffPolicy.maxInterval")).isEqualTo(20000L); - assertThat(TestUtils.getPropertyValue(retry, "backOffPolicy.multiplier")).isEqualTo(5.0); + retry = TestUtils.getPropertyValue(endpoint, "retryTemplate", + RetryTemplate.class); + assertThat(TestUtils.getPropertyValue(retry, "retryPolicy.maxAttempts")) + .isEqualTo(23); + assertThat(TestUtils.getPropertyValue(retry, "backOffPolicy.initialInterval")) + .isEqualTo(2000L); + assertThat(TestUtils.getPropertyValue(retry, "backOffPolicy.maxInterval")) + .isEqualTo(20000L); + assertThat(TestUtils.getPropertyValue(retry, "backOffPolicy.multiplier")) + .isEqualTo(5.0); - List requestMatchers = TestUtils.getPropertyValue(endpoint, "headerMapper.requestHeaderMatcher.matchers", - List.class); + List requestMatchers = TestUtils.getPropertyValue(endpoint, + "headerMapper.requestHeaderMatcher.matchers", List.class); assertThat(requestMatchers).hasSize(1); - assertThat(TestUtils.getPropertyValue(requestMatchers.get(0), "pattern")).isEqualTo("foo"); + assertThat(TestUtils.getPropertyValue(requestMatchers.get(0), "pattern")) + .isEqualTo("foo"); return container; } @@ -1622,12 +1804,14 @@ public class RabbitBinderTests extends List requestMatchers = TestUtils.getPropertyValue(endpoint, "headerMapper.requestHeaderMatcher.matchers", List.class); assertThat(requestMatchers).hasSize(2); - assertThat(TestUtils.getPropertyValue(requestMatchers.get(1), "pattern")).isEqualTo("foo"); + assertThat(TestUtils.getPropertyValue(requestMatchers.get(1), "pattern")) + .isEqualTo("foo"); } @Override protected String getEndpointRouting(Object endpoint) { - return TestUtils.getPropertyValue(endpoint, "routingKeyExpression", SpelExpression.class) + return TestUtils + .getPropertyValue(endpoint, "routingKeyExpression", SpelExpression.class) .getExpressionString(); } @@ -1643,29 +1827,35 @@ public class RabbitBinderTests extends @Override protected void checkRkExpressionForPartitionedModuleSpEL(Object endpoint) { - assertThat(getEndpointRouting(endpoint)).contains(getExpectedRoutingBaseDestination("'part.0'", "test") - + " + '-' + headers['" + BinderHeaders.PARTITION_HEADER + "']"); + assertThat(getEndpointRouting(endpoint)) + .contains(getExpectedRoutingBaseDestination("'part.0'", "test") + + " + '-' + headers['" + BinderHeaders.PARTITION_HEADER + "']"); } @Override public Spy spyOn(final String queue) { - final RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource()); - template.setAfterReceivePostProcessors(new DelegatingDecompressingPostProcessor()); + final RabbitTemplate template = new RabbitTemplate( + this.rabbitAvailableRule.getResource()); + template.setAfterReceivePostProcessors( + new DelegatingDecompressingPostProcessor()); return new Spy() { @Override public Object receive(boolean expectNull) throws Exception { if (expectNull) { Thread.sleep(50); - return template.receiveAndConvert(new RabbitConsumerProperties().getPrefix() + queue); + return template.receiveAndConvert( + new RabbitConsumerProperties().getPrefix() + queue); } Object bar = null; int n = 0; while (n++ < 100 && bar == null) { - bar = template.receiveAndConvert(new RabbitConsumerProperties().getPrefix() + queue); + bar = template.receiveAndConvert( + new RabbitConsumerProperties().getPrefix() + queue); Thread.sleep(100); } - assertThat(n).isLessThan(100).withFailMessage("Message did not arrive in RabbitMQ"); + assertThat(n).isLessThan(100) + .withFailMessage("Message did not arrive in RabbitMQ"); return bar; } @@ -1686,7 +1876,8 @@ public class RabbitBinderTests extends return stringWriter.getBuffer().toString(); } - public static class TestPartitionKeyExtractorClass implements PartitionKeyExtractorStrategy { + public static class TestPartitionKeyExtractorClass + implements PartitionKeyExtractorStrategy { @Override public Object extractKey(Message message) { @@ -1712,17 +1903,14 @@ public class RabbitBinderTests extends super(); } - public Pojo(String field) { this.field = field; } - public String getField() { return this.field; } - public void setField(String field) { this.field = field; } diff --git a/spring-cloud-stream-binder-rabbit/src/test/java/org/springframework/cloud/stream/binder/rabbit/RabbitTestBinder.java b/spring-cloud-stream-binder-rabbit/src/test/java/org/springframework/cloud/stream/binder/rabbit/RabbitTestBinder.java index 4b4a6d382..d6bffdbed 100644 --- a/spring-cloud-stream-binder-rabbit/src/test/java/org/springframework/cloud/stream/binder/rabbit/RabbitTestBinder.java +++ b/spring-cloud-stream-binder-rabbit/src/test/java/org/springframework/cloud/stream/binder/rabbit/RabbitTestBinder.java @@ -47,8 +47,7 @@ import org.springframework.util.StringUtils; * @author Mark Fisher */ public class RabbitTestBinder extends - AbstractPollableConsumerTestBinder, ExtendedProducerProperties> { + AbstractPollableConsumerTestBinder, ExtendedProducerProperties> { private final RabbitAdmin rabbitAdmin; @@ -60,12 +59,14 @@ public class RabbitTestBinder extends private final AnnotationConfigApplicationContext applicationContext; - public RabbitTestBinder(ConnectionFactory connectionFactory, RabbitProperties rabbitProperties) { - this(connectionFactory, new RabbitMessageChannelBinder(connectionFactory, rabbitProperties, - new RabbitExchangeQueueProvisioner(connectionFactory))); + public RabbitTestBinder(ConnectionFactory connectionFactory, + RabbitProperties rabbitProperties) { + this(connectionFactory, new RabbitMessageChannelBinder(connectionFactory, + rabbitProperties, new RabbitExchangeQueueProvisioner(connectionFactory))); } - public RabbitTestBinder(ConnectionFactory connectionFactory, RabbitMessageChannelBinder binder) { + public RabbitTestBinder(ConnectionFactory connectionFactory, + RabbitMessageChannelBinder binder) { this.applicationContext = new AnnotationConfigApplicationContext(Config.class); binder.setApplicationContext(this.applicationContext); this.setPollableConsumerBinder(binder); @@ -77,15 +78,16 @@ public class RabbitTestBinder extends } @Override - public Binding bindConsumer(String name, String group, MessageChannel moduleInputChannel, + public Binding bindConsumer(String name, String group, + MessageChannel moduleInputChannel, ExtendedConsumerProperties properties) { captureConsumerResources(name, group, properties); return super.bindConsumer(name, group, moduleInputChannel, properties); } @Override - public Binding> bindPollableConsumer(String name, String group, - PollableSource inboundBindTarget, + public Binding> bindPollableConsumer(String name, + String group, PollableSource inboundBindTarget, ExtendedConsumerProperties properties) { captureConsumerResources(name, group, properties); return super.bindPollableConsumer(name, group, inboundBindTarget, properties); @@ -102,11 +104,13 @@ public class RabbitTestBinder extends if (properties.isMultiplex()) { names = StringUtils.commaDelimitedListToStringArray(name); for (String nayme : names) { - this.queues.add(properties.getExtension().getPrefix() + nayme.trim() + "." + group); + this.queues.add(properties.getExtension().getPrefix() + + nayme.trim() + "." + group); } } else { - this.queues.add(properties.getExtension().getPrefix() + name + "." + group); + this.queues.add( + properties.getExtension().getPrefix() + name + "." + group); } } } @@ -123,7 +127,8 @@ public class RabbitTestBinder extends } @Override - public Binding bindProducer(String name, MessageChannel moduleOutputChannel, + public Binding bindProducer(String name, + MessageChannel moduleOutputChannel, ExtendedProducerProperties properties) { this.queues.add(properties.getExtension().getPrefix() + name + ".default"); this.exchanges.add(properties.getExtension().getPrefix() + name); @@ -133,7 +138,8 @@ public class RabbitTestBinder extends this.queues.add(properties.getExtension().getPrefix() + group); } else { - this.queues.add(properties.getExtension().getPrefix() + name + "." + group); + this.queues.add( + properties.getExtension().getPrefix() + name + "." + group); } } } diff --git a/spring-cloud-stream-binder-rabbit/src/test/java/org/springframework/cloud/stream/binder/rabbit/integration/RabbitBinderModuleTests.java b/spring-cloud-stream-binder-rabbit/src/test/java/org/springframework/cloud/stream/binder/rabbit/integration/RabbitBinderModuleTests.java index 5dfc01d50..07a002a8e 100644 --- a/spring-cloud-stream-binder-rabbit/src/test/java/org/springframework/cloud/stream/binder/rabbit/integration/RabbitBinderModuleTests.java +++ b/spring-cloud-stream-binder-rabbit/src/test/java/org/springframework/cloud/stream/binder/rabbit/integration/RabbitBinderModuleTests.java @@ -78,8 +78,8 @@ public class RabbitBinderModuleTests { private ConfigurableApplicationContext context; - public static final ConnectionFactory MOCK_CONNECTION_FACTORY = mock(ConnectionFactory.class, - Mockito.RETURNS_MOCKS); + public static final ConnectionFactory MOCK_CONNECTION_FACTORY = mock( + ConnectionFactory.class, Mockito.RETURNS_MOCKS); @After public void tearDown() { @@ -95,8 +95,8 @@ public class RabbitBinderModuleTests { @Test public void testParentConnectionFactoryInheritedByDefault() { context = new SpringApplicationBuilder(SimpleProcessor.class) - .web(WebApplicationType.NONE) - .run("--server.port=0", "--spring.cloud.stream.rabbit.binder.connection-name-prefix=foo"); + .web(WebApplicationType.NONE).run("--server.port=0", + "--spring.cloud.stream.rabbit.binder.connection-name-prefix=foo"); BinderFactory binderFactory = context.getBean(BinderFactory.class); Binder binder = binderFactory.getBinder(null, MessageChannel.class); assertThat(binder).isInstanceOf(RabbitMessageChannelBinder.class); @@ -107,29 +107,35 @@ public class RabbitBinderModuleTests { ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class); assertThat(binderConnectionFactory).isSameAs(connectionFactory); - CompositeHealthIndicator bindersHealthIndicator = context.getBean("bindersHealthIndicator", - CompositeHealthIndicator.class); - DirectFieldAccessor directFieldAccessor = new DirectFieldAccessor(bindersHealthIndicator); + CompositeHealthIndicator bindersHealthIndicator = context + .getBean("bindersHealthIndicator", CompositeHealthIndicator.class); + DirectFieldAccessor directFieldAccessor = new DirectFieldAccessor( + bindersHealthIndicator); assertThat(bindersHealthIndicator).isNotNull(); @SuppressWarnings("unchecked") Map healthIndicators = (Map) directFieldAccessor .getPropertyValue("registry.healthIndicators"); assertThat(healthIndicators).containsKey(("rabbit")); - assertThat(healthIndicators.get("rabbit").health().getStatus()).isEqualTo((Status.UP)); + assertThat(healthIndicators.get("rabbit").health().getStatus()) + .isEqualTo((Status.UP)); - ConnectionFactory publisherConnectionFactory = binderConnectionFactory.getPublisherConnectionFactory(); - assertThat(TestUtils.getPropertyValue(publisherConnectionFactory, "connection.target")).isNull(); + ConnectionFactory publisherConnectionFactory = binderConnectionFactory + .getPublisherConnectionFactory(); + assertThat(TestUtils.getPropertyValue(publisherConnectionFactory, + "connection.target")).isNull(); DirectChannel checkPf = new DirectChannel(); - Binding binding = ((RabbitMessageChannelBinder) binder).bindProducer("checkPF", checkPf, - new ExtendedProducerProperties<>( - new RabbitProducerProperties())); + Binding binding = ((RabbitMessageChannelBinder) binder) + .bindProducer("checkPF", checkPf, + new ExtendedProducerProperties<>(new RabbitProducerProperties())); checkPf.send(new GenericMessage<>("foo".getBytes())); binding.unbind(); - assertThat(TestUtils.getPropertyValue(publisherConnectionFactory, "connection.target")).isNotNull(); + assertThat(TestUtils.getPropertyValue(publisherConnectionFactory, + "connection.target")).isNotNull(); - CachingConnectionFactory cf = this.context.getBean(CachingConnectionFactory.class); - ConnectionNameStrategy cns = TestUtils.getPropertyValue(cf, "connectionNameStrategy", - ConnectionNameStrategy.class); + CachingConnectionFactory cf = this.context + .getBean(CachingConnectionFactory.class); + ConnectionNameStrategy cns = TestUtils.getPropertyValue(cf, + "connectionNameStrategy", ConnectionNameStrategy.class); assertThat(cns.obtainNewConnectionName(cf)).isEqualTo("foo#2"); new RabbitAdmin(rabbitTestSupport.getResource()).deleteExchange("checkPF"); } @@ -138,8 +144,7 @@ public class RabbitBinderModuleTests { @SuppressWarnings("unchecked") public void testParentConnectionFactoryInheritedByDefaultAndRabbitSettingsPropagated() { context = new SpringApplicationBuilder(SimpleProcessor.class) - .web(WebApplicationType.NONE) - .run("--server.port=0", + .web(WebApplicationType.NONE).run("--server.port=0", "--spring.cloud.stream.bindings.input.group=someGroup", "--spring.cloud.stream.rabbit.bindings.input.consumer.transacted=true", "--spring.cloud.stream.rabbit.bindings.output.producer.transacted=true"); @@ -147,46 +152,52 @@ public class RabbitBinderModuleTests { Binder binder = binderFactory.getBinder(null, MessageChannel.class); assertThat(binder).isInstanceOf(RabbitMessageChannelBinder.class); BindingService bindingService = context.getBean(BindingService.class); - DirectFieldAccessor channelBindingServiceAccessor = new DirectFieldAccessor(bindingService); + DirectFieldAccessor channelBindingServiceAccessor = new DirectFieldAccessor( + bindingService); Map>> consumerBindings = (Map>>) channelBindingServiceAccessor .getPropertyValue("consumerBindings"); Binding inputBinding = consumerBindings.get("input").get(0); - SimpleMessageListenerContainer container = TestUtils.getPropertyValue(inputBinding, - "lifecycle.messageListenerContainer", SimpleMessageListenerContainer.class); + SimpleMessageListenerContainer container = TestUtils.getPropertyValue( + inputBinding, "lifecycle.messageListenerContainer", + SimpleMessageListenerContainer.class); assertThat(TestUtils.getPropertyValue(container, "beanName")) - .isEqualTo("setByCustomizerForQueue:input.someGroup,andGroup:someGroup"); - assertThat(TestUtils.getPropertyValue(container, "transactional", Boolean.class)).isTrue(); + .isEqualTo("setByCustomizerForQueue:input.someGroup,andGroup:someGroup"); + assertThat(TestUtils.getPropertyValue(container, "transactional", Boolean.class)) + .isTrue(); Map> producerBindings = (Map>) TestUtils .getPropertyValue(bindingService, "producerBindings"); Binding outputBinding = producerBindings.get("output"); - assertThat(TestUtils.getPropertyValue(outputBinding, "lifecycle.amqpTemplate.transactional", - Boolean.class)).isTrue(); + assertThat(TestUtils.getPropertyValue(outputBinding, + "lifecycle.amqpTemplate.transactional", Boolean.class)).isTrue(); DirectFieldAccessor binderFieldAccessor = new DirectFieldAccessor(binder); ConnectionFactory binderConnectionFactory = (ConnectionFactory) binderFieldAccessor .getPropertyValue("connectionFactory"); assertThat(binderConnectionFactory).isInstanceOf(CachingConnectionFactory.class); ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class); assertThat(binderConnectionFactory).isSameAs(connectionFactory); - CompositeHealthIndicator bindersHealthIndicator = context.getBean("bindersHealthIndicator", - CompositeHealthIndicator.class); - DirectFieldAccessor directFieldAccessor = new DirectFieldAccessor(bindersHealthIndicator); + CompositeHealthIndicator bindersHealthIndicator = context + .getBean("bindersHealthIndicator", CompositeHealthIndicator.class); + DirectFieldAccessor directFieldAccessor = new DirectFieldAccessor( + bindersHealthIndicator); assertThat(bindersHealthIndicator).isNotNull(); Map healthIndicators = (Map) directFieldAccessor .getPropertyValue("registry.healthIndicators"); assertThat(healthIndicators).containsKey("rabbit"); - assertThat(healthIndicators.get("rabbit").health().getStatus()).isEqualTo(Status.UP); + assertThat(healthIndicators.get("rabbit").health().getStatus()) + .isEqualTo(Status.UP); - CachingConnectionFactory cf = this.context.getBean(CachingConnectionFactory.class); - ConnectionNameStrategy cns = TestUtils.getPropertyValue(cf, "connectionNameStrategy", - ConnectionNameStrategy.class); + CachingConnectionFactory cf = this.context + .getBean(CachingConnectionFactory.class); + ConnectionNameStrategy cns = TestUtils.getPropertyValue(cf, + "connectionNameStrategy", ConnectionNameStrategy.class); assertThat(cns.obtainNewConnectionName(cf)).startsWith("rabbitConnectionFactory"); } @Test public void testParentConnectionFactoryInheritedIfOverridden() { - context = new SpringApplicationBuilder(SimpleProcessor.class, ConnectionFactoryConfiguration.class) - .web(WebApplicationType.NONE) - .run("--server.port=0"); + context = new SpringApplicationBuilder(SimpleProcessor.class, + ConnectionFactoryConfiguration.class).web(WebApplicationType.NONE) + .run("--server.port=0"); BinderFactory binderFactory = context.getBean(BinderFactory.class); Binder binder = binderFactory.getBinder(null, MessageChannel.class); assertThat(binder).isInstanceOf(RabbitMessageChannelBinder.class); @@ -196,16 +207,18 @@ public class RabbitBinderModuleTests { assertThat(binderConnectionFactory).isSameAs(MOCK_CONNECTION_FACTORY); ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class); assertThat(binderConnectionFactory).isSameAs(connectionFactory); - CompositeHealthIndicator bindersHealthIndicator = context.getBean("bindersHealthIndicator", - CompositeHealthIndicator.class); + CompositeHealthIndicator bindersHealthIndicator = context + .getBean("bindersHealthIndicator", CompositeHealthIndicator.class); assertThat(bindersHealthIndicator).isNotNull(); - DirectFieldAccessor directFieldAccessor = new DirectFieldAccessor(bindersHealthIndicator); + DirectFieldAccessor directFieldAccessor = new DirectFieldAccessor( + bindersHealthIndicator); @SuppressWarnings("unchecked") Map healthIndicators = (Map) directFieldAccessor .getPropertyValue("registry.healthIndicators"); assertThat(healthIndicators).containsKey("rabbit"); // mock connection factory behaves as if down - assertThat(healthIndicators.get("rabbit").health().getStatus()).isEqualTo(Status.DOWN); + assertThat(healthIndicators.get("rabbit").health().getStatus()) + .isEqualTo(Status.DOWN); } @Test @@ -234,24 +247,27 @@ public class RabbitBinderModuleTests { .getPropertyValue("connectionFactory"); ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class); assertThat(binderConnectionFactory).isNotSameAs(connectionFactory); - CompositeHealthIndicator bindersHealthIndicator = context.getBean("bindersHealthIndicator", - CompositeHealthIndicator.class); + CompositeHealthIndicator bindersHealthIndicator = context + .getBean("bindersHealthIndicator", CompositeHealthIndicator.class); assertThat(bindersHealthIndicator); - DirectFieldAccessor directFieldAccessor = new DirectFieldAccessor(bindersHealthIndicator); + DirectFieldAccessor directFieldAccessor = new DirectFieldAccessor( + bindersHealthIndicator); @SuppressWarnings("unchecked") Map healthIndicators = (Map) directFieldAccessor .getPropertyValue("registry.healthIndicators"); assertThat(healthIndicators).containsKey("custom"); - assertThat(healthIndicators.get("custom").health().getStatus()).isEqualTo(Status.UP); + assertThat(healthIndicators.get("custom").health().getStatus()) + .isEqualTo(Status.UP); String name = UUID.randomUUID().toString(); Binding binding = binder.bindProducer(name, new DirectChannel(), new ExtendedProducerProperties<>(new RabbitProducerProperties())); - RetryTemplate template = TestUtils.getPropertyValue(binding, "lifecycle.amqpTemplate.retryTemplate", - RetryTemplate.class); + RetryTemplate template = TestUtils.getPropertyValue(binding, + "lifecycle.amqpTemplate.retryTemplate", RetryTemplate.class); assertThat(template).isNotNull(); - SimpleRetryPolicy retryPolicy = TestUtils.getPropertyValue(template, "retryPolicy", SimpleRetryPolicy.class); - ExponentialBackOffPolicy backOff = TestUtils.getPropertyValue(template, "backOffPolicy", - ExponentialBackOffPolicy.class); + SimpleRetryPolicy retryPolicy = TestUtils.getPropertyValue(template, + "retryPolicy", SimpleRetryPolicy.class); + ExponentialBackOffPolicy backOff = TestUtils.getPropertyValue(template, + "backOffPolicy", ExponentialBackOffPolicy.class); assertThat(retryPolicy.getMaxAttempts()).isEqualTo(2); assertThat(backOff.getInitialInterval()).isEqualTo(1000L); assertThat(backOff.getMultiplier()).isEqualTo(1.1); @@ -263,22 +279,24 @@ public class RabbitBinderModuleTests { @Test public void testCloudProfile() { - this.context = new SpringApplicationBuilder(SimpleProcessor.class, MockCloudConfiguration.class) - .web(WebApplicationType.NONE) - .profiles("cloud") - .run(); + this.context = new SpringApplicationBuilder(SimpleProcessor.class, + MockCloudConfiguration.class).web(WebApplicationType.NONE) + .profiles("cloud").run(); BinderFactory binderFactory = this.context.getBean(BinderFactory.class); Binder binder = binderFactory.getBinder(null, MessageChannel.class); assertThat(binder).isInstanceOf(RabbitMessageChannelBinder.class); DirectFieldAccessor binderFieldAccessor = new DirectFieldAccessor(binder); ConnectionFactory binderConnectionFactory = (ConnectionFactory) binderFieldAccessor .getPropertyValue("connectionFactory"); - ConnectionFactory connectionFactory = this.context.getBean(ConnectionFactory.class); + ConnectionFactory connectionFactory = this.context + .getBean(ConnectionFactory.class); assertThat(binderConnectionFactory).isNotSameAs(connectionFactory); - assertThat(TestUtils.getPropertyValue(connectionFactory, "addresses")).isNotNull(); - assertThat(TestUtils.getPropertyValue(binderConnectionFactory, "addresses")).isNull(); + assertThat(TestUtils.getPropertyValue(connectionFactory, "addresses")) + .isNotNull(); + assertThat(TestUtils.getPropertyValue(binderConnectionFactory, "addresses")) + .isNull(); Cloud cloud = this.context.getBean(Cloud.class); @@ -288,24 +306,28 @@ public class RabbitBinderModuleTests { @Test public void testExtendedProperties() { context = new SpringApplicationBuilder(SimpleProcessor.class) - .web(WebApplicationType.NONE) - .run("--server.port=0", "--spring.cloud.stream.rabbit.default.producer.routing-key-expression=fooRoutingKey", + .web(WebApplicationType.NONE).run("--server.port=0", + "--spring.cloud.stream.rabbit.default.producer.routing-key-expression=fooRoutingKey", "--spring.cloud.stream.rabbit.bindings.output.producer.batch-size=512", "--spring.cloud.stream.rabbit.default.consumer.max-concurrency=4", "--spring.cloud.stream.rabbit.bindings.input.consumer.exchange-type=fanout"); BinderFactory binderFactory = context.getBean(BinderFactory.class); - Binder rabbitBinder = binderFactory.getBinder(null, MessageChannel.class); + Binder rabbitBinder = binderFactory.getBinder(null, + MessageChannel.class); - RabbitProducerProperties rabbitProducerProperties = - (RabbitProducerProperties)((ExtendedPropertiesBinder) rabbitBinder).getExtendedProducerProperties("output"); + RabbitProducerProperties rabbitProducerProperties = (RabbitProducerProperties) ((ExtendedPropertiesBinder) rabbitBinder) + .getExtendedProducerProperties("output"); - assertThat(rabbitProducerProperties.getRoutingKeyExpression().getExpressionString()).isEqualTo("fooRoutingKey"); + assertThat( + rabbitProducerProperties.getRoutingKeyExpression().getExpressionString()) + .isEqualTo("fooRoutingKey"); assertThat(rabbitProducerProperties.getBatchSize()).isEqualTo(512); - RabbitConsumerProperties rabbitConsumerProperties = - (RabbitConsumerProperties)((ExtendedPropertiesBinder) rabbitBinder).getExtendedConsumerProperties("input"); + RabbitConsumerProperties rabbitConsumerProperties = (RabbitConsumerProperties) ((ExtendedPropertiesBinder) rabbitBinder) + .getExtendedConsumerProperties("input"); - assertThat(rabbitConsumerProperties.getExchangeType()).isEqualTo(ExchangeTypes.FANOUT); + assertThat(rabbitConsumerProperties.getExchangeType()) + .isEqualTo(ExchangeTypes.FANOUT); assertThat(rabbitConsumerProperties.getMaxConcurrency()).isEqualTo(4); } @@ -315,8 +337,8 @@ public class RabbitBinderModuleTests { @Bean public ListenerContainerCustomizer containerCustomizer() { - return (c, q, g) -> c.setBeanName("setByCustomizerForQueue:" + q + - (g == null ? "" : ",andGroup:" + g)); + return (c, q, g) -> c.setBeanName( + "setByCustomizerForQueue:" + q + (g == null ? "" : ",andGroup:" + g)); } } @@ -336,9 +358,8 @@ public class RabbitBinderModuleTests { public Cloud cloud() { Cloud cloud = mock(Cloud.class); - willReturn(new CachingConnectionFactory("localhost")) - .given(cloud) - .getSingletonServiceConnector(ConnectionFactory.class, null); + willReturn(new CachingConnectionFactory("localhost")).given(cloud) + .getSingletonServiceConnector(ConnectionFactory.class, null); return cloud; }