Search in sources :

Example 1 with ErrorHandlingTaskExecutor

use of org.springframework.integration.util.ErrorHandlingTaskExecutor in project spring-integration by spring-projects.

the class AdvisedMessageHandlerTests method testInappropriateAdvice.

@Test
public void testInappropriateAdvice() throws Exception {
    final AtomicBoolean called = new AtomicBoolean(false);
    Advice advice = new AbstractRequestHandlerAdvice() {

        @Override
        protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) throws Exception {
            called.set(true);
            return callback.execute();
        }
    };
    PollableChannel inputChannel = new QueueChannel();
    PollingConsumer consumer = new PollingConsumer(inputChannel, message -> {
    });
    consumer.setAdviceChain(Collections.singletonList(advice));
    ExecutorService exec = Executors.newSingleThreadExecutor();
    consumer.setTaskExecutor(new ErrorHandlingTaskExecutor(exec, t -> {
    }));
    consumer.setBeanFactory(mock(BeanFactory.class));
    consumer.afterPropertiesSet();
    consumer.setTaskScheduler(mock(TaskScheduler.class));
    consumer.start();
    Callable<?> pollingTask = TestUtils.getPropertyValue(consumer, "poller.pollingTask", Callable.class);
    assertTrue(AopUtils.isAopProxy(pollingTask));
    Log logger = TestUtils.getPropertyValue(advice, "logger", Log.class);
    logger = spy(logger);
    when(logger.isWarnEnabled()).thenReturn(Boolean.TRUE);
    final AtomicReference<String> logMessage = new AtomicReference<String>();
    doAnswer(invocation -> {
        logMessage.set(invocation.getArgument(0));
        return null;
    }).when(logger).warn(Mockito.anyString());
    DirectFieldAccessor accessor = new DirectFieldAccessor(advice);
    accessor.setPropertyValue("logger", logger);
    pollingTask.call();
    assertFalse(called.get());
    assertNotNull(logMessage.get());
    assertThat(logMessage.get(), Matchers.containsString("can only be used for MessageHandlers; " + "an attempt to advise method 'call' in " + "'org.springframework.integration.endpoint.AbstractPollingEndpoint"));
    consumer.stop();
    exec.shutdownNow();
}
Also used : DirtiesContext(org.springframework.test.annotation.DirtiesContext) DefaultRetryState(org.springframework.retry.support.DefaultRetryState) AopUtils(org.springframework.aop.support.AopUtils) Autowired(org.springframework.beans.factory.annotation.Autowired) ErrorMessage(org.springframework.messaging.support.ErrorMessage) PollingConsumer(org.springframework.integration.endpoint.PollingConsumer) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) Assert.assertThat(org.junit.Assert.assertThat) MethodInvocation(org.aopalliance.intercept.MethodInvocation) SpringJUnit4ClassRunner(org.springframework.test.context.junit4.SpringJUnit4ClassRunner) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MessageHandlingException(org.springframework.messaging.MessageHandlingException) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Map(java.util.Map) Assert.fail(org.junit.Assert.fail) PollableChannel(org.springframework.messaging.PollableChannel) Method(java.lang.reflect.Method) AdviceMessage(org.springframework.integration.message.AdviceMessage) TaskScheduler(org.springframework.scheduling.TaskScheduler) MessageChannel(org.springframework.messaging.MessageChannel) Executors(java.util.concurrent.Executors) List(java.util.List) Assert.assertFalse(org.junit.Assert.assertFalse) Matchers.containsString(org.hamcrest.Matchers.containsString) Mockito.mock(org.mockito.Mockito.mock) QueueChannel(org.springframework.integration.channel.QueueChannel) MessagingException(org.springframework.messaging.MessagingException) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) RunWith(org.junit.runner.RunWith) AbstractReplyProducingMessageHandler(org.springframework.integration.handler.AbstractReplyProducingMessageHandler) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) Mockito.spy(org.mockito.Mockito.spy) TestUtils(org.springframework.integration.test.util.TestUtils) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) Assert.assertSame(org.junit.Assert.assertSame) MessageFilter(org.springframework.integration.filter.MessageFilter) Advice(org.aopalliance.aop.Advice) Message(org.springframework.messaging.Message) ExecutorService(java.util.concurrent.ExecutorService) ErrorHandlingTaskExecutor(org.springframework.integration.util.ErrorHandlingTaskExecutor) MessageHandlingExpressionEvaluatingAdviceException(org.springframework.integration.handler.advice.ExpressionEvaluatingRequestHandlerAdvice.MessageHandlingExpressionEvaluatingAdviceException) SimpleRetryPolicy(org.springframework.retry.policy.SimpleRetryPolicy) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) Matchers(org.hamcrest.Matchers) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) MethodInterceptor(org.aopalliance.intercept.MethodInterceptor) Mockito(org.mockito.Mockito) Assert.assertNull(org.junit.Assert.assertNull) RetryContext(org.springframework.retry.RetryContext) BeanFactory(org.springframework.beans.factory.BeanFactory) ContextConfiguration(org.springframework.test.context.ContextConfiguration) ProxyFactory(org.springframework.aop.framework.ProxyFactory) Log(org.apache.commons.logging.Log) GenericMessage(org.springframework.messaging.support.GenericMessage) RetryTemplate(org.springframework.retry.support.RetryTemplate) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) PollingConsumer(org.springframework.integration.endpoint.PollingConsumer) ErrorMessage(org.springframework.messaging.support.ErrorMessage) AdviceMessage(org.springframework.integration.message.AdviceMessage) Message(org.springframework.messaging.Message) GenericMessage(org.springframework.messaging.support.GenericMessage) QueueChannel(org.springframework.integration.channel.QueueChannel) Log(org.apache.commons.logging.Log) AtomicReference(java.util.concurrent.atomic.AtomicReference) Matchers.containsString(org.hamcrest.Matchers.containsString) TaskScheduler(org.springframework.scheduling.TaskScheduler) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) PollableChannel(org.springframework.messaging.PollableChannel) ExecutorService(java.util.concurrent.ExecutorService) BeanFactory(org.springframework.beans.factory.BeanFactory) Advice(org.aopalliance.aop.Advice) ErrorHandlingTaskExecutor(org.springframework.integration.util.ErrorHandlingTaskExecutor) Test(org.junit.Test)

Example 2 with ErrorHandlingTaskExecutor

use of org.springframework.integration.util.ErrorHandlingTaskExecutor in project spring-integration by spring-projects.

the class RedisQueueInboundGateway method onInit.

@Override
protected void onInit() throws Exception {
    super.onInit();
    if (!this.extractPayload) {
        Assert.notNull(this.serializer, "'serializer' has to be provided where 'extractPayload == false'.");
    }
    if (this.taskExecutor == null) {
        String beanName = this.getComponentName();
        this.taskExecutor = new SimpleAsyncTaskExecutor((beanName == null ? "" : beanName + "-") + this.getComponentType());
    }
    if (!(this.taskExecutor instanceof ErrorHandlingTaskExecutor) && this.getBeanFactory() != null) {
        MessagePublishingErrorHandler errorHandler = new MessagePublishingErrorHandler(new BeanFactoryChannelResolver(getBeanFactory()));
        errorHandler.setDefaultErrorChannel(getErrorChannel());
        this.taskExecutor = new ErrorHandlingTaskExecutor(this.taskExecutor, errorHandler);
    }
}
Also used : MessagePublishingErrorHandler(org.springframework.integration.channel.MessagePublishingErrorHandler) SimpleAsyncTaskExecutor(org.springframework.core.task.SimpleAsyncTaskExecutor) BeanFactoryChannelResolver(org.springframework.integration.support.channel.BeanFactoryChannelResolver) ErrorHandlingTaskExecutor(org.springframework.integration.util.ErrorHandlingTaskExecutor)

Example 3 with ErrorHandlingTaskExecutor

use of org.springframework.integration.util.ErrorHandlingTaskExecutor in project spring-integration by spring-projects.

the class ExecutorChannel method onInit.

@Override
public final void onInit() throws Exception {
    Assert.state(getDispatcher().getHandlerCount() == 0, "You cannot subscribe() until the channel " + "bean is fully initialized by the framework. Do not subscribe in a @Bean definition");
    super.onInit();
    if (!(this.executor instanceof ErrorHandlingTaskExecutor)) {
        ErrorHandler errorHandler = new MessagePublishingErrorHandler(new BeanFactoryChannelResolver(this.getBeanFactory()));
        this.executor = new ErrorHandlingTaskExecutor(this.executor, errorHandler);
    }
    UnicastingDispatcher unicastingDispatcher = new UnicastingDispatcher(this.executor);
    unicastingDispatcher.setFailover(this.failover);
    if (this.maxSubscribers == null) {
        this.maxSubscribers = getIntegrationProperty(IntegrationProperties.CHANNELS_MAX_UNICAST_SUBSCRIBERS, Integer.class);
    }
    unicastingDispatcher.setMaxSubscribers(this.maxSubscribers);
    if (this.loadBalancingStrategy != null) {
        unicastingDispatcher.setLoadBalancingStrategy(this.loadBalancingStrategy);
    }
    unicastingDispatcher.setMessageHandlingTaskDecorator(task -> {
        if (ExecutorChannel.this.executorInterceptorsSize > 0) {
            return new MessageHandlingTask(task);
        } else {
            return task;
        }
    });
    this.dispatcher = unicastingDispatcher;
}
Also used : ErrorHandler(org.springframework.util.ErrorHandler) BeanFactoryChannelResolver(org.springframework.integration.support.channel.BeanFactoryChannelResolver) UnicastingDispatcher(org.springframework.integration.dispatcher.UnicastingDispatcher) ErrorHandlingTaskExecutor(org.springframework.integration.util.ErrorHandlingTaskExecutor)

Example 4 with ErrorHandlingTaskExecutor

use of org.springframework.integration.util.ErrorHandlingTaskExecutor in project spring-integration by spring-projects.

the class PublishSubscribeChannel method onInit.

/**
 * Callback method for initialization.
 * @throws Exception the exception.
 */
@Override
public final void onInit() throws Exception {
    super.onInit();
    if (this.executor != null) {
        Assert.state(getDispatcher().getHandlerCount() == 0, "When providing an Executor, you cannot subscribe() until the channel " + "bean is fully initialized by the framework. Do not subscribe in a @Bean definition");
        if (!(this.executor instanceof ErrorHandlingTaskExecutor)) {
            if (this.errorHandler == null) {
                this.errorHandler = new MessagePublishingErrorHandler(new BeanFactoryChannelResolver(this.getBeanFactory()));
            }
            this.executor = new ErrorHandlingTaskExecutor(this.executor, this.errorHandler);
        }
        this.dispatcher = new BroadcastingDispatcher(this.executor);
        getDispatcher().setIgnoreFailures(this.ignoreFailures);
        getDispatcher().setApplySequence(this.applySequence);
        getDispatcher().setMinSubscribers(this.minSubscribers);
    }
    if (this.maxSubscribers == null) {
        Integer maxSubscribers = getIntegrationProperty(IntegrationProperties.CHANNELS_MAX_BROADCAST_SUBSCRIBERS, Integer.class);
        this.setMaxSubscribers(maxSubscribers);
    }
    getDispatcher().setBeanFactory(this.getBeanFactory());
    getDispatcher().setMessageHandlingTaskDecorator(task -> {
        if (PublishSubscribeChannel.this.executorInterceptorsSize > 0) {
            return new MessageHandlingTask(task);
        } else {
            return task;
        }
    });
}
Also used : BeanFactoryChannelResolver(org.springframework.integration.support.channel.BeanFactoryChannelResolver) ErrorHandlingTaskExecutor(org.springframework.integration.util.ErrorHandlingTaskExecutor) BroadcastingDispatcher(org.springframework.integration.dispatcher.BroadcastingDispatcher)

Example 5 with ErrorHandlingTaskExecutor

use of org.springframework.integration.util.ErrorHandlingTaskExecutor in project spring-integration by spring-projects.

the class AbstractPollingEndpoint method onInit.

@Override
protected void onInit() {
    synchronized (this.initializationMonitor) {
        if (this.initialized) {
            return;
        }
        Assert.notNull(this.trigger, "Trigger is required");
        if (this.taskExecutor != null) {
            if (!(this.taskExecutor instanceof ErrorHandlingTaskExecutor)) {
                if (this.errorHandler == null) {
                    Assert.notNull(this.getBeanFactory(), "BeanFactory is required");
                    this.errorHandler = new MessagePublishingErrorHandler(new BeanFactoryChannelResolver(getBeanFactory()));
                    this.errorHandlerIsDefault = true;
                }
                this.taskExecutor = new ErrorHandlingTaskExecutor(this.taskExecutor, this.errorHandler);
            }
        }
        if (this.transactionSynchronizationFactory == null && this.adviceChain != null) {
            if (this.adviceChain.stream().anyMatch(TransactionInterceptor.class::isInstance)) {
                this.transactionSynchronizationFactory = new PassThroughTransactionSynchronizationFactory();
            }
        }
        this.initialized = true;
    }
    try {
        super.onInit();
    } catch (Exception e) {
        throw new BeanInitializationException("Cannot initialize: " + this, e);
    }
}
Also used : BeanInitializationException(org.springframework.beans.factory.BeanInitializationException) TransactionInterceptor(org.springframework.transaction.interceptor.TransactionInterceptor) MessagePublishingErrorHandler(org.springframework.integration.channel.MessagePublishingErrorHandler) BeanFactoryChannelResolver(org.springframework.integration.support.channel.BeanFactoryChannelResolver) PassThroughTransactionSynchronizationFactory(org.springframework.integration.transaction.PassThroughTransactionSynchronizationFactory) MessagingException(org.springframework.messaging.MessagingException) BeanInitializationException(org.springframework.beans.factory.BeanInitializationException) ErrorHandlingTaskExecutor(org.springframework.integration.util.ErrorHandlingTaskExecutor)

Aggregations

ErrorHandlingTaskExecutor (org.springframework.integration.util.ErrorHandlingTaskExecutor)8 BeanFactoryChannelResolver (org.springframework.integration.support.channel.BeanFactoryChannelResolver)5 MessagePublishingErrorHandler (org.springframework.integration.channel.MessagePublishingErrorHandler)3 ArrayList (java.util.ArrayList)2 ExecutorService (java.util.concurrent.ExecutorService)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 Test (org.junit.Test)2 ErrorHandler (org.springframework.util.ErrorHandler)2 Method (java.lang.reflect.Method)1 Collections (java.util.Collections)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Map (java.util.Map)1 Callable (java.util.concurrent.Callable)1 Executors (java.util.concurrent.Executors)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1 Connection (javax.jms.Connection)1 ConnectionFactory (javax.jms.ConnectionFactory)1 Destination (javax.jms.Destination)1