Search in sources :

Example 1 with Header

use of org.springframework.messaging.handler.annotation.Header in project spring-integration by spring-projects.

the class MethodInvokingMessageProcessorTests method testOptionalArgs.

@Test
public void testOptionalArgs() throws Exception {
    class Foo {

        private final Map<String, Object> arguments = new LinkedHashMap<String, Object>();

        @SuppressWarnings("unused")
        public void optionalHeaders(Optional<String> foo, @Header(value = "foo", required = false) String foo1, @Header("foo") Optional<String> foo2) {
            this.arguments.put("foo", (foo.isPresent() ? foo.get() : null));
            this.arguments.put("foo1", foo1);
            this.arguments.put("foo2", (foo2.isPresent() ? foo2.get() : null));
        }
    }
    Foo targetObject = new Foo();
    MessagingMethodInvokerHelper helper = new MessagingMethodInvokerHelper(targetObject, (String) null, false);
    helper.process(new GenericMessage<>(Optional.empty()));
    assertNull(targetObject.arguments.get("foo"));
    assertNull(targetObject.arguments.get("foo1"));
    assertNull(targetObject.arguments.get("foo2"));
    helper.process(MessageBuilder.withPayload("foo").setHeader("foo", "FOO").build());
    assertEquals("foo", targetObject.arguments.get("foo"));
    assertEquals("FOO", targetObject.arguments.get("foo1"));
    assertEquals("FOO", targetObject.arguments.get("foo2"));
}
Also used : MessagingMethodInvokerHelper(org.springframework.integration.handler.support.MessagingMethodInvokerHelper) Optional(java.util.Optional) Header(org.springframework.messaging.handler.annotation.Header) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) Test(org.junit.Test)

Example 2 with Header

use of org.springframework.messaging.handler.annotation.Header in project spring-integration by spring-projects.

the class MethodInvokingMessageProcessorTests method testProxyAndHeaderAnnotation.

@Test
public void testProxyAndHeaderAnnotation() {
    final AtomicReference<Object> payloadReference = new AtomicReference<>();
    final AtomicReference<UUID> idReference = new AtomicReference<>();
    class MyHandler {

        public void handle(@Header(MessageHeaders.ID) UUID id, @Payload Object payload) {
            idReference.set(id);
            payloadReference.set(payload);
        }
    }
    MyHandler service = new MyHandler();
    final AtomicBoolean adviceCalled = new AtomicBoolean();
    ProxyFactory proxyFactory = new ProxyFactory(service);
    proxyFactory.addAdvice((MethodInterceptor) i -> {
        adviceCalled.set(true);
        return i.proceed();
    });
    service = (MyHandler) proxyFactory.getProxy(getClass().getClassLoader());
    GenericMessage<String> testMessage = new GenericMessage<>("foo");
    MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, "handle");
    processor.processMessage(testMessage);
    assertEquals(testMessage.getPayload(), payloadReference.get());
    assertEquals(testMessage.getHeaders().getId(), idReference.get());
    assertTrue(adviceCalled.get());
}
Also used : Arrays(java.util.Arrays) Date(java.util.Date) ConfigurableListableBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory) Assert.assertThat(org.junit.Assert.assertThat) MessageHandlingException(org.springframework.messaging.MessageHandlingException) Map(java.util.Map) Assert.fail(org.junit.Assert.fail) Method(java.lang.reflect.Method) Header(org.springframework.messaging.handler.annotation.Header) StopWatch(org.springframework.util.StopWatch) UUID(java.util.UUID) EnableIntegration(org.springframework.integration.config.EnableIntegration) Collectors(java.util.stream.Collectors) TypeSafeMatcher(org.hamcrest.TypeSafeMatcher) AnnotationConfigApplicationContext(org.springframework.context.annotation.AnnotationConfigApplicationContext) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) AdditionalAnswers.returnsFirstArg(org.mockito.AdditionalAnswers.returnsFirstArg) Configuration(org.springframework.context.annotation.Configuration) ServiceActivator(org.springframework.integration.annotation.ServiceActivator) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) MessageHandler(org.springframework.messaging.MessageHandler) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Optional(java.util.Optional) Payload(org.springframework.messaging.handler.annotation.Payload) LogFactory(org.apache.commons.logging.LogFactory) Mockito.mock(org.mockito.Mockito.mock) SpelEvaluationException(org.springframework.expression.spel.SpelEvaluationException) MessagingException(org.springframework.messaging.MessagingException) UseSpelInvoker(org.springframework.integration.annotation.UseSpelInvoker) RequestReplyExchanger(org.springframework.integration.gateway.RequestReplyExchanger) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) TestUtils(org.springframework.integration.test.util.TestUtils) AtomicReference(java.util.concurrent.atomic.AtomicReference) Assert.assertSame(org.junit.Assert.assertSame) LinkedHashMap(java.util.LinkedHashMap) MessageBuilder(org.springframework.integration.support.MessageBuilder) Message(org.springframework.messaging.Message) ExpectedException(org.junit.rules.ExpectedException) Description(org.hamcrest.Description) Properties(java.util.Properties) Assert.assertNotNull(org.junit.Assert.assertNotNull) MessagingMethodInvokerHelper(org.springframework.integration.handler.support.MessagingMethodInvokerHelper) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Assert.assertTrue(org.junit.Assert.assertTrue) Matchers(org.hamcrest.Matchers) Test(org.junit.Test) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) SpelParserConfiguration(org.springframework.expression.spel.SpelParserConfiguration) ApplicationContext(org.springframework.context.ApplicationContext) MessageHeaders(org.springframework.messaging.MessageHeaders) BDDMockito.willAnswer(org.mockito.BDDMockito.willAnswer) MethodInterceptor(org.aopalliance.intercept.MethodInterceptor) Assert.assertNull(org.junit.Assert.assertNull) Rule(org.junit.Rule) GatewayProxyFactoryBean(org.springframework.integration.gateway.GatewayProxyFactoryBean) BeanFactory(org.springframework.beans.factory.BeanFactory) ProxyFactory(org.springframework.aop.framework.ProxyFactory) Expression(org.springframework.expression.Expression) Log(org.apache.commons.logging.Log) SpelExpressionParser(org.springframework.expression.spel.standard.SpelExpressionParser) GenericMessage(org.springframework.messaging.support.GenericMessage) SpelCompilerMode(org.springframework.expression.spel.SpelCompilerMode) Collections(java.util.Collections) StandardEvaluationContext(org.springframework.expression.spel.support.StandardEvaluationContext) Assert.assertEquals(org.junit.Assert.assertEquals) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ProxyFactory(org.springframework.aop.framework.ProxyFactory) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) GenericMessage(org.springframework.messaging.support.GenericMessage) Header(org.springframework.messaging.handler.annotation.Header) Payload(org.springframework.messaging.handler.annotation.Payload) UUID(java.util.UUID) Test(org.junit.Test)

Example 3 with Header

use of org.springframework.messaging.handler.annotation.Header in project spring-integration by spring-projects.

the class MethodInvokingMessageGroupProcessorTests method testHeaderParameters.

@Test
public void testHeaderParameters() throws Exception {
    class SingleAnnotationTestBean {

        @Aggregator
        public String method1(List<String> input, @Header("foo") String foo) {
            return input.get(0) + foo;
        }
    }
    SingleAnnotationTestBean bean = new SingleAnnotationTestBean();
    MethodInvokingMessageGroupProcessor aggregator = new MethodInvokingMessageGroupProcessor(bean);
    SimpleMessageGroup group = new SimpleMessageGroup("FOO");
    group.add(MessageBuilder.withPayload("foo").setHeader("foo", "bar").build());
    group.add(MessageBuilder.withPayload("bar").setHeader("foo", "bar").build());
    assertEquals("foobar", aggregator.aggregatePayloads(group, aggregator.aggregateHeaders(group)));
}
Also used : Header(org.springframework.messaging.handler.annotation.Header) ArrayList(java.util.ArrayList) List(java.util.List) SimpleMessageGroup(org.springframework.integration.store.SimpleMessageGroup) Test(org.junit.Test)

Example 4 with Header

use of org.springframework.messaging.handler.annotation.Header in project spring-integration by spring-projects.

the class GatewayProxyFactoryBean method createGatewayForMethod.

private MethodInvocationGateway createGatewayForMethod(Method method) {
    Gateway gatewayAnnotation = method.getAnnotation(Gateway.class);
    String requestChannelName = null;
    String replyChannelName = null;
    Expression requestTimeout = this.defaultRequestTimeout;
    Expression replyTimeout = this.defaultReplyTimeout;
    String payloadExpression = this.globalMethodMetadata != null ? this.globalMethodMetadata.getPayloadExpression() : null;
    Map<String, Expression> headerExpressions = new HashMap<String, Expression>();
    if (gatewayAnnotation != null) {
        requestChannelName = gatewayAnnotation.requestChannel();
        replyChannelName = gatewayAnnotation.replyChannel();
        /*
			 * INT-2636 Unspecified annotation attributes should not
			 * override the default values supplied by explicit configuration.
			 * There is a small risk that someone has used Long.MIN_VALUE explicitly
			 * to indicate an indefinite timeout on a gateway method and that will
			 * no longer work as expected; they will need to use, say, -1 instead.
			 */
        if (requestTimeout == null || gatewayAnnotation.requestTimeout() != Long.MIN_VALUE) {
            requestTimeout = new ValueExpression<>(gatewayAnnotation.requestTimeout());
        }
        if (StringUtils.hasText(gatewayAnnotation.requestTimeoutExpression())) {
            requestTimeout = ExpressionUtils.longExpression(gatewayAnnotation.requestTimeoutExpression());
        }
        if (replyTimeout == null || gatewayAnnotation.replyTimeout() != Long.MIN_VALUE) {
            replyTimeout = new ValueExpression<>(gatewayAnnotation.replyTimeout());
        }
        if (StringUtils.hasText(gatewayAnnotation.replyTimeoutExpression())) {
            replyTimeout = ExpressionUtils.longExpression(gatewayAnnotation.replyTimeoutExpression());
        }
        if (payloadExpression == null || StringUtils.hasText(gatewayAnnotation.payloadExpression())) {
            payloadExpression = gatewayAnnotation.payloadExpression();
        }
        if (!ObjectUtils.isEmpty(gatewayAnnotation.headers())) {
            for (GatewayHeader gatewayHeader : gatewayAnnotation.headers()) {
                String value = gatewayHeader.value();
                String expression = gatewayHeader.expression();
                String name = gatewayHeader.name();
                boolean hasValue = StringUtils.hasText(value);
                if (hasValue == StringUtils.hasText(expression)) {
                    throw new BeanDefinitionStoreException("exactly one of 'value' or 'expression' " + "is required on a gateway's header.");
                }
                headerExpressions.put(name, hasValue ? new LiteralExpression(value) : EXPRESSION_PARSER.parseExpression(expression));
            }
        }
    } else if (this.methodMetadataMap != null && this.methodMetadataMap.size() > 0) {
        GatewayMethodMetadata methodMetadata = this.methodMetadataMap.get(method.getName());
        if (methodMetadata != null) {
            if (StringUtils.hasText(methodMetadata.getPayloadExpression())) {
                payloadExpression = methodMetadata.getPayloadExpression();
            }
            if (!CollectionUtils.isEmpty(methodMetadata.getHeaderExpressions())) {
                headerExpressions.putAll(methodMetadata.getHeaderExpressions());
            }
            requestChannelName = methodMetadata.getRequestChannelName();
            replyChannelName = methodMetadata.getReplyChannelName();
            String reqTimeout = methodMetadata.getRequestTimeout();
            if (StringUtils.hasText(reqTimeout)) {
                requestTimeout = ExpressionUtils.longExpression(reqTimeout);
            }
            String repTimeout = methodMetadata.getReplyTimeout();
            if (StringUtils.hasText(repTimeout)) {
                replyTimeout = ExpressionUtils.longExpression(repTimeout);
            }
        }
    }
    Map<String, Object> headers = null;
    // We don't want to eagerly resolve the error channel here
    Object errorChannel = this.errorChannel == null ? this.errorChannelName : this.errorChannel;
    if (errorChannel != null && method.getReturnType().equals(void.class)) {
        headers = new HashMap<>();
        headers.put(MessageHeaders.ERROR_CHANNEL, errorChannel);
    }
    if (getMessageBuilderFactory() instanceof DefaultMessageBuilderFactory) {
        Set<String> headerNames = new HashSet<>(headerExpressions.keySet());
        if (this.globalMethodMetadata != null) {
            headerNames.addAll(this.globalMethodMetadata.getHeaderExpressions().keySet());
        }
        List<MethodParameter> methodParameters = GatewayMethodInboundMessageMapper.getMethodParameterList(method);
        for (MethodParameter methodParameter : methodParameters) {
            Header header = methodParameter.getParameterAnnotation(Header.class);
            if (header != null) {
                String headerName = GatewayMethodInboundMessageMapper.determineHeaderName(header, methodParameter);
                headerNames.add(headerName);
            }
        }
        for (String header : headerNames) {
            if ((MessageHeaders.ID.equals(header) || MessageHeaders.TIMESTAMP.equals(header))) {
                throw new BeanInitializationException("Messaging Gateway cannot override 'id' and 'timestamp' read-only headers.\n" + "Wrong headers configuration for " + getComponentName());
            }
        }
    }
    GatewayMethodInboundMessageMapper messageMapper = new GatewayMethodInboundMessageMapper(method, headerExpressions, this.globalMethodMetadata != null ? this.globalMethodMetadata.getHeaderExpressions() : null, headers, this.argsMapper, this.getMessageBuilderFactory());
    if (StringUtils.hasText(payloadExpression)) {
        messageMapper.setPayloadExpression(payloadExpression);
    }
    messageMapper.setBeanFactory(getBeanFactory());
    MethodInvocationGateway gateway = new MethodInvocationGateway(messageMapper);
    if (this.errorChannel != null) {
        gateway.setErrorChannel(this.errorChannel);
    } else if (StringUtils.hasText(this.errorChannelName)) {
        gateway.setErrorChannelName(this.errorChannelName);
    }
    if (this.getTaskScheduler() != null) {
        gateway.setTaskScheduler(this.getTaskScheduler());
    }
    gateway.setBeanName(this.getComponentName());
    if (StringUtils.hasText(requestChannelName)) {
        gateway.setRequestChannelName(requestChannelName);
    } else if (StringUtils.hasText(this.defaultRequestChannelName)) {
        gateway.setRequestChannelName(this.defaultRequestChannelName);
    } else {
        gateway.setRequestChannel(this.defaultRequestChannel);
    }
    if (StringUtils.hasText(replyChannelName)) {
        gateway.setReplyChannelName(replyChannelName);
    } else if (StringUtils.hasText(this.defaultReplyChannelName)) {
        gateway.setReplyChannelName(this.defaultReplyChannelName);
    } else {
        gateway.setReplyChannel(this.defaultReplyChannel);
    }
    if (requestTimeout == null) {
        gateway.setRequestTimeout(-1);
    } else if (requestTimeout instanceof ValueExpression) {
        gateway.setRequestTimeout(requestTimeout.getValue(Long.class));
    } else {
        messageMapper.setSendTimeoutExpression(requestTimeout);
    }
    if (replyTimeout == null) {
        gateway.setReplyTimeout(-1);
    } else if (replyTimeout instanceof ValueExpression) {
        gateway.setReplyTimeout(replyTimeout.getValue(Long.class));
    } else {
        messageMapper.setReplyTimeoutExpression(replyTimeout);
    }
    if (this.getBeanFactory() != null) {
        gateway.setBeanFactory(this.getBeanFactory());
    }
    if (replyTimeout != null) {
        gateway.setReceiveTimeoutExpression(replyTimeout);
    }
    gateway.setShouldTrack(this.shouldTrack);
    gateway.afterPropertiesSet();
    return gateway;
}
Also used : BeanInitializationException(org.springframework.beans.factory.BeanInitializationException) HashMap(java.util.HashMap) BeanDefinitionStoreException(org.springframework.beans.factory.BeanDefinitionStoreException) LiteralExpression(org.springframework.expression.common.LiteralExpression) Header(org.springframework.messaging.handler.annotation.Header) GatewayHeader(org.springframework.integration.annotation.GatewayHeader) LiteralExpression(org.springframework.expression.common.LiteralExpression) ValueExpression(org.springframework.integration.expression.ValueExpression) Expression(org.springframework.expression.Expression) Gateway(org.springframework.integration.annotation.Gateway) ValueExpression(org.springframework.integration.expression.ValueExpression) DefaultMessageBuilderFactory(org.springframework.integration.support.DefaultMessageBuilderFactory) MethodParameter(org.springframework.core.MethodParameter) GatewayHeader(org.springframework.integration.annotation.GatewayHeader) HashSet(java.util.HashSet)

Aggregations

Header (org.springframework.messaging.handler.annotation.Header)4 Test (org.junit.Test)3 LinkedHashMap (java.util.LinkedHashMap)2 List (java.util.List)2 Map (java.util.Map)2 Optional (java.util.Optional)2 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)2 MessagingMethodInvokerHelper (org.springframework.integration.handler.support.MessagingMethodInvokerHelper)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 Method (java.lang.reflect.Method)1 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 Collections (java.util.Collections)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Properties (java.util.Properties)1 UUID (java.util.UUID)1 CountDownLatch (java.util.concurrent.CountDownLatch)1