Search in sources :

Example 6 with PollableChannel

use of org.springframework.messaging.PollableChannel in project spring-integration by spring-projects.

the class MessagingGatewaySupport method receive.

protected Object receive(long timeout) {
    this.initializeIfNecessary();
    MessageChannel replyChannel = getReplyChannel();
    Assert.state(replyChannel != null && (replyChannel instanceof PollableChannel), "receive is not supported, because no pollable reply channel has been configured");
    return this.messagingTemplate.receiveAndConvert(replyChannel, timeout);
}
Also used : MessageChannel(org.springframework.messaging.MessageChannel) PollableChannel(org.springframework.messaging.PollableChannel)

Example 7 with PollableChannel

use of org.springframework.messaging.PollableChannel in project spring-integration by spring-projects.

the class MessagingGatewaySupport method registerReplyMessageCorrelatorIfNecessary.

protected void registerReplyMessageCorrelatorIfNecessary() {
    MessageChannel replyChannel = getReplyChannel();
    if (replyChannel != null && this.replyMessageCorrelator == null) {
        boolean shouldStartCorrelator;
        synchronized (this.replyMessageCorrelatorMonitor) {
            if (this.replyMessageCorrelator != null) {
                return;
            }
            AbstractEndpoint correlator;
            BridgeHandler handler = new BridgeHandler();
            if (getBeanFactory() != null) {
                handler.setBeanFactory(getBeanFactory());
            }
            handler.afterPropertiesSet();
            if (replyChannel instanceof SubscribableChannel) {
                correlator = new EventDrivenConsumer((SubscribableChannel) replyChannel, handler);
            } else if (replyChannel instanceof PollableChannel) {
                PollingConsumer endpoint = new PollingConsumer((PollableChannel) replyChannel, handler);
                endpoint.setBeanFactory(getBeanFactory());
                endpoint.setReceiveTimeout(this.replyTimeout);
                endpoint.afterPropertiesSet();
                correlator = endpoint;
            } else if (replyChannel instanceof ReactiveStreamsSubscribableChannel) {
                ReactiveStreamsConsumer endpoint = new ReactiveStreamsConsumer(replyChannel, (Subscriber<Message<?>>) handler);
                endpoint.afterPropertiesSet();
                correlator = endpoint;
            } else {
                throw new MessagingException("Unsupported 'replyChannel' type [" + replyChannel.getClass() + "]." + "SubscribableChannel or PollableChannel type are supported.");
            }
            this.replyMessageCorrelator = correlator;
            shouldStartCorrelator = true;
        }
        if (shouldStartCorrelator && isRunning()) {
            if (isRunning()) {
                this.replyMessageCorrelator.start();
            }
        }
    }
}
Also used : AbstractEndpoint(org.springframework.integration.endpoint.AbstractEndpoint) EventDrivenConsumer(org.springframework.integration.endpoint.EventDrivenConsumer) PollingConsumer(org.springframework.integration.endpoint.PollingConsumer) ReactiveStreamsConsumer(org.springframework.integration.endpoint.ReactiveStreamsConsumer) MessageChannel(org.springframework.messaging.MessageChannel) ErrorMessage(org.springframework.messaging.support.ErrorMessage) Message(org.springframework.messaging.Message) BridgeHandler(org.springframework.integration.handler.BridgeHandler) MessagingException(org.springframework.messaging.MessagingException) PollableChannel(org.springframework.messaging.PollableChannel) ReactiveStreamsSubscribableChannel(org.springframework.integration.channel.ReactiveStreamsSubscribableChannel) SubscribableChannel(org.springframework.messaging.SubscribableChannel) ReactiveStreamsSubscribableChannel(org.springframework.integration.channel.ReactiveStreamsSubscribableChannel)

Example 8 with PollableChannel

use of org.springframework.messaging.PollableChannel in project spring-integration by spring-projects.

the class AdvisedMessageHandlerTests method successFailureAdvice.

@Test
public void successFailureAdvice() {
    final AtomicBoolean doFail = new AtomicBoolean();
    AbstractReplyProducingMessageHandler handler = new AbstractReplyProducingMessageHandler() {

        @Override
        protected Object handleRequestMessage(Message<?> requestMessage) {
            if (doFail.get()) {
                throw new RuntimeException("qux");
            }
            return "baz";
        }
    };
    String componentName = "testComponentName";
    handler.setComponentName(componentName);
    QueueChannel replies = new QueueChannel();
    handler.setOutputChannel(replies);
    Message<String> message = new GenericMessage<String>("Hello, world!");
    // no advice
    handler.handleMessage(message);
    Message<?> reply = replies.receive(1000);
    assertNotNull(reply);
    assertEquals("baz", reply.getPayload());
    PollableChannel successChannel = new QueueChannel();
    PollableChannel failureChannel = new QueueChannel();
    ExpressionEvaluatingRequestHandlerAdvice advice = new ExpressionEvaluatingRequestHandlerAdvice();
    advice.setBeanFactory(mock(BeanFactory.class));
    advice.setSuccessChannel(successChannel);
    advice.setFailureChannel(failureChannel);
    advice.setOnSuccessExpressionString("'foo'");
    advice.setOnFailureExpressionString("'bar:' + #exception.message");
    List<Advice> adviceChain = new ArrayList<Advice>();
    adviceChain.add(advice);
    final AtomicReference<String> compName = new AtomicReference<String>();
    adviceChain.add(new AbstractRequestHandlerAdvice() {

        @Override
        protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) throws Exception {
            compName.set(((AbstractReplyProducingMessageHandler.RequestHandler) target).getAdvisedHandler().getComponentName());
            return callback.execute();
        }
    });
    handler.setAdviceChain(adviceChain);
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.afterPropertiesSet();
    // advice with success
    handler.handleMessage(message);
    reply = replies.receive(1000);
    assertNotNull(reply);
    assertEquals("baz", reply.getPayload());
    assertEquals(componentName, compName.get());
    Message<?> success = successChannel.receive(1000);
    assertNotNull(success);
    assertEquals("Hello, world!", ((AdviceMessage<?>) success).getInputMessage().getPayload());
    assertEquals("foo", success.getPayload());
    // advice with failure, not trapped
    doFail.set(true);
    try {
        handler.handleMessage(message);
        fail("Expected exception");
    } catch (Exception e) {
        assertEquals("qux", e.getCause().getMessage());
    }
    Message<?> failure = failureChannel.receive(1000);
    assertNotNull(failure);
    assertEquals("Hello, world!", ((MessagingException) failure.getPayload()).getFailedMessage().getPayload());
    assertEquals("bar:qux", ((MessageHandlingExpressionEvaluatingAdviceException) failure.getPayload()).getEvaluationResult());
    // advice with failure, trapped
    advice.setTrapException(true);
    handler.handleMessage(message);
    failure = failureChannel.receive(1000);
    assertNotNull(failure);
    assertEquals("Hello, world!", ((MessagingException) failure.getPayload()).getFailedMessage().getPayload());
    assertEquals("bar:qux", ((MessageHandlingExpressionEvaluatingAdviceException) failure.getPayload()).getEvaluationResult());
    assertNull(replies.receive(1));
    // advice with failure, eval is result
    advice.setReturnFailureExpressionResult(true);
    handler.handleMessage(message);
    failure = failureChannel.receive(1000);
    assertNotNull(failure);
    assertEquals("Hello, world!", ((MessagingException) failure.getPayload()).getFailedMessage().getPayload());
    assertEquals("bar:qux", ((MessageHandlingExpressionEvaluatingAdviceException) failure.getPayload()).getEvaluationResult());
    reply = replies.receive(1000);
    assertNotNull(reply);
    assertEquals("bar:qux", reply.getPayload());
}
Also used : 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) MessagingException(org.springframework.messaging.MessagingException) ArrayList(java.util.ArrayList) AtomicReference(java.util.concurrent.atomic.AtomicReference) Matchers.containsString(org.hamcrest.Matchers.containsString) AdviceMessage(org.springframework.integration.message.AdviceMessage) MessageHandlingException(org.springframework.messaging.MessageHandlingException) MessagingException(org.springframework.messaging.MessagingException) MessageHandlingExpressionEvaluatingAdviceException(org.springframework.integration.handler.advice.ExpressionEvaluatingRequestHandlerAdvice.MessageHandlingExpressionEvaluatingAdviceException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) GenericMessage(org.springframework.messaging.support.GenericMessage) PollableChannel(org.springframework.messaging.PollableChannel) BeanFactory(org.springframework.beans.factory.BeanFactory) AbstractReplyProducingMessageHandler(org.springframework.integration.handler.AbstractReplyProducingMessageHandler) Advice(org.aopalliance.aop.Advice) Test(org.junit.Test)

Example 9 with PollableChannel

use of org.springframework.messaging.PollableChannel 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 10 with PollableChannel

use of org.springframework.messaging.PollableChannel in project spring-integration by spring-projects.

the class AdvisedMessageHandlerTests method propagateOnFailureExpressionFailures.

@Test
public void propagateOnFailureExpressionFailures() {
    final AtomicBoolean doFail = new AtomicBoolean(true);
    AbstractReplyProducingMessageHandler handler = new AbstractReplyProducingMessageHandler() {

        @Override
        protected Object handleRequestMessage(Message<?> requestMessage) {
            if (doFail.get()) {
                throw new RuntimeException("qux");
            }
            return "baz";
        }
    };
    QueueChannel replies = new QueueChannel();
    handler.setOutputChannel(replies);
    Message<String> message = new GenericMessage<String>("Hello, world!");
    PollableChannel successChannel = new QueueChannel();
    PollableChannel failureChannel = new QueueChannel();
    ExpressionEvaluatingRequestHandlerAdvice advice = new ExpressionEvaluatingRequestHandlerAdvice();
    advice.setBeanFactory(mock(BeanFactory.class));
    advice.setSuccessChannel(successChannel);
    advice.setFailureChannel(failureChannel);
    advice.setOnSuccessExpressionString("1/0");
    advice.setOnFailureExpressionString("1/0");
    List<Advice> adviceChain = new ArrayList<Advice>();
    adviceChain.add(advice);
    handler.setAdviceChain(adviceChain);
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.afterPropertiesSet();
    // failing advice with failure
    try {
        handler.handleMessage(message);
        fail("Expected exception");
    } catch (Exception e) {
        assertEquals("qux", e.getCause().getMessage());
    }
    Message<?> reply = replies.receive(1);
    assertNull(reply);
    Message<?> failure = failureChannel.receive(10000);
    assertNotNull(failure);
    assertEquals("Hello, world!", ((MessagingException) failure.getPayload()).getFailedMessage().getPayload());
    assertEquals(MessageHandlingExpressionEvaluatingAdviceException.class, failure.getPayload().getClass());
    assertEquals("qux", ((Exception) failure.getPayload()).getCause().getMessage());
    // propagate failing advice with failure; expect original exception
    advice.setPropagateEvaluationFailures(true);
    try {
        handler.handleMessage(message);
        fail("Expected Exception");
    } catch (MessageHandlingException e) {
        assertEquals("qux", e.getCause().getMessage());
    }
    reply = replies.receive(1);
    assertNull(reply);
    failure = failureChannel.receive(10000);
    assertNotNull(failure);
    assertEquals("Hello, world!", ((MessagingException) failure.getPayload()).getFailedMessage().getPayload());
    assertEquals(MessageHandlingExpressionEvaluatingAdviceException.class, failure.getPayload().getClass());
    assertEquals("qux", ((Exception) failure.getPayload()).getCause().getMessage());
}
Also used : 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) MessagingException(org.springframework.messaging.MessagingException) ArrayList(java.util.ArrayList) Matchers.containsString(org.hamcrest.Matchers.containsString) MessageHandlingException(org.springframework.messaging.MessageHandlingException) MessagingException(org.springframework.messaging.MessagingException) MessageHandlingExpressionEvaluatingAdviceException(org.springframework.integration.handler.advice.ExpressionEvaluatingRequestHandlerAdvice.MessageHandlingExpressionEvaluatingAdviceException) MessageHandlingException(org.springframework.messaging.MessageHandlingException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) GenericMessage(org.springframework.messaging.support.GenericMessage) PollableChannel(org.springframework.messaging.PollableChannel) BeanFactory(org.springframework.beans.factory.BeanFactory) AbstractReplyProducingMessageHandler(org.springframework.integration.handler.AbstractReplyProducingMessageHandler) Advice(org.aopalliance.aop.Advice) Test(org.junit.Test)

Aggregations

PollableChannel (org.springframework.messaging.PollableChannel)210 Test (org.junit.Test)190 MessageChannel (org.springframework.messaging.MessageChannel)89 ClassPathXmlApplicationContext (org.springframework.context.support.ClassPathXmlApplicationContext)82 QueueChannel (org.springframework.integration.channel.QueueChannel)52 GenericMessage (org.springframework.messaging.support.GenericMessage)52 Message (org.springframework.messaging.Message)40 BeanFactory (org.springframework.beans.factory.BeanFactory)25 ConfigurableApplicationContext (org.springframework.context.ConfigurableApplicationContext)20 EventDrivenConsumer (org.springframework.integration.endpoint.EventDrivenConsumer)19 MessagingException (org.springframework.messaging.MessagingException)16 SourcePollingChannelAdapter (org.springframework.integration.endpoint.SourcePollingChannelAdapter)13 MessagingTemplate (org.springframework.integration.core.MessagingTemplate)12 ErrorMessage (org.springframework.messaging.support.ErrorMessage)12 Document (org.w3c.dom.Document)12 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)11 Matchers.containsString (org.hamcrest.Matchers.containsString)11 Date (java.util.Date)10 ArrayList (java.util.ArrayList)9 MessageHistory (org.springframework.integration.history.MessageHistory)9