Search in sources :

Example 1 with AbstractReplyProducingMessageHandler

use of org.springframework.integration.handler.AbstractReplyProducingMessageHandler in project spring-cloud-stream by spring-cloud.

the class StreamListenerAnnotationBeanPostProcessor method afterSingletonsInstantiated.

@Override
public final void afterSingletonsInstantiated() {
    this.injectAndPostProcessDependencies();
    EvaluationContext evaluationContext = IntegrationContextUtils.getEvaluationContext(this.applicationContext.getBeanFactory());
    for (Map.Entry<String, List<StreamListenerHandlerMethodMapping>> mappedBindingEntry : mappedListenerMethods.entrySet()) {
        ArrayList<DispatchingStreamListenerMessageHandler.ConditionalStreamListenerMessageHandlerWrapper> handlers = new ArrayList<>();
        for (StreamListenerHandlerMethodMapping mapping : mappedBindingEntry.getValue()) {
            final InvocableHandlerMethod invocableHandlerMethod = this.messageHandlerMethodFactory.createInvocableHandlerMethod(mapping.getTargetBean(), checkProxy(mapping.getMethod(), mapping.getTargetBean()));
            StreamListenerMessageHandler streamListenerMessageHandler = new StreamListenerMessageHandler(invocableHandlerMethod, resolveExpressionAsBoolean(mapping.getCopyHeaders(), "copyHeaders"), springIntegrationProperties.getMessageHandlerNotPropagatedHeaders());
            streamListenerMessageHandler.setApplicationContext(this.applicationContext);
            streamListenerMessageHandler.setBeanFactory(this.applicationContext.getBeanFactory());
            if (StringUtils.hasText(mapping.getDefaultOutputChannel())) {
                streamListenerMessageHandler.setOutputChannelName(mapping.getDefaultOutputChannel());
            }
            streamListenerMessageHandler.afterPropertiesSet();
            if (StringUtils.hasText(mapping.getCondition())) {
                String conditionAsString = resolveExpressionAsString(mapping.getCondition(), "condition");
                Expression condition = SPEL_EXPRESSION_PARSER.parseExpression(conditionAsString);
                handlers.add(new DispatchingStreamListenerMessageHandler.ConditionalStreamListenerMessageHandlerWrapper(condition, streamListenerMessageHandler));
            } else {
                handlers.add(new DispatchingStreamListenerMessageHandler.ConditionalStreamListenerMessageHandlerWrapper(null, streamListenerMessageHandler));
            }
        }
        if (handlers.size() > 1) {
            for (DispatchingStreamListenerMessageHandler.ConditionalStreamListenerMessageHandlerWrapper handler : handlers) {
                Assert.isTrue(handler.isVoid(), StreamListenerErrorMessages.MULTIPLE_VALUE_RETURNING_METHODS);
            }
        }
        AbstractReplyProducingMessageHandler handler;
        if (handlers.size() > 1 || handlers.get(0).getCondition() != null) {
            handler = new DispatchingStreamListenerMessageHandler(handlers, evaluationContext);
        } else {
            handler = handlers.get(0).getStreamListenerMessageHandler();
        }
        handler.setApplicationContext(this.applicationContext);
        handler.setChannelResolver(this.binderAwareChannelResolver);
        handler.afterPropertiesSet();
        this.applicationContext.getBeanFactory().registerSingleton(handler.getClass().getSimpleName() + handler.hashCode(), handler);
        applicationContext.getBean(mappedBindingEntry.getKey(), SubscribableChannel.class).subscribe(handler);
    }
    this.mappedListenerMethods.clear();
}
Also used : InvocableHandlerMethod(org.springframework.messaging.handler.invocation.InvocableHandlerMethod) ArrayList(java.util.ArrayList) Expression(org.springframework.expression.Expression) AbstractReplyProducingMessageHandler(org.springframework.integration.handler.AbstractReplyProducingMessageHandler) ArrayList(java.util.ArrayList) List(java.util.List) EvaluationContext(org.springframework.expression.EvaluationContext) Map(java.util.Map) MultiValueMap(org.springframework.util.MultiValueMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) SubscribableChannel(org.springframework.messaging.SubscribableChannel)

Example 2 with AbstractReplyProducingMessageHandler

use of org.springframework.integration.handler.AbstractReplyProducingMessageHandler in project spring-integration-samples by spring-projects.

the class TcpServerCustomSerializerTest method testHappyPath.

@Test
public void testHappyPath() {
    // add a listener to this channel, otherwise there is not one defined
    // the reason we use a listener here is so we can assert truths on the
    // message and/or payload
    SubscribableChannel channel = (SubscribableChannel) incomingServerChannel;
    channel.subscribe(new AbstractReplyProducingMessageHandler() {

        @Override
        protected Object handleRequestMessage(Message<?> requestMessage) {
            CustomOrder payload = (CustomOrder) requestMessage.getPayload();
            // we assert during the processing of the messaging that the
            // payload is just the content we wanted to send without the
            // framing bytes (STX/ETX)
            assertEquals(123, payload.getNumber());
            assertEquals("PINGPONG02", payload.getSender());
            assertEquals("You got it to work!", payload.getMessage());
            return requestMessage;
        }
    });
    String sourceMessage = "123PINGPONG02000019You got it to work!";
    // use the java socket API to make the connection to the server
    Socket socket = null;
    Writer out = null;
    BufferedReader in = null;
    try {
        socket = new Socket("localhost", this.serverConnectionFactory.getPort());
        out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        out.write(sourceMessage);
        out.flush();
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        StringBuffer str = new StringBuffer();
        int c;
        while ((c = in.read()) != -1) {
            str.append((char) c);
        }
        String response = str.toString();
        assertEquals(sourceMessage, response);
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
        fail(String.format("Test (port: %s) ended with an exception: %s", this.serverConnectionFactory.getPort(), e.getMessage()));
    } finally {
        try {
            socket.close();
            out.close();
            in.close();
        } catch (Exception e) {
        // swallow exception
        }
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) IOException(java.io.IOException) IOException(java.io.IOException) BufferedWriter(java.io.BufferedWriter) BufferedReader(java.io.BufferedReader) AbstractReplyProducingMessageHandler(org.springframework.integration.handler.AbstractReplyProducingMessageHandler) OutputStreamWriter(java.io.OutputStreamWriter) SubscribableChannel(org.springframework.messaging.SubscribableChannel) Socket(java.net.Socket) OutputStreamWriter(java.io.OutputStreamWriter) BufferedWriter(java.io.BufferedWriter) Writer(java.io.Writer) Test(org.junit.Test)

Example 3 with AbstractReplyProducingMessageHandler

use of org.springframework.integration.handler.AbstractReplyProducingMessageHandler 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 4 with AbstractReplyProducingMessageHandler

use of org.springframework.integration.handler.AbstractReplyProducingMessageHandler in project spring-integration by spring-projects.

the class AdvisedMessageHandlerTests method testInt2943RetryWithExceptionClassifier.

private void testInt2943RetryWithExceptionClassifier(boolean retryForMyException, int expected) {
    final AtomicInteger counter = new AtomicInteger(0);
    @SuppressWarnings("serial")
    class MyException extends RuntimeException {
    }
    AbstractReplyProducingMessageHandler handler = new AbstractReplyProducingMessageHandler() {

        @Override
        protected Object handleRequestMessage(Message<?> requestMessage) {
            counter.incrementAndGet();
            throw new MyException();
        }
    };
    QueueChannel replies = new QueueChannel();
    handler.setOutputChannel(replies);
    RequestHandlerRetryAdvice advice = new RequestHandlerRetryAdvice();
    RetryTemplate retryTemplate = new RetryTemplate();
    Map<Class<? extends Throwable>, Boolean> retryableExceptions = new HashMap<Class<? extends Throwable>, Boolean>();
    retryableExceptions.put(MyException.class, retryForMyException);
    retryableExceptions.put(MessagingException.class, true);
    retryTemplate.setRetryPolicy(new SimpleRetryPolicy(3, retryableExceptions));
    advice.setRetryTemplate(retryTemplate);
    List<Advice> adviceChain = new ArrayList<Advice>();
    adviceChain.add(advice);
    handler.setAdviceChain(adviceChain);
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.afterPropertiesSet();
    Message<String> message = new GenericMessage<String>("Hello, world!");
    try {
        handler.handleMessage(message);
        fail("MessagingException expected.");
    } catch (Exception e) {
        assertThat(e, Matchers.instanceOf(MessagingException.class));
        assertThat(e.getCause(), Matchers.instanceOf(MyException.class));
    }
    assertEquals(expected, counter.get());
}
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) HashMap(java.util.HashMap) SimpleRetryPolicy(org.springframework.retry.policy.SimpleRetryPolicy) 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) GenericMessage(org.springframework.messaging.support.GenericMessage) RetryTemplate(org.springframework.retry.support.RetryTemplate) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BeanFactory(org.springframework.beans.factory.BeanFactory) AbstractReplyProducingMessageHandler(org.springframework.integration.handler.AbstractReplyProducingMessageHandler) Advice(org.aopalliance.aop.Advice) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Example 5 with AbstractReplyProducingMessageHandler

use of org.springframework.integration.handler.AbstractReplyProducingMessageHandler in project spring-integration by spring-projects.

the class AdvisedMessageHandlerTests method errorMessageSendingRecovererTestsNoThrowable.

@Test
public void errorMessageSendingRecovererTestsNoThrowable() {
    AbstractReplyProducingMessageHandler handler = new AbstractReplyProducingMessageHandler() {

        @Override
        protected Object handleRequestMessage(Message<?> requestMessage) {
            throw new RuntimeException("fooException");
        }
    };
    QueueChannel errors = new QueueChannel();
    RequestHandlerRetryAdvice advice = new RequestHandlerRetryAdvice();
    ErrorMessageSendingRecoverer recoverer = new ErrorMessageSendingRecoverer(errors);
    advice.setRecoveryCallback(recoverer);
    RetryTemplate retryTemplate = new RetryTemplate();
    retryTemplate.setRetryPolicy(new SimpleRetryPolicy() {

        static final long serialVersionUID = -1;

        @Override
        public boolean canRetry(RetryContext context) {
            return false;
        }
    });
    advice.setRetryTemplate(retryTemplate);
    advice.setBeanFactory(mock(BeanFactory.class));
    advice.afterPropertiesSet();
    List<Advice> adviceChain = new ArrayList<Advice>();
    adviceChain.add(advice);
    handler.setAdviceChain(adviceChain);
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.afterPropertiesSet();
    Message<String> message = new GenericMessage<String>("Hello, world!");
    handler.handleMessage(message);
    Message<?> error = errors.receive(10000);
    assertNotNull(error);
    assertTrue(error.getPayload() instanceof ErrorMessageSendingRecoverer.RetryExceptionNotAvailableException);
    assertNotNull(((MessagingException) error.getPayload()).getFailedMessage());
    assertSame(message, ((MessagingException) error.getPayload()).getFailedMessage());
}
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) RetryContext(org.springframework.retry.RetryContext) SimpleRetryPolicy(org.springframework.retry.policy.SimpleRetryPolicy) ArrayList(java.util.ArrayList) Matchers.containsString(org.hamcrest.Matchers.containsString) GenericMessage(org.springframework.messaging.support.GenericMessage) RetryTemplate(org.springframework.retry.support.RetryTemplate) BeanFactory(org.springframework.beans.factory.BeanFactory) AbstractReplyProducingMessageHandler(org.springframework.integration.handler.AbstractReplyProducingMessageHandler) Advice(org.aopalliance.aop.Advice) Test(org.junit.Test)

Aggregations

AbstractReplyProducingMessageHandler (org.springframework.integration.handler.AbstractReplyProducingMessageHandler)52 Test (org.junit.Test)46 BeanFactory (org.springframework.beans.factory.BeanFactory)37 QueueChannel (org.springframework.integration.channel.QueueChannel)29 Message (org.springframework.messaging.Message)28 DirectChannel (org.springframework.integration.channel.DirectChannel)23 GenericMessage (org.springframework.messaging.support.GenericMessage)20 Matchers.containsString (org.hamcrest.Matchers.containsString)19 ErrorMessage (org.springframework.messaging.support.ErrorMessage)18 ArrayList (java.util.ArrayList)14 AdviceMessage (org.springframework.integration.message.AdviceMessage)14 Advice (org.aopalliance.aop.Advice)13 HashMap (java.util.HashMap)12 MessageHandlingException (org.springframework.messaging.MessageHandlingException)12 Expression (org.springframework.expression.Expression)10 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)10 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)9 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)9 MessageHandlingExpressionEvaluatingAdviceException (org.springframework.integration.handler.advice.ExpressionEvaluatingRequestHandlerAdvice.MessageHandlingExpressionEvaluatingAdviceException)9 MessagingException (org.springframework.messaging.MessagingException)9