Search in sources :

Example 1 with DefaultMessageBuilderFactory

use of org.springframework.integration.support.DefaultMessageBuilderFactory in project tutorials by eugenp.

the class SecurityPubSubChannel method buildNewMessage.

public Message<String> buildNewMessage(String content, Message<?> message) {
    DefaultMessageBuilderFactory builderFactory = new DefaultMessageBuilderFactory();
    MessageBuilder<String> messageBuilder = builderFactory.withPayload(content);
    messageBuilder.copyHeaders(message.getHeaders());
    return messageBuilder.build();
}
Also used : DefaultMessageBuilderFactory(org.springframework.integration.support.DefaultMessageBuilderFactory)

Example 2 with DefaultMessageBuilderFactory

use of org.springframework.integration.support.DefaultMessageBuilderFactory in project spring-integration by spring-projects.

the class ContentEnricher method doInit.

/**
 * Initializes the Content Enricher. Will instantiate an internal Gateway if the
 * requestChannel is set.
 */
@Override
protected void doInit() {
    Assert.state(!(this.requestChannelName != null && this.requestChannel != null), "'requestChannelName' and 'requestChannel' are mutually exclusive.");
    Assert.state(!(this.replyChannelName != null && this.replyChannel != null), "'replyChannelName' and 'replyChannel' are mutually exclusive.");
    Assert.state(!(this.errorChannelName != null && this.errorChannel != null), "'errorChannelName' and 'errorChannel' are mutually exclusive.");
    if (this.replyChannel != null || this.replyChannelName != null) {
        Assert.state(this.requestChannel != null || this.requestChannelName != null, "If the replyChannel is set, then the requestChannel must not be null");
    }
    if (this.errorChannel != null || this.errorChannelName != null) {
        Assert.state(this.requestChannel != null || this.requestChannelName != null, "If the errorChannel is set, then the requestChannel must not be null");
    }
    if (this.requestChannel != null || this.requestChannelName != null) {
        this.gateway = new Gateway();
        this.gateway.setRequestChannel(this.requestChannel);
        if (this.requestChannelName != null) {
            this.gateway.setRequestChannelName(this.requestChannelName);
        }
        if (this.requestTimeout != null) {
            this.gateway.setRequestTimeout(this.requestTimeout);
        }
        if (this.replyTimeout != null) {
            this.gateway.setReplyTimeout(this.replyTimeout);
        }
        this.gateway.setReplyChannel(this.replyChannel);
        if (this.replyChannelName != null) {
            this.gateway.setReplyChannelName(this.replyChannelName);
        }
        this.gateway.setErrorChannel(this.errorChannel);
        if (this.errorChannelName != null) {
            this.gateway.setErrorChannelName(this.errorChannelName);
        }
        if (this.getBeanFactory() != null) {
            this.gateway.setBeanFactory(this.getBeanFactory());
        }
        this.gateway.afterPropertiesSet();
    }
    if (this.sourceEvaluationContext == null) {
        this.sourceEvaluationContext = ExpressionUtils.createStandardEvaluationContext(getBeanFactory());
    }
    StandardEvaluationContext targetContext = ExpressionUtils.createStandardEvaluationContext(getBeanFactory());
    // bean resolution is NOT allowed for the target of the enrichment
    targetContext.setBeanResolver(null);
    this.targetEvaluationContext = targetContext;
    if (getBeanFactory() != null) {
        boolean checkReadOnlyHeaders = getMessageBuilderFactory() instanceof DefaultMessageBuilderFactory;
        for (Map.Entry<String, HeaderValueMessageProcessor<?>> entry : this.headerExpressions.entrySet()) {
            if (checkReadOnlyHeaders && (MessageHeaders.ID.equals(entry.getKey()) || MessageHeaders.TIMESTAMP.equals(entry.getKey()))) {
                throw new BeanInitializationException("ContentEnricher cannot override 'id' and 'timestamp' read-only headers.\n" + "Wrong 'headerExpressions' [" + this.headerExpressions + "] configuration for " + getComponentName());
            }
            if (entry.getValue() instanceof BeanFactoryAware) {
                ((BeanFactoryAware) entry.getValue()).setBeanFactory(getBeanFactory());
            }
        }
        for (Map.Entry<String, HeaderValueMessageProcessor<?>> entry : this.nullResultHeaderExpressions.entrySet()) {
            if (checkReadOnlyHeaders && (MessageHeaders.ID.equals(entry.getKey()) || MessageHeaders.TIMESTAMP.equals(entry.getKey()))) {
                throw new BeanInitializationException("ContentEnricher cannot override 'id' and 'timestamp' read-only headers.\n" + "Wrong 'nullResultHeaderExpressions' [" + this.nullResultHeaderExpressions + "] configuration for " + getComponentName());
            }
            if (entry.getValue() instanceof BeanFactoryAware) {
                ((BeanFactoryAware) entry.getValue()).setBeanFactory(getBeanFactory());
            }
        }
    }
}
Also used : BeanInitializationException(org.springframework.beans.factory.BeanInitializationException) BeanFactoryAware(org.springframework.beans.factory.BeanFactoryAware) StandardEvaluationContext(org.springframework.expression.spel.support.StandardEvaluationContext) DefaultMessageBuilderFactory(org.springframework.integration.support.DefaultMessageBuilderFactory) HeaderValueMessageProcessor(org.springframework.integration.transformer.support.HeaderValueMessageProcessor) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with DefaultMessageBuilderFactory

use of org.springframework.integration.support.DefaultMessageBuilderFactory 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)

Example 4 with DefaultMessageBuilderFactory

use of org.springframework.integration.support.DefaultMessageBuilderFactory in project spring-integration by spring-projects.

the class MessageHistory method write.

@SuppressWarnings("unchecked")
public static <T> Message<T> write(Message<T> message, NamedComponent component, MessageBuilderFactory messageBuilderFactory) {
    Assert.notNull(message, "Message must not be null");
    Assert.notNull(component, "Component must not be null");
    Properties metadata = extractMetadata(component);
    if (!metadata.isEmpty()) {
        MessageHistory previousHistory = message.getHeaders().get(HEADER_NAME, MessageHistory.class);
        List<Properties> components = (previousHistory != null) ? new ArrayList<Properties>(previousHistory) : new ArrayList<Properties>();
        components.add(metadata);
        MessageHistory history = new MessageHistory(components);
        if (message instanceof MutableMessage) {
            message.getHeaders().put(HEADER_NAME, history);
        } else if (message instanceof ErrorMessage) {
            IntegrationMessageHeaderAccessor headerAccessor = new IntegrationMessageHeaderAccessor(message);
            headerAccessor.setHeader(HEADER_NAME, history);
            Throwable payload = ((ErrorMessage) message).getPayload();
            ErrorMessage errorMessage = new ErrorMessage(payload, headerAccessor.toMessageHeaders());
            message = (Message<T>) errorMessage;
        } else if (message instanceof AdviceMessage) {
            IntegrationMessageHeaderAccessor headerAccessor = new IntegrationMessageHeaderAccessor(message);
            headerAccessor.setHeader(HEADER_NAME, history);
            message = new AdviceMessage<T>(message.getPayload(), headerAccessor.toMessageHeaders(), ((AdviceMessage<?>) message).getInputMessage());
        } else {
            if (!(message instanceof GenericMessage) && (messageBuilderFactory instanceof DefaultMessageBuilderFactory || messageBuilderFactory instanceof MutableMessageBuilderFactory)) {
                if (logger.isWarnEnabled()) {
                    logger.warn("MessageHistory rebuilds the message and produces the result of the [" + messageBuilderFactory + "], not an instance of the provided type [" + message.getClass() + "]. Consider to supply a custom MessageBuilderFactory " + "to retain custom messages during MessageHistory tracking.");
                }
            }
            message = messageBuilderFactory.fromMessage(message).setHeader(HEADER_NAME, history).build();
        }
    }
    return message;
}
Also used : AdviceMessage(org.springframework.integration.message.AdviceMessage) ErrorMessage(org.springframework.messaging.support.ErrorMessage) MutableMessage(org.springframework.integration.support.MutableMessage) Message(org.springframework.messaging.Message) GenericMessage(org.springframework.messaging.support.GenericMessage) AdviceMessage(org.springframework.integration.message.AdviceMessage) Properties(java.util.Properties) IntegrationMessageHeaderAccessor(org.springframework.integration.IntegrationMessageHeaderAccessor) GenericMessage(org.springframework.messaging.support.GenericMessage) MutableMessage(org.springframework.integration.support.MutableMessage) MutableMessageBuilderFactory(org.springframework.integration.support.MutableMessageBuilderFactory) DefaultMessageBuilderFactory(org.springframework.integration.support.DefaultMessageBuilderFactory) ErrorMessage(org.springframework.messaging.support.ErrorMessage)

Aggregations

DefaultMessageBuilderFactory (org.springframework.integration.support.DefaultMessageBuilderFactory)4 HashMap (java.util.HashMap)2 BeanInitializationException (org.springframework.beans.factory.BeanInitializationException)2 HashSet (java.util.HashSet)1 Map (java.util.Map)1 Properties (java.util.Properties)1 BeanDefinitionStoreException (org.springframework.beans.factory.BeanDefinitionStoreException)1 BeanFactoryAware (org.springframework.beans.factory.BeanFactoryAware)1 MethodParameter (org.springframework.core.MethodParameter)1 Expression (org.springframework.expression.Expression)1 LiteralExpression (org.springframework.expression.common.LiteralExpression)1 StandardEvaluationContext (org.springframework.expression.spel.support.StandardEvaluationContext)1 IntegrationMessageHeaderAccessor (org.springframework.integration.IntegrationMessageHeaderAccessor)1 Gateway (org.springframework.integration.annotation.Gateway)1 GatewayHeader (org.springframework.integration.annotation.GatewayHeader)1 ValueExpression (org.springframework.integration.expression.ValueExpression)1 AdviceMessage (org.springframework.integration.message.AdviceMessage)1 MutableMessage (org.springframework.integration.support.MutableMessage)1 MutableMessageBuilderFactory (org.springframework.integration.support.MutableMessageBuilderFactory)1 HeaderValueMessageProcessor (org.springframework.integration.transformer.support.HeaderValueMessageProcessor)1