Sonar complexity issues

This commit is contained in:
Gary Russell
2019-04-29 13:16:45 -04:00
committed by Artem Bilan
parent 8de53ccee9
commit 7569d0ad79
10 changed files with 384 additions and 268 deletions

View File

@@ -245,6 +245,16 @@ public class DefaultAmqpHeaderMapper extends AbstractHeaderMapper<MessagePropert
.acceptIfNotNull(getHeaderIfAvailable(headers, AmqpHeaders.USER_ID, String.class),
amqpMessageProperties::setUserId);
mapJsonHeaders(headers, amqpMessageProperties);
JavaUtils.INSTANCE
.acceptIfHasText(getHeaderIfAvailable(headers, AmqpHeaders.SPRING_REPLY_CORRELATION, String.class),
replyCorrelation -> amqpMessageProperties.setHeader("spring_reply_correlation", replyCorrelation))
.acceptIfHasText(getHeaderIfAvailable(headers, AmqpHeaders.SPRING_REPLY_TO_STACK, String.class),
replyToStack -> amqpMessageProperties.setHeader("spring_reply_to", replyToStack));
}
private void mapJsonHeaders(Map<String, Object> headers, MessageProperties amqpMessageProperties) {
Map<String, String> jsonHeaders = new HashMap<String, String>();
for (String jsonHeader : JsonHeaders.HEADERS) {
@@ -265,12 +275,6 @@ public class DefaultAmqpHeaderMapper extends AbstractHeaderMapper<MessagePropert
if (!amqpMessageProperties.getHeaders().containsKey(JsonHeaders.TYPE_ID.replaceFirst(JsonHeaders.PREFIX, ""))) {
amqpMessageProperties.getHeaders().putAll(jsonHeaders);
}
JavaUtils.INSTANCE
.acceptIfHasText(getHeaderIfAvailable(headers, AmqpHeaders.SPRING_REPLY_CORRELATION, String.class),
replyCorrelation -> amqpMessageProperties.setHeader("spring_reply_correlation", replyCorrelation))
.acceptIfHasText(getHeaderIfAvailable(headers, AmqpHeaders.SPRING_REPLY_TO_STACK, String.class),
replyToStack -> amqpMessageProperties.setHeader("spring_reply_to", replyToStack));
}
@Override

View File

@@ -92,52 +92,65 @@ public abstract class AbstractEvaluationContextFactoryBean implements Applicatio
protected void initialize(String beanName) {
if (this.applicationContext != null) {
ConversionService conversionService = IntegrationUtils.getConversionService(getApplicationContext());
if (conversionService != null) {
this.typeConverter = new StandardTypeConverter(conversionService);
}
Map<String, SpelFunctionFactoryBean> functionFactoryBeanMap = BeanFactoryUtils
.beansOfTypeIncludingAncestors(this.applicationContext, SpelFunctionFactoryBean.class);
for (SpelFunctionFactoryBean spelFunctionFactoryBean : functionFactoryBeanMap.values()) {
if (!getFunctions().containsKey(spelFunctionFactoryBean.getFunctionName())) {
getFunctions().put(spelFunctionFactoryBean.getFunctionName(), spelFunctionFactoryBean.getObject());
}
}
try {
SpelPropertyAccessorRegistrar propertyAccessorRegistrar =
this.applicationContext.getBean(SpelPropertyAccessorRegistrar.class);
for (Entry<String, PropertyAccessor> entry : propertyAccessorRegistrar.getPropertyAccessors()
.entrySet()) {
if (!getPropertyAccessors().containsKey(entry.getKey())) {
getPropertyAccessors().put(entry.getKey(), entry.getValue());
}
}
}
catch (@SuppressWarnings("unused") NoSuchBeanDefinitionException e) {
// There is no 'SpelPropertyAccessorRegistrar' bean in the application context.
}
ApplicationContext parent = this.applicationContext.getParent();
if (parent != null && parent.containsBean(beanName)) {
AbstractEvaluationContextFactoryBean parentFactoryBean = parent.getBean("&" + beanName, getClass());
for (Entry<String, PropertyAccessor> entry : parentFactoryBean.getPropertyAccessors().entrySet()) {
if (!getPropertyAccessors().containsKey(entry.getKey())) {
getPropertyAccessors().put(entry.getKey(), entry.getValue());
}
}
for (Entry<String, Method> entry : parentFactoryBean.getFunctions().entrySet()) {
if (!getFunctions().containsKey(entry.getKey())) {
getFunctions().put(entry.getKey(), entry.getValue());
}
}
}
conversionService();
functions();
propertyAccessors();
processParentIfPresent(beanName);
}
this.initialized = true;
}
private void conversionService() {
ConversionService conversionService = IntegrationUtils.getConversionService(getApplicationContext());
if (conversionService != null) {
this.typeConverter = new StandardTypeConverter(conversionService);
}
}
private void functions() {
Map<String, SpelFunctionFactoryBean> functionFactoryBeanMap = BeanFactoryUtils
.beansOfTypeIncludingAncestors(this.applicationContext, SpelFunctionFactoryBean.class);
for (SpelFunctionFactoryBean spelFunctionFactoryBean : functionFactoryBeanMap.values()) {
if (!getFunctions().containsKey(spelFunctionFactoryBean.getFunctionName())) {
getFunctions().put(spelFunctionFactoryBean.getFunctionName(), spelFunctionFactoryBean.getObject());
}
}
}
private void propertyAccessors() {
try {
SpelPropertyAccessorRegistrar propertyAccessorRegistrar =
this.applicationContext.getBean(SpelPropertyAccessorRegistrar.class);
for (Entry<String, PropertyAccessor> entry : propertyAccessorRegistrar.getPropertyAccessors()
.entrySet()) {
if (!getPropertyAccessors().containsKey(entry.getKey())) {
getPropertyAccessors().put(entry.getKey(), entry.getValue());
}
}
}
catch (@SuppressWarnings("unused") NoSuchBeanDefinitionException e) {
// There is no 'SpelPropertyAccessorRegistrar' bean in the application context.
}
}
private void processParentIfPresent(String beanName) {
ApplicationContext parent = this.applicationContext.getParent();
if (parent != null && parent.containsBean(beanName)) {
AbstractEvaluationContextFactoryBean parentFactoryBean = parent.getBean("&" + beanName, getClass());
for (Entry<String, PropertyAccessor> entry : parentFactoryBean.getPropertyAccessors().entrySet()) {
if (!getPropertyAccessors().containsKey(entry.getKey())) {
getPropertyAccessors().put(entry.getKey(), entry.getValue());
}
}
for (Entry<String, Method> entry : parentFactoryBean.getFunctions().entrySet()) {
if (!getFunctions().containsKey(entry.getKey())) {
getFunctions().put(entry.getKey(), entry.getValue());
}
}
}
}
}

View File

@@ -215,27 +215,9 @@ public abstract class AbstractSimpleMessageHandlerFactoryBean<H extends MessageH
if (actualHandler == null) {
actualHandler = this.handler;
}
final Object handlerToConfigure = actualHandler; // must final for lambdas
if (actualHandler instanceof IntegrationObjectSupport) {
JavaUtils.INSTANCE
.acceptIfNotNull(this.componentName,
name -> ((IntegrationObjectSupport) handlerToConfigure).setComponentName(name))
.acceptIfNotNull(this.channelResolver,
resolver -> ((IntegrationObjectSupport) handlerToConfigure).setChannelResolver(resolver));
}
if (!CollectionUtils.isEmpty(this.adviceChain)) {
if (actualHandler instanceof AbstractReplyProducingMessageHandler) {
((AbstractReplyProducingMessageHandler) actualHandler).setAdviceChain(this.adviceChain);
}
else if (this.logger.isDebugEnabled()) {
String name = this.componentName;
if (name == null && actualHandler instanceof NamedComponent) {
name = ((NamedComponent) actualHandler).getBeanName();
}
this.logger.debug("adviceChain can only be set on an AbstractReplyProducingMessageHandler"
+ (name == null ? "" : (", " + name)) + ".");
}
}
final Object handlerToConfigure = actualHandler; // must be final for lambdas
integrationObjectSupport(actualHandler, handlerToConfigure);
adviceChain(actualHandler);
JavaUtils.INSTANCE
.acceptIfCondition(this.async != null && actualHandler instanceof AbstractMessageProducingHandler,
this.async,
@@ -244,6 +226,37 @@ public abstract class AbstractSimpleMessageHandlerFactoryBean<H extends MessageH
this.order, theOrder -> ((Orderable) this.handler).setOrder(theOrder));
this.initialized = true;
}
initializingBean();
return this.handler;
}
private void integrationObjectSupport(Object actualHandler, final Object handlerToConfigure) {
if (actualHandler instanceof IntegrationObjectSupport) {
JavaUtils.INSTANCE
.acceptIfNotNull(this.componentName,
name -> ((IntegrationObjectSupport) handlerToConfigure).setComponentName(name))
.acceptIfNotNull(this.channelResolver,
resolver -> ((IntegrationObjectSupport) handlerToConfigure).setChannelResolver(resolver));
}
}
private void adviceChain(Object actualHandler) {
if (!CollectionUtils.isEmpty(this.adviceChain)) {
if (actualHandler instanceof AbstractReplyProducingMessageHandler) {
((AbstractReplyProducingMessageHandler) actualHandler).setAdviceChain(this.adviceChain);
}
else if (this.logger.isDebugEnabled()) {
String name = this.componentName;
if (name == null && actualHandler instanceof NamedComponent) {
name = ((NamedComponent) actualHandler).getBeanName();
}
this.logger.debug("adviceChain can only be set on an AbstractReplyProducingMessageHandler"
+ (name == null ? "" : (", " + name)) + ".");
}
}
}
private void initializingBean() {
if (this.handler instanceof InitializingBean) {
try {
((InitializingBean) this.handler).afterPropertiesSet();
@@ -252,7 +265,6 @@ public abstract class AbstractSimpleMessageHandlerFactoryBean<H extends MessageH
throw new BeanInitializationException("failed to initialize MessageHandler", e);
}
}
return this.handler;
}
private void configureOutputChannelIfAny() {

View File

@@ -210,6 +210,14 @@ public class ConsumerEndpointFactoryBean
}
}
adviceChain();
if (this.channelResolver == null) {
this.channelResolver = ChannelResolverUtils.getChannelResolver(this.beanFactory);
}
initializeEndpoint();
}
private void adviceChain() {
if (!CollectionUtils.isEmpty(this.adviceChain)) {
/*
* ARPMHs advise the handleRequestMessage method internally and already have the advice chain injected.
@@ -236,10 +244,6 @@ public class ConsumerEndpointFactoryBean
}
}
}
if (this.channelResolver == null) {
this.channelResolver = ChannelResolverUtils.getChannelResolver(this.beanFactory);
}
initializeEndpoint();
}
@Override
@@ -277,55 +281,17 @@ public class ConsumerEndpointFactoryBean
}
Assert.state(channel != null, "one of inputChannelName or inputChannel is required");
if (channel instanceof SubscribableChannel) {
Assert.isNull(this.pollerMetadata, "A poller should not be specified for endpoint '" + this.beanName
+ "', since '" + channel + "' is a SubscribableChannel (not pollable).");
this.endpoint = new EventDrivenConsumer((SubscribableChannel) channel, this.handler);
if (logger.isWarnEnabled()
&& Boolean.FALSE.equals(this.autoStartup)
&& channel instanceof FixedSubscriberChannel) {
logger.warn("'autoStartup=\"false\"' has no effect when using a FixedSubscriberChannel");
}
eventDrivenConsumer(channel);
}
else if (channel instanceof PollableChannel) {
PollingConsumer pollingConsumer = new PollingConsumer((PollableChannel) channel, this.handler);
if (this.pollerMetadata == null) {
this.pollerMetadata = PollerMetadata.getDefaultPollerMetadata(this.beanFactory);
Assert.notNull(this.pollerMetadata, "No poller has been defined for endpoint '" + this.beanName
+ "', and no default poller is available within the context.");
}
pollingConsumer.setTaskExecutor(this.pollerMetadata.getTaskExecutor());
pollingConsumer.setTrigger(this.pollerMetadata.getTrigger());
pollingConsumer.setAdviceChain(this.pollerMetadata.getAdviceChain());
pollingConsumer.setMaxMessagesPerPoll(this.pollerMetadata.getMaxMessagesPerPoll());
pollingConsumer.setErrorHandler(this.pollerMetadata.getErrorHandler());
pollingConsumer.setReceiveTimeout(this.pollerMetadata.getReceiveTimeout());
pollingConsumer.setTransactionSynchronizationFactory(
this.pollerMetadata.getTransactionSynchronizationFactory());
pollingConsumer.setBeanClassLoader(this.beanClassLoader);
pollingConsumer.setBeanFactory(this.beanFactory);
this.endpoint = pollingConsumer;
pollingConsumer(channel);
}
else {
this.endpoint = new ReactiveStreamsConsumer(channel, this.handler);
}
this.endpoint.setBeanName(this.beanName);
this.endpoint.setBeanFactory(this.beanFactory);
if (this.autoStartup != null) {
this.endpoint.setAutoStartup(this.autoStartup);
}
int phaseToSet = this.phase;
if (!this.isPhaseSet) {
if (this.endpoint instanceof PollingConsumer) {
phaseToSet = Integer.MAX_VALUE / 2;
}
else {
phaseToSet = Integer.MIN_VALUE;
}
}
this.endpoint.setPhase(phaseToSet);
smartLifecycle();
this.endpoint.setRole(this.role);
if (this.taskScheduler != null) {
this.endpoint.setTaskScheduler(this.taskScheduler);
@@ -335,6 +301,56 @@ public class ConsumerEndpointFactoryBean
}
}
private void eventDrivenConsumer(MessageChannel channel) {
Assert.isNull(this.pollerMetadata, "A poller should not be specified for endpoint '" + this.beanName
+ "', since '" + channel + "' is a SubscribableChannel (not pollable).");
this.endpoint = new EventDrivenConsumer((SubscribableChannel) channel, this.handler);
if (logger.isWarnEnabled()
&& Boolean.FALSE.equals(this.autoStartup)
&& channel instanceof FixedSubscriberChannel) {
logger.warn("'autoStartup=\"false\"' has no effect when using a FixedSubscriberChannel");
}
}
private void pollingConsumer(MessageChannel channel) {
PollingConsumer pollingConsumer = new PollingConsumer((PollableChannel) channel, this.handler);
if (this.pollerMetadata == null) {
this.pollerMetadata = PollerMetadata.getDefaultPollerMetadata(this.beanFactory);
Assert.notNull(this.pollerMetadata, "No poller has been defined for endpoint '" + this.beanName
+ "', and no default poller is available within the context.");
}
pollingConsumer.setTaskExecutor(this.pollerMetadata.getTaskExecutor());
pollingConsumer.setTrigger(this.pollerMetadata.getTrigger());
pollingConsumer.setAdviceChain(this.pollerMetadata.getAdviceChain());
pollingConsumer.setMaxMessagesPerPoll(this.pollerMetadata.getMaxMessagesPerPoll());
pollingConsumer.setErrorHandler(this.pollerMetadata.getErrorHandler());
pollingConsumer.setReceiveTimeout(this.pollerMetadata.getReceiveTimeout());
pollingConsumer.setTransactionSynchronizationFactory(
this.pollerMetadata.getTransactionSynchronizationFactory());
pollingConsumer.setBeanClassLoader(this.beanClassLoader);
pollingConsumer.setBeanFactory(this.beanFactory);
this.endpoint = pollingConsumer;
}
private void smartLifecycle() {
if (this.autoStartup != null) {
this.endpoint.setAutoStartup(this.autoStartup);
}
int phaseToSet = this.phase;
if (!this.isPhaseSet) {
if (this.endpoint instanceof PollingConsumer) {
phaseToSet = Integer.MAX_VALUE / 2;
}
else {
phaseToSet = Integer.MIN_VALUE;
}
}
this.endpoint.setPhase(phaseToSet);
}
/*
* SmartLifecycle implementation (delegates to the created endpoint)

View File

@@ -343,14 +343,20 @@ class DefaultConfiguringBeanFactoryPostProcessor
*/
private void registerBuiltInBeans() {
int registryId = System.identityHashCode(this.registry);
jsonPath(registryId);
xpath(registryId);
jsonNodeToString(registryId);
registriesProcessed.add(registryId);
}
private void jsonPath(int registryId) throws LinkageError {
String jsonPathBeanName = "jsonPath";
if (!this.beanFactory.containsBean(jsonPathBeanName) && !registriesProcessed.contains(registryId)) {
Class<?> jsonPathClass = null;
try {
jsonPathClass = ClassUtils.forName("com.jayway.jsonpath.JsonPath", this.classLoader);
}
catch (ClassNotFoundException e) {
catch (@SuppressWarnings("unused") ClassNotFoundException e) {
logger.debug("The '#jsonPath' SpEL function cannot be registered: " +
"there is no jayway json-path.jar on the classpath.");
}
@@ -374,7 +380,9 @@ class DefaultConfiguringBeanFactoryPostProcessor
IntegrationConfigUtils.BASE_PACKAGE + ".json.JsonPathUtils", "evaluate");
}
}
}
private void xpath(int registryId) throws LinkageError {
String xpathBeanName = "xpath";
if (!this.beanFactory.containsBean(xpathBeanName) && !registriesProcessed.contains(registryId)) {
Class<?> xpathClass = null;
@@ -382,7 +390,7 @@ class DefaultConfiguringBeanFactoryPostProcessor
xpathClass = ClassUtils.forName(IntegrationConfigUtils.BASE_PACKAGE + ".xml.xpath.XPathUtils",
this.classLoader);
}
catch (ClassNotFoundException e) {
catch (@SuppressWarnings("unused") ClassNotFoundException e) {
logger.debug("SpEL function '#xpath' isn't registered: " +
"there is no spring-integration-xml.jar on the classpath.");
}
@@ -392,7 +400,9 @@ class DefaultConfiguringBeanFactoryPostProcessor
IntegrationConfigUtils.BASE_PACKAGE + ".xml.xpath.XPathUtils", "evaluate");
}
}
}
private void jsonNodeToString(int registryId) {
if (!this.beanFactory.containsBean(
IntegrationContextUtils.TO_STRING_FRIENDLY_JSON_NODE_TO_STRING_CONVERTER_BEAN_NAME) &&
!registriesProcessed.contains(registryId) && JacksonPresent.isJackson2Present()) {
@@ -406,8 +416,6 @@ class DefaultConfiguringBeanFactoryPostProcessor
new RuntimeBeanReference(
IntegrationContextUtils.TO_STRING_FRIENDLY_JSON_NODE_TO_STRING_CONVERTER_BEAN_NAME));
}
registriesProcessed.add(registryId);
}
/**

View File

@@ -103,29 +103,37 @@ public final class IdGeneratorConfigurer implements ApplicationListener<Applicat
ReflectionUtils.setField(idGeneratorField, null, idGeneratorBean);
IdGeneratorConfigurer.theIdGenerator = idGeneratorBean;
}
catch (NoSuchBeanDefinitionException e) {
catch (@SuppressWarnings("unused") NoSuchBeanDefinitionException e) {
// No custom IdGenerator. We will use the default.
int idBeans = context.getBeansOfType(IdGenerator.class).size();
if (idBeans > 1 && this.logger.isWarnEnabled()) {
this.logger.warn("Found too many 'IdGenerator' beans (" + idBeans + ") " +
"Will use the existing UUID strategy.");
}
else if (this.logger.isDebugEnabled()) {
this.logger.debug("Unable to locate MessageHeaders.IdGenerator. Will use the existing UUID strategy.");
}
noSuchBean(context);
return false;
}
catch (IllegalStateException e) {
// thrown from ReflectionUtils
if (this.logger.isWarnEnabled()) {
this.logger.warn("Unexpected exception occurred while accessing idGenerator of MessageHeaders." +
" Will use the existing UUID strategy.", e);
}
illegalState(e);
return false;
}
return true;
}
private void noSuchBean(ApplicationContext context) {
int idBeans = context.getBeansOfType(IdGenerator.class).size();
if (idBeans > 1 && this.logger.isWarnEnabled()) {
this.logger.warn("Found too many 'IdGenerator' beans (" + idBeans + ") " +
"Will use the existing UUID strategy.");
}
else if (this.logger.isDebugEnabled()) {
this.logger.debug("Unable to locate MessageHeaders.IdGenerator. Will use the existing UUID strategy.");
}
}
private void illegalState(IllegalStateException e) {
if (this.logger.isWarnEnabled()) {
this.logger.warn("Unexpected exception occurred while accessing idGenerator of MessageHeaders." +
" Will use the existing UUID strategy.", e);
}
}
private void unsetIdGenerator() {
try {
Field idGeneratorField = ReflectionUtils.findField(MessageHeaders.class, "idGenerator");

View File

@@ -76,49 +76,7 @@ public class IdempotentReceiverAutoProxyCreatorInitializer implements Integratio
}
}
else if (beanDefinition instanceof AnnotatedBeanDefinition) {
if (beanDefinition.getSource() instanceof MethodMetadata) {
MethodMetadata beanMethod = (MethodMetadata) beanDefinition.getSource();
String annotationType = IdempotentReceiver.class.getName();
if (beanMethod.isAnnotated(annotationType)) { // NOSONAR never null
Object value = beanMethod.getAnnotationAttributes(annotationType).get("value"); // NOSONAR
if (value != null) {
Class<?> returnType;
if (beanMethod instanceof StandardMethodMetadata) {
returnType = ((StandardMethodMetadata) beanMethod).getIntrospectedMethod()
.getReturnType();
}
else {
try {
returnType = ClassUtils.forName(beanMethod.getReturnTypeName(),
beanFactory.getBeanClassLoader());
}
catch (ClassNotFoundException e) {
throw new CannotLoadBeanClassException(beanDefinition.getDescription(),
beanName, beanMethod.getReturnTypeName(), e);
}
}
String endpoint = beanName;
if (!MessageHandler.class.isAssignableFrom(returnType)) {
/*
MessageHandler beans, populated from @Bean methods, have a complex id,
including @Configuration bean name, method name and the Messaging annotation name.
The following pattern matches the bean name, regardless of the annotation name.
*/
endpoint = beanDefinition.getFactoryBeanName() + "." + beanName +
".*" + IntegrationConfigUtils.HANDLER_ALIAS_SUFFIX;
}
String[] interceptors = (String[]) value;
for (String interceptor : interceptors) {
Map<String, String> idempotentEndpoint = new ManagedMap<String, String>();
idempotentEndpoint.put(interceptor, endpoint);
idempotentEndpointsMapping.add(idempotentEndpoint);
}
}
}
}
annotated(beanFactory, idempotentEndpointsMapping, beanName, beanDefinition);
}
}
@@ -130,4 +88,52 @@ public class IdempotentReceiverAutoProxyCreatorInitializer implements Integratio
}
}
private void annotated(ConfigurableListableBeanFactory beanFactory,
List<Map<String, String>> idempotentEndpointsMapping, String beanName, BeanDefinition beanDefinition)
throws LinkageError {
if (beanDefinition.getSource() instanceof MethodMetadata) {
MethodMetadata beanMethod = (MethodMetadata) beanDefinition.getSource();
String annotationType = IdempotentReceiver.class.getName();
if (beanMethod.isAnnotated(annotationType)) { // NOSONAR never null
Object value = beanMethod.getAnnotationAttributes(annotationType).get("value"); // NOSONAR
if (value != null) {
Class<?> returnType;
if (beanMethod instanceof StandardMethodMetadata) {
returnType = ((StandardMethodMetadata) beanMethod).getIntrospectedMethod()
.getReturnType();
}
else {
try {
returnType = ClassUtils.forName(beanMethod.getReturnTypeName(),
beanFactory.getBeanClassLoader());
}
catch (ClassNotFoundException e) {
throw new CannotLoadBeanClassException(beanDefinition.getDescription(),
beanName, beanMethod.getReturnTypeName(), e);
}
}
String endpoint = beanName;
if (!MessageHandler.class.isAssignableFrom(returnType)) {
/*
MessageHandler beans, populated from @Bean methods, have a complex id,
including @Configuration bean name, method name and the Messaging annotation name.
The following pattern matches the bean name, regardless of the annotation name.
*/
endpoint = beanDefinition.getFactoryBeanName() + "." + beanName +
".*" + IntegrationConfigUtils.HANDLER_ALIAS_SUFFIX;
}
String[] interceptors = (String[]) value;
for (String interceptor : interceptors) {
Map<String, String> idempotentEndpoint = new ManagedMap<String, String>();
idempotentEndpoint.put(interceptor, endpoint);
idempotentEndpointsMapping.add(idempotentEndpoint);
}
}
}
}
}
}

View File

@@ -111,23 +111,7 @@ public class IntegrationComponentScanRegistrar implements ImportBeanDefinitionRe
};
if ((boolean) componentScan.get("useDefaultFilters")) { // NOSONAR - never null
for (TypeFilter typeFilter : this.componentRegistrars.keySet()) {
scanner.addIncludeFilter(typeFilter);
}
}
for (AnnotationAttributes filter : (AnnotationAttributes[]) componentScan.get("includeFilters")) {
for (TypeFilter typeFilter : typeFiltersFor(filter, registry)) {
scanner.addIncludeFilter(typeFilter);
}
}
for (AnnotationAttributes filter : (AnnotationAttributes[]) componentScan.get("excludeFilters")) {
for (TypeFilter typeFilter : typeFiltersFor(filter, registry)) {
scanner.addExcludeFilter(typeFilter);
}
}
filter(registry, componentScan, scanner); // NOSONAR - never null
scanner.setResourceLoader(this.resourceLoader);
@@ -144,8 +128,30 @@ public class IntegrationComponentScanRegistrar implements ImportBeanDefinitionRe
}
}
private void filter(BeanDefinitionRegistry registry, Map<String, Object> componentScan,
ClassPathScanningCandidateComponentProvider scanner) {
if ((boolean) componentScan.get("useDefaultFilters")) { // NOSONAR - never null
for (TypeFilter typeFilter : this.componentRegistrars.keySet()) {
scanner.addIncludeFilter(typeFilter);
}
}
for (AnnotationAttributes filter : (AnnotationAttributes[]) componentScan.get("includeFilters")) {
for (TypeFilter typeFilter : typeFiltersFor(filter, registry)) {
scanner.addIncludeFilter(typeFilter);
}
}
for (AnnotationAttributes filter : (AnnotationAttributes[]) componentScan.get("excludeFilters")) {
for (TypeFilter typeFilter : typeFiltersFor(filter, registry)) {
scanner.addExcludeFilter(typeFilter);
}
}
}
protected Collection<String> getBasePackages(AnnotationMetadata importingClassMetadata,
BeanDefinitionRegistry registry) {
@SuppressWarnings("unused") BeanDefinitionRegistry registry) {
Map<String, Object> componentScan =
importingClassMetadata.getAnnotationAttributes(IntegrationComponentScan.class.getName());

View File

@@ -73,7 +73,7 @@ public class MessagingGatewayRegistrar implements ImportBeanDefinitionRegistrar
}
}
public BeanDefinitionHolder parse(Map<String, Object> gatewayAttributes) {
public BeanDefinitionHolder parse(Map<String, Object> gatewayAttributes) { // NOSONAR complexity
String defaultPayloadExpression = (String) gatewayAttributes.get("defaultPayloadExpression");
@SuppressWarnings("unchecked")

View File

@@ -133,7 +133,7 @@ public abstract class AbstractMethodAnnotationPostProcessor<T extends Annotation
try {
disposablesBean = beanFactory.getBean(Disposables.class);
}
catch (Exception e) {
catch (@SuppressWarnings("unused") Exception e) {
// NOSONAR - only for test cases
}
this.disposables = disposablesBean;
@@ -155,18 +155,46 @@ public abstract class AbstractMethodAnnotationPostProcessor<T extends Annotation
MessageHandler handler = createHandler(bean, method, annotations);
List<Advice> adviceChain = extractAdviceChain(beanName, annotations);
orderable(method, handler);
producerOrRouter(annotations, handler);
if (!CollectionUtils.isEmpty(adviceChain) && handler instanceof AbstractReplyProducingMessageHandler) {
((AbstractReplyProducingMessageHandler) handler).setAdviceChain(adviceChain);
if (handler != sourceHandler) {
String handlerBeanName = generateHandlerBeanName(beanName, method);
if (handler instanceof ReplyProducingMessageHandlerWrapper
&& StringUtils.hasText(MessagingAnnotationUtils.endpointIdValue(method))) {
handlerBeanName = handlerBeanName + ".wrapper";
}
this.beanFactory.registerSingleton(handlerBeanName, handler);
handler = (MessageHandler) this.beanFactory.initializeBean(handler, handlerBeanName);
if (handler instanceof DisposableBean && this.disposables != null) {
this.disposables.add((DisposableBean) handler);
}
}
handler = annotated(method, handler);
handler = adviceChain(beanName, annotations, handler);
AbstractEndpoint endpoint = createEndpoint(handler, method, annotations);
if (endpoint != null) {
return endpoint;
}
else {
return handler;
}
}
private void orderable(Method method, MessageHandler handler) {
if (handler instanceof Orderable) {
Order orderAnnotation = AnnotationUtils.findAnnotation(method, Order.class);
if (orderAnnotation != null) {
((Orderable) handler).setOrder(orderAnnotation.value());
}
}
}
private void producerOrRouter(List<Annotation> annotations, MessageHandler handler) {
if (handler instanceof AbstractMessageProducingHandler || handler instanceof AbstractMessageRouter) {
String sendTimeout = MessagingAnnotationUtils.resolveAttribute(annotations, "sendTimeout", String.class);
if (sendTimeout != null) {
@@ -182,22 +210,14 @@ public abstract class AbstractMethodAnnotationPostProcessor<T extends Annotation
}
}
}
}
if (handler != sourceHandler) {
String handlerBeanName = generateHandlerBeanName(beanName, method);
if (handler instanceof ReplyProducingMessageHandlerWrapper
&& StringUtils.hasText(MessagingAnnotationUtils.endpointIdValue(method))) {
handlerBeanName = handlerBeanName + ".wrapper";
}
this.beanFactory.registerSingleton(handlerBeanName, handler);
handler = (MessageHandler) this.beanFactory.initializeBean(handler, handlerBeanName);
if (handler instanceof DisposableBean && this.disposables != null) {
this.disposables.add((DisposableBean) handler);
}
}
private MessageHandler annotated(Method method, MessageHandler handlerArg) {
MessageHandler handler = handlerArg;
if (AnnotatedElementUtils.isAnnotated(method, IdempotentReceiver.class.getName())
&& !AnnotatedElementUtils.isAnnotated(method, Bean.class.getName())) {
String[] interceptors =
AnnotationUtils.getAnnotation(method, IdempotentReceiver.class).value(); // NOSONAR never null
for (String interceptor : interceptors) {
@@ -218,6 +238,17 @@ public abstract class AbstractMethodAnnotationPostProcessor<T extends Annotation
}
}
}
return handler;
}
private MessageHandler adviceChain(String beanName, List<Annotation> annotations, MessageHandler handlerArg) {
MessageHandler handler = handlerArg;
List<Advice> adviceChain = extractAdviceChain(beanName, annotations);
if (!CollectionUtils.isEmpty(adviceChain) && handler instanceof AbstractReplyProducingMessageHandler) {
((AbstractReplyProducingMessageHandler) handler).setAdviceChain(adviceChain);
}
if (!CollectionUtils.isEmpty(adviceChain)) {
for (Advice advice : adviceChain) {
@@ -235,14 +266,7 @@ public abstract class AbstractMethodAnnotationPostProcessor<T extends Annotation
}
}
}
AbstractEndpoint endpoint = createEndpoint(handler, method, annotations);
if (endpoint != null) {
return endpoint;
}
else {
return handler;
}
return handler;
}
@Override
@@ -299,7 +323,9 @@ public abstract class AbstractMethodAnnotationPostProcessor<T extends Annotation
return adviceChain;
}
protected AbstractEndpoint createEndpoint(MessageHandler handler, Method method, List<Annotation> annotations) {
protected AbstractEndpoint createEndpoint(MessageHandler handler, @SuppressWarnings("unused") Method method,
List<Annotation> annotations) {
AbstractEndpoint endpoint = null;
String inputChannelName = MessagingAnnotationUtils.resolveAttribute(annotations, getInputChannelAttribute(),
String.class);
@@ -376,53 +402,8 @@ public abstract class AbstractMethodAnnotationPostProcessor<T extends Annotation
pollerMetadata = this.beanFactory.getBean(ref, PollerMetadata.class);
}
else {
pollerMetadata = new PollerMetadata();
if (StringUtils.hasText(maxMessagesPerPollValue)) {
pollerMetadata.setMaxMessagesPerPoll(Long.parseLong(maxMessagesPerPollValue));
}
else if (pollingEndpoint instanceof SourcePollingChannelAdapter) {
// SPCAs default to 1 message per poll
pollerMetadata.setMaxMessagesPerPoll(1);
}
if (StringUtils.hasText(executorRef)) {
pollerMetadata.setTaskExecutor(this.beanFactory.getBean(executorRef, TaskExecutor.class));
}
Trigger trigger = null;
if (StringUtils.hasText(triggerRef)) {
Assert.state(!StringUtils.hasText(cron) && !StringUtils.hasText(fixedDelayValue)
&& !StringUtils.hasText(fixedRateValue),
"The '@Poller' 'trigger' attribute is mutually exclusive with other attributes.");
trigger = this.beanFactory.getBean(triggerRef, Trigger.class);
}
else if (StringUtils.hasText(cron)) {
Assert.state(!StringUtils.hasText(fixedDelayValue) && !StringUtils.hasText(fixedRateValue),
"The '@Poller' 'cron' attribute is mutually exclusive with other attributes.");
trigger = new CronTrigger(cron);
}
else if (StringUtils.hasText(fixedDelayValue)) {
Assert.state(!StringUtils.hasText(fixedRateValue),
"The '@Poller' 'fixedDelay' attribute is mutually exclusive with other attributes.");
trigger = new PeriodicTrigger(Long.parseLong(fixedDelayValue));
}
else if (StringUtils.hasText(fixedRateValue)) {
trigger = new PeriodicTrigger(Long.parseLong(fixedRateValue));
((PeriodicTrigger) trigger).setFixedRate(true);
}
//'Trigger' can be null. 'PollingConsumer' does fallback to the 'new PeriodicTrigger(10)'.
pollerMetadata.setTrigger(trigger);
if (StringUtils.hasText(errorChannel)) {
MessagePublishingErrorHandler errorHandler = new MessagePublishingErrorHandler();
errorHandler.setDefaultErrorChannelName(errorChannel);
errorHandler.setBeanFactory(this.beanFactory);
pollerMetadata.setErrorHandler(errorHandler);
}
if (StringUtils.hasText(receiveTimeout)) {
pollerMetadata.setReceiveTimeout(Long.parseLong(receiveTimeout));
}
pollerMetadata = configurePoller(pollingEndpoint, triggerRef, executorRef, fixedDelayValue,
fixedRateValue, maxMessagesPerPollValue, cron, errorChannel, receiveTimeout);
}
}
else {
@@ -441,6 +422,68 @@ public abstract class AbstractMethodAnnotationPostProcessor<T extends Annotation
pollingEndpoint.setTransactionSynchronizationFactory(pollerMetadata.getTransactionSynchronizationFactory());
}
private PollerMetadata configurePoller(AbstractPollingEndpoint pollingEndpoint, String triggerRef,
String executorRef, String fixedDelayValue, String fixedRateValue, String maxMessagesPerPollValue,
String cron, String errorChannel, String receiveTimeout) {
PollerMetadata pollerMetadata;
pollerMetadata = new PollerMetadata();
if (StringUtils.hasText(maxMessagesPerPollValue)) {
pollerMetadata.setMaxMessagesPerPoll(Long.parseLong(maxMessagesPerPollValue));
}
else if (pollingEndpoint instanceof SourcePollingChannelAdapter) {
// SPCAs default to 1 message per poll
pollerMetadata.setMaxMessagesPerPoll(1);
}
if (StringUtils.hasText(executorRef)) {
pollerMetadata.setTaskExecutor(this.beanFactory.getBean(executorRef, TaskExecutor.class));
}
trigger(triggerRef, fixedDelayValue, fixedRateValue, cron, pollerMetadata);
if (StringUtils.hasText(errorChannel)) {
MessagePublishingErrorHandler errorHandler = new MessagePublishingErrorHandler();
errorHandler.setDefaultErrorChannelName(errorChannel);
errorHandler.setBeanFactory(this.beanFactory);
pollerMetadata.setErrorHandler(errorHandler);
}
if (StringUtils.hasText(receiveTimeout)) {
pollerMetadata.setReceiveTimeout(Long.parseLong(receiveTimeout));
}
return pollerMetadata;
}
private void trigger(String triggerRef, String fixedDelayValue, String fixedRateValue, String cron,
PollerMetadata pollerMetadata) {
Trigger trigger = null;
if (StringUtils.hasText(triggerRef)) {
Assert.state(!StringUtils.hasText(cron) && !StringUtils.hasText(fixedDelayValue)
&& !StringUtils.hasText(fixedRateValue),
"The '@Poller' 'trigger' attribute is mutually exclusive with other attributes.");
trigger = this.beanFactory.getBean(triggerRef, Trigger.class);
}
else if (StringUtils.hasText(cron)) {
Assert.state(!StringUtils.hasText(fixedDelayValue) && !StringUtils.hasText(fixedRateValue),
"The '@Poller' 'cron' attribute is mutually exclusive with other attributes.");
trigger = new CronTrigger(cron);
}
else if (StringUtils.hasText(fixedDelayValue)) {
Assert.state(!StringUtils.hasText(fixedRateValue),
"The '@Poller' 'fixedDelay' attribute is mutually exclusive with other attributes.");
trigger = new PeriodicTrigger(Long.parseLong(fixedDelayValue));
}
else if (StringUtils.hasText(fixedRateValue)) {
trigger = new PeriodicTrigger(Long.parseLong(fixedRateValue));
((PeriodicTrigger) trigger).setFixedRate(true);
}
//'Trigger' can be null. 'PollingConsumer' does fallback to the 'new PeriodicTrigger(10)'.
pollerMetadata.setTrigger(trigger);
}
protected String generateHandlerBeanName(String originalBeanName, Method method) {
String name = MessagingAnnotationUtils.endpointIdValue(method);
if (!StringUtils.hasText(name)) {