Example usage for org.springframework.beans.factory BeanInitializationException BeanInitializationException

List of usage examples for org.springframework.beans.factory BeanInitializationException BeanInitializationException

Introduction

In this page you can find the example usage for org.springframework.beans.factory BeanInitializationException BeanInitializationException.

Prototype

public BeanInitializationException(String msg, Throwable cause) 

Source Link

Document

Create a new BeanInitializationException with the specified message and root cause.

Usage

From source file:org.springframework.integration.x.http.NettyHttpInboundChannelAdapter.java

@Override
protected void onInit() {
    try {//  w  w  w  . java2 s. c  o m
        if (this.ssl) {
            this.sslContext = initializeSSLContext();
        }
    } catch (Exception e) {
        throw new BeanInitializationException("failed to initialize", e);
    }
    super.onInit();
}

From source file:org.springframework.integration.x.kafka.KafkaTopicMetadataStore.java

private void readOffsetData(Partition offsetManagementPartition, BrokerAddress leader) {
    Result<Long> earliestOffsetResult = connectionFactory.connect(leader)
            .fetchInitialOffset(OffsetRequest.EarliestTime(), offsetManagementPartition);
    if (earliestOffsetResult.getErrors().size() > 0) {
        throw new BeanInitializationException(
                "Cannot initialize offset manager, unable to read earliest offset",
                ErrorMapping$.MODULE$.exceptionFor(earliestOffsetResult.getError(offsetManagementPartition)));
    }//from  ww w  .j  av a2s .c  om
    Result<Long> latestOffsetResult = connectionFactory.connect(leader)
            .fetchInitialOffset(OffsetRequest.LatestTime(), offsetManagementPartition);
    if (latestOffsetResult.getErrors().size() > 0) {
        throw new BeanInitializationException("Cannot initialize offset manager, unable to read latest offset");
    }

    long initialOffset = earliestOffsetResult.getResult(offsetManagementPartition);
    long finalOffset = latestOffsetResult.getResult(offsetManagementPartition);

    long readingOffset = initialOffset;
    while (readingOffset < finalOffset) {
        FetchRequest fetchRequest = new FetchRequest(offsetManagementPartition, readingOffset, maxSize);
        Result<KafkaMessageBatch> receive = kafkaTemplate.receive(Collections.singleton(fetchRequest));
        if (receive.getErrors().size() > 0) {
            throw new BeanInitializationException("Error while fetching initial offsets:",
                    ErrorMapping$.MODULE$.exceptionFor(receive.getError(offsetManagementPartition)));
        }
        KafkaMessageBatch result = receive.getResult(offsetManagementPartition);
        for (KafkaMessage kafkaMessage : result.getMessages()) {
            addMessageToOffsets(kafkaMessage);
            readingOffset = kafkaMessage.getMetadata().getNextOffset();
        }
        if (log.isDebugEnabled()) {
            log.debug(data.size() + " entries in the final map");
        }
        if (log.isTraceEnabled()) {
            for (Map.Entry<String, String> dataEntry : data.entrySet()) {
                log.trace(String.format("Final value for %s : %s", dataEntry.getKey(), dataEntry.getValue()));
            }
        }
    }
}

From source file:org.springframework.jms.annotation.JmsListenerAnnotationBeanPostProcessor.java

/**
 * Process the given {@link JmsListener} annotation on the given method,
 * registering a corresponding endpoint for the given bean instance.
 * @param jmsListener the annotation to process
 * @param mostSpecificMethod the annotated method
 * @param bean the instance to invoke the method on
 * @see #createMethodJmsListenerEndpoint()
 * @see JmsListenerEndpointRegistrar#registerEndpoint
 *//*from  ww  w  .j a  v a  2 s .co  m*/
protected void processJmsListener(JmsListener jmsListener, Method mostSpecificMethod, Object bean) {
    Method invocableMethod = AopUtils.selectInvocableMethod(mostSpecificMethod, bean.getClass());

    MethodJmsListenerEndpoint endpoint = createMethodJmsListenerEndpoint();
    endpoint.setBean(bean);
    endpoint.setMethod(invocableMethod);
    endpoint.setMostSpecificMethod(mostSpecificMethod);
    endpoint.setMessageHandlerMethodFactory(this.messageHandlerMethodFactory);
    endpoint.setEmbeddedValueResolver(this.embeddedValueResolver);
    endpoint.setBeanFactory(this.beanFactory);
    endpoint.setId(getEndpointId(jmsListener));
    endpoint.setDestination(resolve(jmsListener.destination()));
    if (StringUtils.hasText(jmsListener.selector())) {
        endpoint.setSelector(resolve(jmsListener.selector()));
    }
    if (StringUtils.hasText(jmsListener.subscription())) {
        endpoint.setSubscription(resolve(jmsListener.subscription()));
    }
    if (StringUtils.hasText(jmsListener.concurrency())) {
        endpoint.setConcurrency(resolve(jmsListener.concurrency()));
    }

    JmsListenerContainerFactory<?> factory = null;
    String containerFactoryBeanName = resolve(jmsListener.containerFactory());
    if (StringUtils.hasText(containerFactoryBeanName)) {
        Assert.state(this.beanFactory != null,
                "BeanFactory must be set to obtain container factory by bean name");
        try {
            factory = this.beanFactory.getBean(containerFactoryBeanName, JmsListenerContainerFactory.class);
        } catch (NoSuchBeanDefinitionException ex) {
            throw new BeanInitializationException("Could not register JMS listener endpoint on ["
                    + mostSpecificMethod + "], no " + JmsListenerContainerFactory.class.getSimpleName()
                    + " with id '" + containerFactoryBeanName + "' was found in the application context", ex);
        }
    }

    this.registrar.registerEndpoint(endpoint, factory);
}

From source file:org.springframework.jms.config.JmsListenerEndpointRegistry.java

/**
 * Create and start a new container using the specified factory.
 *///from   w w  w .  ja  v a 2 s  . c o  m
protected MessageListenerContainer createListenerContainer(JmsListenerEndpoint endpoint,
        JmsListenerContainerFactory<?> factory) {

    MessageListenerContainer listenerContainer = factory.createListenerContainer(endpoint);

    if (listenerContainer instanceof InitializingBean) {
        try {
            ((InitializingBean) listenerContainer).afterPropertiesSet();
        } catch (Exception ex) {
            throw new BeanInitializationException("Failed to initialize message listener container", ex);
        }
    }

    int containerPhase = listenerContainer.getPhase();
    if (containerPhase < Integer.MAX_VALUE) { // a custom phase value
        if (this.phase < Integer.MAX_VALUE && this.phase != containerPhase) {
            throw new IllegalStateException("Encountered phase mismatch between container factory definitions: "
                    + this.phase + " vs " + containerPhase);
        }
        this.phase = listenerContainer.getPhase();
    }

    return listenerContainer;
}

From source file:org.springframework.jms.core.support.JmsGatewaySupport.java

@Override
public final void afterPropertiesSet() throws IllegalArgumentException, BeanInitializationException {
    if (this.jmsTemplate == null) {
        throw new IllegalArgumentException("'connectionFactory' or 'jmsTemplate' is required");
    }//w  ww.  j  av  a  2s . c  om
    try {
        initGateway();
    } catch (Exception ex) {
        throw new BeanInitializationException("Initialization of JMS gateway failed: " + ex.getMessage(), ex);
    }
}

From source file:org.springframework.kafka.annotation.KafkaListenerAnnotationBeanPostProcessor.java

protected void processListener(MethodKafkaListenerEndpoint<?, ?> endpoint, KafkaListener kafkaListener,
        Object bean, Object adminTarget, String beanName) {
    endpoint.setBean(bean);//from w ww . j av  a 2  s  . c  o m
    endpoint.setMessageHandlerMethodFactory(this.messageHandlerMethodFactory);
    endpoint.setId(getEndpointId(kafkaListener));
    endpoint.setTopicPartitions(resolveTopicPartitions(kafkaListener));
    endpoint.setTopics(resolveTopics(kafkaListener));
    endpoint.setTopicPattern(resolvePattern(kafkaListener));
    String group = kafkaListener.group();
    if (StringUtils.hasText(group)) {
        Object resolvedGroup = resolveExpression(group);
        if (resolvedGroup instanceof String) {
            endpoint.setGroup((String) resolvedGroup);
        }
    }

    KafkaListenerContainerFactory<?> factory = null;
    String containerFactoryBeanName = resolve(kafkaListener.containerFactory());
    if (StringUtils.hasText(containerFactoryBeanName)) {
        Assert.state(this.beanFactory != null,
                "BeanFactory must be set to obtain container factory by bean name");
        try {
            factory = this.beanFactory.getBean(containerFactoryBeanName, KafkaListenerContainerFactory.class);
        } catch (NoSuchBeanDefinitionException ex) {
            throw new BeanInitializationException(
                    "Could not register Kafka listener endpoint on [" + adminTarget + "] for bean " + beanName
                            + ", no " + KafkaListenerContainerFactory.class.getSimpleName() + " with id '"
                            + containerFactoryBeanName + "' was found in the application context",
                    ex);
        }
    }

    this.registrar.registerEndpoint(endpoint, factory);
}

From source file:org.springframework.kafka.config.KafkaListenerEndpointRegistry.java

/**
 * Create and start a new {@link MessageListenerContainer} using the specified factory.
 * @param endpoint the endpoint to create a {@link MessageListenerContainer}.
 * @param factory the {@link KafkaListenerContainerFactory} to use.
 * @return the {@link MessageListenerContainer}.
 *///w  w  w  . j  a  va2s.  c o m
protected MessageListenerContainer createListenerContainer(KafkaListenerEndpoint endpoint,
        KafkaListenerContainerFactory<?> factory) {

    MessageListenerContainer listenerContainer = factory.createListenerContainer(endpoint);

    if (listenerContainer instanceof InitializingBean) {
        try {
            ((InitializingBean) listenerContainer).afterPropertiesSet();
        } catch (Exception ex) {
            throw new BeanInitializationException("Failed to initialize message listener container", ex);
        }
    }

    int containerPhase = listenerContainer.getPhase();
    if (containerPhase < Integer.MAX_VALUE) { // a custom phase value
        if (this.phase < Integer.MAX_VALUE && this.phase != containerPhase) {
            throw new IllegalStateException("Encountered phase mismatch between container factory definitions: "
                    + this.phase + " vs " + containerPhase);
        }
        this.phase = listenerContainer.getPhase();
    }

    return listenerContainer;
}

From source file:org.springframework.statemachine.processor.StateMachineAnnotationPostProcessor.java

@Override
public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
    Assert.notNull(beanFactory, "BeanFactory must not be null");
    final Class<?> beanClass = getBeanClass(bean);

    if (AnnotationUtils.findAnnotation(beanClass, WithStateMachine.class) == null) {
        // we only post-process beans having WithStateMachine
        // in it or as a meta annotation
        return bean;
    }/*www .j  av a  2  s  .  c o  m*/

    ReflectionUtils.doWithMethods(beanClass, new ReflectionUtils.MethodCallback() {

        @SuppressWarnings({ "unchecked", "rawtypes" })
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            for (Class<? extends Annotation> ppa : postProcessors.keySet()) {
                Annotation metaAnnotation = AnnotationUtils.findAnnotation(method, ppa);
                if (metaAnnotation == null) {
                    continue;
                }
                for (Annotation a : AnnotationUtils.getAnnotations(method)) {
                    MethodAnnotationPostProcessor postProcessor = metaAnnotation != null
                            ? postProcessors.get(metaAnnotation.annotationType())
                            : null;
                    if (postProcessor != null && shouldCreateHandler(a)) {
                        Object result = postProcessor.postProcess(beanClass, bean, beanName, method,
                                metaAnnotation, a);
                        if (result != null && result instanceof StateMachineHandler) {
                            String endpointBeanName = generateBeanName(beanName, method, a.annotationType());

                            if (result instanceof BeanNameAware) {
                                ((BeanNameAware) result).setBeanName(endpointBeanName);
                            }
                            beanFactory.registerSingleton(endpointBeanName, result);
                            if (result instanceof BeanFactoryAware) {
                                ((BeanFactoryAware) result).setBeanFactory(beanFactory);
                            }
                            if (result instanceof InitializingBean) {
                                try {
                                    ((InitializingBean) result).afterPropertiesSet();
                                } catch (Exception e) {
                                    throw new BeanInitializationException(
                                            "failed to initialize annotated component", e);
                                }
                            }
                            if (result instanceof Lifecycle) {
                                lifecycles.add((Lifecycle) result);
                                if (result instanceof SmartLifecycle
                                        && ((SmartLifecycle) result).isAutoStartup()) {
                                    ((SmartLifecycle) result).start();
                                }
                            }
                            if (result instanceof ApplicationListener) {
                                listeners.add((ApplicationListener) result);
                            }
                        }
                    }
                }
            }
        }
    });
    return bean;
}

From source file:org.springframework.statemachine.support.LifecycleObjectSupport.java

@Override
public final void afterPropertiesSet() {
    try {//from  ww w .  j a v a  2  s .c o m
        if (afterPropertiesSetCalled.compareAndSet(false, true)) {
            this.onInit();
        } else {
            log.debug("afterPropertiesSet() is already called, not calling onInit()");
        }
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        throw new BeanInitializationException("failed to initialize", e);
    }
}

From source file:org.springframework.web.portlet.DispatcherPortlet.java

/**
 * Create a List of default strategy objects for the given strategy interface.
 * <p>The default implementation uses the "DispatcherPortlet.properties" file
 * (in the same package as the DispatcherPortlet class) to determine the class names.
 * It instantiates the strategy objects and satisifies ApplicationContextAware
 * if necessary.//from   www  . j  a v a 2 s. c om
 * @param context the current Portlet ApplicationContext
 * @param strategyInterface the strategy interface
 * @return the List of corresponding strategy objects
 */
@SuppressWarnings("unchecked")
protected <T> List<T> getDefaultStrategies(ApplicationContext context, Class<T> strategyInterface) {
    String key = strategyInterface.getName();
    String value = defaultStrategies.getProperty(key);
    if (value != null) {
        String[] classNames = StringUtils.commaDelimitedListToStringArray(value);
        List<T> strategies = new ArrayList<T>(classNames.length);
        for (String className : classNames) {
            try {
                Class<?> clazz = ClassUtils.forName(className, DispatcherPortlet.class.getClassLoader());
                Object strategy = createDefaultStrategy(context, clazz);
                strategies.add((T) strategy);
            } catch (ClassNotFoundException ex) {
                throw new BeanInitializationException(
                        "Could not find DispatcherPortlet's default strategy class [" + className
                                + "] for interface [" + key + "]",
                        ex);
            } catch (LinkageError err) {
                throw new BeanInitializationException(
                        "Error loading DispatcherPortlet's default strategy class [" + className
                                + "] for interface [" + key + "]: problem with class file or dependent class",
                        err);
            }
        }
        return strategies;
    } else {
        return new LinkedList<T>();
    }
}