Example usage for org.springframework.beans FatalBeanException FatalBeanException

List of usage examples for org.springframework.beans FatalBeanException FatalBeanException

Introduction

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

Prototype

public FatalBeanException(String msg, @Nullable Throwable cause) 

Source Link

Document

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

Usage

From source file:org.springbyexample.util.log.LoggerBeanPostProcessor.java

/**
 * Gets logger based on the logger name and type of 
 * logger (class name, ex: 'org.slf4j.Logger').
 *//*from w w w . j av a  2s  . com*/
protected Object getLogger(String loggerName, String loggerType) {
    Object result = null;

    String staticMethod = hLoggerFactories.get(loggerType);

    if (staticMethod != null) {
        try {
            MethodInvokingFactoryBean factory = new MethodInvokingFactoryBean();
            factory.setStaticMethod(staticMethod);
            factory.setArguments(new Object[] { loggerName });
            factory.afterPropertiesSet();

            result = factory.getObject();
        } catch (Throwable e) {
            throw new FatalBeanException("Problem injecting logger.  " + e.getMessage(), e);
        }
    }

    return result;
}

From source file:org.springframework.batch.core.configuration.support.JobRegistryBeanPostProcessor.java

/**
 * If the bean is an instance of {@link Job} then register it.
 * @throws FatalBeanException if there is a {@link DuplicateJobException}.
 *
 * @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization(java.lang.Object,
 * java.lang.String)/*  w w  w . ja va 2s  .  c  o  m*/
 */
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    if (bean instanceof Job) {
        Job job = (Job) bean;
        try {
            String groupName = this.groupName;
            if (beanFactory != null && beanFactory.containsBean(beanName)) {
                groupName = getGroupName(beanFactory.getBeanDefinition(beanName), job);
            }
            job = groupName == null ? job : new GroupAwareJob(groupName, job);
            ReferenceJobFactory jobFactory = new ReferenceJobFactory(job);
            String name = jobFactory.getJobName();
            if (logger.isDebugEnabled()) {
                logger.debug("Registering job: " + name);
            }
            jobRegistry.register(jobFactory);
            jobNames.add(name);
        } catch (DuplicateJobException e) {
            throw new FatalBeanException("Cannot register job configuration", e);
        }
        return job;
    }
    return bean;
}

From source file:org.springframework.beans.BeanUtils.java

/**
 * Copy the property values of the given source bean into the given target bean.
 * <p>Note: The source and target classes do not have to match or even be derived
 * from each other, as long as the properties match. Any bean properties that the
 * source bean exposes but the target bean does not will silently be ignored.
 * @param source the source bean//from w  w  w.  ja  v  a 2s  .  c  o m
 * @param target the target bean
 * @param editable the class (or interface) to restrict property setting to
 * @param ignoreProperties array of property names to ignore
 * @throws BeansException if the copying failed
 * @see BeanWrapper
 */
private static void copyProperties(Object source, Object target, @Nullable Class<?> editable,
        @Nullable String... ignoreProperties) throws BeansException {

    Assert.notNull(source, "Source must not be null");
    Assert.notNull(target, "Target must not be null");

    Class<?> actualEditable = target.getClass();
    if (editable != null) {
        if (!editable.isInstance(target)) {
            throw new IllegalArgumentException("Target class [" + target.getClass().getName()
                    + "] not assignable to Editable class [" + editable.getName() + "]");
        }
        actualEditable = editable;
    }
    PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
    List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);

    for (PropertyDescriptor targetPd : targetPds) {
        Method writeMethod = targetPd.getWriteMethod();
        if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
            PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
            if (sourcePd != null) {
                Method readMethod = sourcePd.getReadMethod();
                if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0],
                        readMethod.getReturnType())) {
                    try {
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                            readMethod.setAccessible(true);
                        }
                        Object value = readMethod.invoke(source);
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            writeMethod.setAccessible(true);
                        }
                        writeMethod.invoke(target, value);
                    } catch (Throwable ex) {
                        throw new FatalBeanException(
                                "Could not copy property '" + targetPd.getName() + "' from source to target",
                                ex);
                    }
                }
            }
        }
    }
}

From source file:org.springframework.beans.CachedIntrospectionResults.java

/**
 * Create a new CachedIntrospectionResults instance for the given class.
 * @param beanClass the bean class to analyze
 * @throws BeansException in case of introspection failure
 *///from   w  w w.j  a v a 2  s.c o  m
private CachedIntrospectionResults(Class<?> beanClass) throws BeansException {
    try {
        if (logger.isTraceEnabled()) {
            logger.trace("Getting BeanInfo for class [" + beanClass.getName() + "]");
        }
        this.beanInfo = getBeanInfo(beanClass, shouldIntrospectorIgnoreBeaninfoClasses);

        if (logger.isTraceEnabled()) {
            logger.trace("Caching PropertyDescriptors for class [" + beanClass.getName() + "]");
        }
        this.propertyDescriptorCache = new LinkedHashMap<>();

        // This call is slow so we do it once.
        PropertyDescriptor[] pds = this.beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor pd : pds) {
            if (Class.class == beanClass
                    && ("classLoader".equals(pd.getName()) || "protectionDomain".equals(pd.getName()))) {
                // Ignore Class.getClassLoader() and getProtectionDomain() methods - nobody needs to bind to those
                continue;
            }
            if (logger.isTraceEnabled()) {
                logger.trace("Found bean property '" + pd.getName() + "'"
                        + (pd.getPropertyType() != null ? " of type [" + pd.getPropertyType().getName() + "]"
                                : "")
                        + (pd.getPropertyEditorClass() != null
                                ? "; editor [" + pd.getPropertyEditorClass().getName() + "]"
                                : ""));
            }
            pd = buildGenericTypeAwarePropertyDescriptor(beanClass, pd);
            this.propertyDescriptorCache.put(pd.getName(), pd);
        }

        // Explicitly check implemented interfaces for setter/getter methods as well,
        // in particular for Java 8 default methods...
        Class<?> clazz = beanClass;
        while (clazz != null && clazz != Object.class) {
            Class<?>[] ifcs = clazz.getInterfaces();
            for (Class<?> ifc : ifcs) {
                if (!ClassUtils.isJavaLanguageInterface(ifc)) {
                    BeanInfo ifcInfo = getBeanInfo(ifc, true);
                    PropertyDescriptor[] ifcPds = ifcInfo.getPropertyDescriptors();
                    for (PropertyDescriptor pd : ifcPds) {
                        if (!this.propertyDescriptorCache.containsKey(pd.getName())) {
                            pd = buildGenericTypeAwarePropertyDescriptor(beanClass, pd);
                            this.propertyDescriptorCache.put(pd.getName(), pd);
                        }
                    }
                }
            }
            clazz = clazz.getSuperclass();
        }

        this.typeDescriptorCache = new ConcurrentReferenceHashMap<>();
    } catch (IntrospectionException ex) {
        throw new FatalBeanException("Failed to obtain BeanInfo for class [" + beanClass.getName() + "]", ex);
    }
}

From source file:org.springframework.integration.test.util.TestUtils.java

private static void registerBean(String beanName, Object bean, BeanFactory beanFactory) {
    Assert.notNull(beanName, "bean name must not be null");
    ConfigurableListableBeanFactory configurableListableBeanFactory = null;
    if (beanFactory instanceof ConfigurableListableBeanFactory) {
        configurableListableBeanFactory = (ConfigurableListableBeanFactory) beanFactory;
    } else if (beanFactory instanceof GenericApplicationContext) {
        configurableListableBeanFactory = ((GenericApplicationContext) beanFactory).getBeanFactory();
    }/*ww  w. j a v a2  s  .  c o m*/
    if (bean instanceof BeanNameAware) {
        ((BeanNameAware) bean).setBeanName(beanName);
    }
    if (bean instanceof BeanFactoryAware) {
        ((BeanFactoryAware) bean).setBeanFactory(beanFactory);
    }
    if (bean instanceof InitializingBean) {
        try {
            ((InitializingBean) bean).afterPropertiesSet();
        } catch (Exception e) {
            throw new FatalBeanException("failed to register bean with test context", e);
        }
    }
    configurableListableBeanFactory.registerSingleton(beanName, bean); //NOSONAR false positive
}

From source file:org.springframework.osgi.extensions.annotation.ServiceReferenceInjectionBeanPostProcessor.java

public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean,
        String beanName) throws BeansException {

    MutablePropertyValues newprops = new MutablePropertyValues(pvs);
    for (PropertyDescriptor pd : pds) {
        ServiceReference s = hasServiceProperty(pd);
        if (s != null && !pvs.contains(pd.getName())) {
            try {
                if (logger.isDebugEnabled())
                    logger.debug(//from   w  w w. j  av a 2  s.co  m
                            "Processing annotation [" + s + "] for [" + beanName + "." + pd.getName() + "]");
                FactoryBean importer = getServiceImporter(s, pd.getWriteMethod(), beanName);
                // BPPs are created in stageOne(), even though they are run
                // in stageTwo(). This check means that
                // the call to getObject() will not fail with
                // ServiceUnavailable. This is safe to do because
                // ServiceReferenceDependencyBeanFactoryPostProcessor will
                // ensure that mandatory services are
                // satisfied before stageTwo() is run.
                if (bean instanceof BeanPostProcessor) {
                    ImporterCallAdapter.setAvailability(importer, Availability.OPTIONAL);
                }
                newprops.addPropertyValue(pd.getName(), importer.getObject());
            } catch (Exception e) {
                throw new FatalBeanException("Could not create service reference", e);
            }
        }
    }
    return newprops;
}

From source file:org.springframework.rest.documentation.boot.RestDocumentationView.java

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

    Resource resource = applicationContext.getResource("classpath:javadoc.json");
    Javadoc javadoc;/*from  www.jav a  2 s .c om*/
    try {
        javadoc = new ObjectMapper().readValue(resource.getInputStream(), Javadoc.class);
    } catch (Exception e) {
        throw new FatalBeanException("Failed to load javadoc JSON", e);
    }

    this.documentationGenerator = new DocumentationGenerator(applicationContext, javadoc);
}

From source file:org.springmodules.commons.validator.DefaultValidatorFactory.java

/**
 * Sets the locations of the validation configuration files from which to load validation rules. Creates an instance
 * of <code>ValidatorResources</code> from the specified configuration files.
 *
 * @see Resource//from   www  .  ja v  a2s  . c om
 * @see ValidatorResources
 */
public void setValidationConfigLocations(Resource[] validationConfigLocations) {

    if (log.isInfoEnabled()) {
        log.info("Loading validation configurations from ["
                + StringUtils.arrayToCommaDelimitedString(validationConfigLocations) + "]");
    }

    try {
        InputStream[] inputStreams = new InputStream[validationConfigLocations.length];

        for (int i = 0; i < inputStreams.length; i++) {
            inputStreams[i] = validationConfigLocations[i].getInputStream();
        }

        this.validatorResources = new ValidatorResources(inputStreams);
    } catch (IOException e) {
        throw new FatalBeanException("Unable to read validation configuration due to IOException.", e);
    } catch (SAXException e) {
        throw new FatalBeanException("Unable to parse validation configuration XML", e);
    }
}

From source file:org.springmodules.workflow.osworkflow.configuration.ConfigurationBean.java

/**
 * Loads a <code>WorkflowDescriptor</code> from the specified location
 * using the <code>WorkflowLoader</code> class.
 *//*  w ww  .j a  va 2s  .com*/
protected WorkflowDescriptor loadWorkflowDescriptor(String resourceLocation, String name) {
    Resource resource = this.resourceLoader.getResource(resourceLocation);
    WorkflowDescriptor workflowDescriptor = null;
    try {
        workflowDescriptor = this.invokeLoader(resource);
    } catch (IOException ex) {
        throw new FatalBeanException("Unable to load workflow resource [" + resourceLocation + "].", ex);
    } catch (InvalidWorkflowDescriptorException ex) {
        throw new FatalBeanException(
                "Descriptor for workflow [" + name + "] in [" + resourceLocation + "] is invalid.", ex);
    } catch (SAXException ex) {
        throw new FatalBeanException(
                "XML in descriptorfor workflow [" + name + "] in [" + resourceLocation + "] is invalid.", ex);
    }
    return workflowDescriptor;
}

From source file:org.tinygroup.beanwrapper.CachedIntrospectionResults.java

/**
 * Create a new CachedIntrospectionResults instance for the given class.
 * @param beanClass the bean class to analyze
 * @throws BeansException in case of introspection failure
 *///from   ww w. ja va 2 s .c  om
private CachedIntrospectionResults(Class beanClass) throws BeansException {
    try {
        if (logger.isTraceEnabled()) {
            logger.trace("Getting BeanInfo for class [" + beanClass.getName() + "]");
        }
        this.beanInfo = Introspector.getBeanInfo(beanClass);

        // Immediately remove class from Introspector cache, to allow for proper
        // garbage collection on class loader shutdown - we cache it here anyway,
        // in a GC-friendly manner. In contrast to CachedIntrospectionResults,
        // Introspector does not use WeakReferences as values of its WeakHashMap!
        Class classToFlush = beanClass;
        do {
            Introspector.flushFromCaches(classToFlush);
            classToFlush = classToFlush.getSuperclass();
        } while (classToFlush != null);

        if (logger.isTraceEnabled()) {
            logger.trace("Caching PropertyDescriptors for class [" + beanClass.getName() + "]");
        }
        this.propertyDescriptorCache = new HashMap();

        // This call is slow so we do it once.
        PropertyDescriptor[] pds = this.beanInfo.getPropertyDescriptors();
        for (int i = 0; i < pds.length; i++) {
            PropertyDescriptor pd = pds[i];
            if (logger.isTraceEnabled()) {
                logger.trace("Found bean property '" + pd.getName() + "'"
                        + (pd.getPropertyType() != null ? " of type [" + pd.getPropertyType().getName() + "]"
                                : "")
                        + (pd.getPropertyEditorClass() != null
                                ? "; editor [" + pd.getPropertyEditorClass().getName() + "]"
                                : ""));
            }
            if (JdkVersion.isAtLeastJava15()) {
                pd = new GenericTypeAwarePropertyDescriptor(beanClass, pd.getName(), pd.getReadMethod(),
                        pd.getWriteMethod(), pd.getPropertyEditorClass());
            }
            this.propertyDescriptorCache.put(pd.getName(), pd);
        }
    } catch (IntrospectionException ex) {
        throw new FatalBeanException("Cannot get BeanInfo for object of class [" + beanClass.getName() + "]",
                ex);
    }
}