Search in sources :

Example 26 with BeanInitializationException

use of org.springframework.beans.factory.BeanInitializationException 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 27 with BeanInitializationException

use of org.springframework.beans.factory.BeanInitializationException 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)

Example 28 with BeanInitializationException

use of org.springframework.beans.factory.BeanInitializationException in project spring-integration by spring-projects.

the class MethodInvokingHeaderEnricherTests method overwriteId.

@Test
public void overwriteId() {
    HeaderEnricher enricher = new HeaderEnricher(Collections.singletonMap(MessageHeaders.ID, new StaticHeaderValueMessageProcessor<>("foo")));
    try {
        enricher.afterPropertiesSet();
        fail("BeanInitializationException expected");
    } catch (Exception e) {
        assertThat(e, instanceOf(BeanInitializationException.class));
        assertThat(e.getMessage(), containsString("HeaderEnricher cannot override 'id' and 'timestamp' read-only headers."));
    }
}
Also used : StaticHeaderValueMessageProcessor(org.springframework.integration.transformer.support.StaticHeaderValueMessageProcessor) HeaderEnricher(org.springframework.integration.transformer.HeaderEnricher) BeanInitializationException(org.springframework.beans.factory.BeanInitializationException) Test(org.junit.Test)

Example 29 with BeanInitializationException

use of org.springframework.beans.factory.BeanInitializationException in project spring-integration by spring-projects.

the class AbstractInboundFileSynchronizingMessageSource method afterPropertiesSet.

@Override
public void afterPropertiesSet() throws Exception {
    super.afterPropertiesSet();
    Assert.notNull(this.localDirectory, "localDirectory must not be null");
    try {
        if (!this.localDirectory.exists()) {
            if (this.autoCreateLocalDirectory) {
                if (logger.isDebugEnabled()) {
                    logger.debug("The '" + this.localDirectory + "' directory doesn't exist; Will create.");
                }
                this.localDirectory.mkdirs();
            } else {
                throw new FileNotFoundException(this.localDirectory.getName());
            }
        }
        this.fileSource.setDirectory(this.localDirectory);
        if (this.localFileListFilter == null) {
            this.localFileListFilter = new FileSystemPersistentAcceptOnceFileListFilter(new SimpleMetadataStore(), getComponentName());
        }
        FileListFilter<File> filter = buildFilter();
        if (this.scannerExplicitlySet) {
            Assert.state(!this.fileSource.isUseWatchService(), "'useWatchService' and 'scanner' are mutually exclusive.");
            this.fileSource.getScanner().setFilter(filter);
        } else if (!this.fileSource.isUseWatchService()) {
            DirectoryScanner directoryScanner = new DefaultDirectoryScanner();
            directoryScanner.setFilter(filter);
            this.fileSource.setScanner(directoryScanner);
        } else {
            this.fileSource.setFilter(filter);
        }
        if (this.getBeanFactory() != null) {
            this.fileSource.setBeanFactory(this.getBeanFactory());
        }
        this.fileSource.afterPropertiesSet();
        this.synchronizer.afterPropertiesSet();
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new BeanInitializationException("Failure during initialization of MessageSource for: " + this.getClass(), e);
    }
}
Also used : BeanInitializationException(org.springframework.beans.factory.BeanInitializationException) FileSystemPersistentAcceptOnceFileListFilter(org.springframework.integration.file.filters.FileSystemPersistentAcceptOnceFileListFilter) DirectoryScanner(org.springframework.integration.file.DirectoryScanner) DefaultDirectoryScanner(org.springframework.integration.file.DefaultDirectoryScanner) FileNotFoundException(java.io.FileNotFoundException) SimpleMetadataStore(org.springframework.integration.metadata.SimpleMetadataStore) File(java.io.File) DefaultDirectoryScanner(org.springframework.integration.file.DefaultDirectoryScanner) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) BeanInitializationException(org.springframework.beans.factory.BeanInitializationException)

Example 30 with BeanInitializationException

use of org.springframework.beans.factory.BeanInitializationException in project ff4j by ff4j.

the class FF4jPropertiesPlaceHolderConfigurer method postProcessBeanFactory.

/**
 * {@inheritDoc}
 */
public final void postProcessBeanFactory(final ConfigurableListableBeanFactory beanFactory) {
    try {
        // 1) Retrieve properties from ff4j
        BeanDefinitionVisitor visitor = new PropertiesPlaceHolderBeanDefinitionVisitor(ff4j);
        // 2) Inject property & features value
        String[] beanNames = beanFactory.getBeanDefinitionNames();
        for (int i = 0; i < beanNames.length; i++) {
            if (beanNames[i].equals(beanName)) {
                continue;
            }
            BeanDefinition bd = beanFactory.getBeanDefinition(beanNames[i]);
            try {
                visitor.visitBeanDefinition(bd);
            } catch (BeanDefinitionStoreException ex) {
                throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanNames[i], ex.getMessage());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Cannot handle placeholding through ff4j : ", e);
        throw new BeanInitializationException("An error occured during substition", e);
    }
}
Also used : BeanInitializationException(org.springframework.beans.factory.BeanInitializationException) BeanDefinitionVisitor(org.springframework.beans.factory.config.BeanDefinitionVisitor) BeanDefinitionStoreException(org.springframework.beans.factory.BeanDefinitionStoreException) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) BeansException(org.springframework.beans.BeansException) BeanDefinitionStoreException(org.springframework.beans.factory.BeanDefinitionStoreException) BeanInitializationException(org.springframework.beans.factory.BeanInitializationException)

Aggregations

BeanInitializationException (org.springframework.beans.factory.BeanInitializationException)41 IOException (java.io.IOException)9 BeansException (org.springframework.beans.BeansException)7 HashMap (java.util.HashMap)4 Bean (org.springframework.context.annotation.Bean)4 File (java.io.File)3 Method (java.lang.reflect.Method)3 Properties (java.util.Properties)3 Field (java.lang.reflect.Field)2 Connection (java.sql.Connection)2 SQLException (java.sql.SQLException)2 ArrayList (java.util.ArrayList)2 HashSet (java.util.HashSet)2 LinkedHashMap (java.util.LinkedHashMap)2 Map (java.util.Map)2 Matcher (java.util.regex.Matcher)2 MutablePropertyValues (org.springframework.beans.MutablePropertyValues)2 PropertyValue (org.springframework.beans.PropertyValue)2 BeanDefinitionStoreException (org.springframework.beans.factory.BeanDefinitionStoreException)2 BeanFactoryAware (org.springframework.beans.factory.BeanFactoryAware)2