Example usage for org.springframework.util Assert state

List of usage examples for org.springframework.util Assert state

Introduction

In this page you can find the example usage for org.springframework.util Assert state.

Prototype

public static void state(boolean expression, Supplier<String> messageSupplier) 

Source Link

Document

Assert a boolean expression, throwing an IllegalStateException if the expression evaluates to false .

Usage

From source file:org.springframework.beans.factory.config.AbstractFactoryBean.java

/**
 * Expose the singleton instance (for access through the 'early singleton' proxy).
 * @return the singleton instance that this FactoryBean holds
 * @throws IllegalStateException if the singleton instance is not initialized
 */// w w  w  .ja v a  2  s .  c o  m
@Nullable
private T getSingletonInstance() throws IllegalStateException {
    Assert.state(this.initialized, "Singleton instance not initialized yet");
    return this.singletonInstance;
}

From source file:org.springframework.beans.factory.config.PropertyPathFactoryBean.java

@Override
@Nullable//w w w  .j a v  a  2s.  co m
public Object getObject() throws BeansException {
    BeanWrapper target = this.targetBeanWrapper;
    if (target != null) {
        if (logger.isWarnEnabled() && this.targetBeanName != null
                && this.beanFactory instanceof ConfigurableBeanFactory
                && ((ConfigurableBeanFactory) this.beanFactory).isCurrentlyInCreation(this.targetBeanName)) {
            logger.warn("Target bean '" + this.targetBeanName + "' is still in creation due to a circular "
                    + "reference - obtained value for property '" + this.propertyPath + "' may be outdated!");
        }
    } else {
        // Fetch prototype target bean...
        Assert.state(this.beanFactory != null, "No BeanFactory available");
        Assert.state(this.targetBeanName != null, "No target bean name specified");
        Object bean = this.beanFactory.getBean(this.targetBeanName);
        target = PropertyAccessorFactory.forBeanPropertyAccess(bean);
    }
    Assert.state(this.propertyPath != null, "No property path specified");
    return target.getPropertyValue(this.propertyPath);
}

From source file:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java

/**
 * Invoke the specified custom init method on the given bean.
 * Called by invokeInitMethods./*from ww  w.j  a va 2  s.  c  om*/
 * <p>Can be overridden in subclasses for custom resolution of init
 * methods with arguments.
 * @see #invokeInitMethods
 */
protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd)
        throws Throwable {

    String initMethodName = mbd.getInitMethodName();
    Assert.state(initMethodName != null, "No init method set");
    final Method initMethod = (mbd.isNonPublicAccessAllowed()
            ? BeanUtils.findMethod(bean.getClass(), initMethodName)
            : ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName));

    if (initMethod == null) {
        if (mbd.isEnforceInitMethod()) {
            throw new BeanDefinitionValidationException("Couldn't find an init method named '" + initMethodName
                    + "' on bean with name '" + beanName + "'");
        } else {
            if (logger.isTraceEnabled()) {
                logger.trace("No default init method named '" + initMethodName + "' found on bean with name '"
                        + beanName + "'");
            }
            // Ignore non-existent default lifecycle methods.
            return;
        }
    }

    if (logger.isTraceEnabled()) {
        logger.trace("Invoking init method  '" + initMethodName + "' on bean with name '" + beanName + "'");
    }

    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
            ReflectionUtils.makeAccessible(initMethod);
            return null;
        });
        try {
            AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> initMethod.invoke(bean),
                    getAccessControlContext());
        } catch (PrivilegedActionException pae) {
            InvocationTargetException ex = (InvocationTargetException) pae.getException();
            throw ex.getTargetException();
        }
    } else {
        try {
            ReflectionUtils.makeAccessible(initMethod);
            initMethod.invoke(bean);
        } catch (InvocationTargetException ex) {
            throw ex.getTargetException();
        }
    }
}

From source file:org.springframework.beans.factory.support.ConstructorResolver.java

/**
 * Resolve the factory method in the specified bean definition, if possible.
 * {@link RootBeanDefinition#getResolvedFactoryMethod()} can be checked for the result.
 * @param mbd the bean definition to check
 *///from  w w w .j  av  a2 s  .co m
public void resolveFactoryMethodIfPossible(RootBeanDefinition mbd) {
    Class<?> factoryClass;
    boolean isStatic;
    if (mbd.getFactoryBeanName() != null) {
        factoryClass = this.beanFactory.getType(mbd.getFactoryBeanName());
        isStatic = false;
    } else {
        factoryClass = mbd.getBeanClass();
        isStatic = true;
    }
    Assert.state(factoryClass != null, "Unresolvable factory class");
    factoryClass = ClassUtils.getUserClass(factoryClass);

    Method[] candidates = getCandidateMethods(factoryClass, mbd);
    Method uniqueCandidate = null;
    for (Method candidate : candidates) {
        if (Modifier.isStatic(candidate.getModifiers()) == isStatic && mbd.isFactoryMethod(candidate)) {
            if (uniqueCandidate == null) {
                uniqueCandidate = candidate;
            } else if (!Arrays.equals(uniqueCandidate.getParameterTypes(), candidate.getParameterTypes())) {
                uniqueCandidate = null;
                break;
            }
        }
    }
    synchronized (mbd.constructorArgumentLock) {
        mbd.resolvedConstructorOrFactoryMethod = uniqueCandidate;
    }
}

From source file:org.springframework.beans.factory.wiring.BeanConfigurerSupport.java

/**
 * Configure the bean instance.//  www. j  av a  2 s .com
 * <p>Subclasses can override this to provide custom configuration logic.
 * Typically called by an aspect, for all bean instances matched by a pointcut.
 * @param beanInstance the bean instance to configure (must <b>not</b> be {@code null})
 */
public void configureBean(Object beanInstance) {
    if (this.beanFactory == null) {
        if (logger.isDebugEnabled()) {
            logger.debug("BeanFactory has not been set on " + ClassUtils.getShortName(getClass()) + ": "
                    + "Make sure this configurer runs in a Spring container. Unable to configure bean of type ["
                    + ClassUtils.getDescriptiveType(beanInstance) + "]. Proceeding without injection.");
        }
        return;
    }

    BeanWiringInfoResolver bwiResolver = this.beanWiringInfoResolver;
    Assert.state(bwiResolver != null, "No BeanWiringInfoResolver available");
    BeanWiringInfo bwi = bwiResolver.resolveWiringInfo(beanInstance);
    if (bwi == null) {
        // Skip the bean if no wiring info given.
        return;
    }

    ConfigurableListableBeanFactory beanFactory = this.beanFactory;
    Assert.state(beanFactory != null, "No BeanFactory available");
    try {
        if (bwi.indicatesAutowiring() || (bwi.isDefaultBeanName() && bwi.getBeanName() != null
                && !beanFactory.containsBean(bwi.getBeanName()))) {
            // Perform autowiring (also applying standard factory / post-processor callbacks).
            beanFactory.autowireBeanProperties(beanInstance, bwi.getAutowireMode(), bwi.getDependencyCheck());
            beanFactory.initializeBean(beanInstance, bwi.getBeanName());
        } else {
            // Perform explicit wiring based on the specified bean definition.
            beanFactory.configureBean(beanInstance, bwi.getBeanName());
        }
    } catch (BeanCreationException ex) {
        Throwable rootCause = ex.getMostSpecificCause();
        if (rootCause instanceof BeanCurrentlyInCreationException) {
            BeanCreationException bce = (BeanCreationException) rootCause;
            String bceBeanName = bce.getBeanName();
            if (bceBeanName != null && beanFactory.isCurrentlyInCreation(bceBeanName)) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Failed to create target bean '" + bce.getBeanName()
                            + "' while configuring object of type [" + beanInstance.getClass().getName()
                            + "] - probably due to a circular reference. This is a common startup situation "
                            + "and usually not fatal. Proceeding without injection. Original exception: " + ex);
                }
                return;
            }
        }
        throw ex;
    }
}

From source file:org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.java

/**
 * Return the descriptor for the XML resource that this parser works on.
 *//*from w  w  w  .  ja v a  2  s  . c om*/
protected final XmlReaderContext getReaderContext() {
    Assert.state(this.readerContext != null, "No XmlReaderContext available");
    return this.readerContext;
}

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

public Method getWriteMethodForActualAccess() {
    Assert.state(this.writeMethod != null, "No write method available");
    Set<Method> ambiguousCandidates = this.ambiguousWriteMethods;
    if (ambiguousCandidates != null) {
        this.ambiguousWriteMethods = null;
        LogFactory.getLog(GenericTypeAwarePropertyDescriptor.class)
                .warn("Invalid JavaBean property '" + getName()
                        + "' being accessed! Ambiguous write methods found next to actually used ["
                        + this.writeMethod + "]: " + ambiguousCandidates);
    }/*from  w w w.j  a v  a2  s .c  o  m*/
    return this.writeMethod;
}

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

public MethodParameter getWriteMethodParameter() {
    Assert.state(this.writeMethodParameter != null, "No write method available");
    return this.writeMethodParameter;
}

From source file:org.springframework.boot.actuate.endpoint.annotation.AnnotationEndpointDiscoverer.java

private void addEndpoint(Map<Class<?>, DiscoveredEndpoint> endpoints,
        Map<String, DiscoveredEndpoint> endpointsById, String beanName) {
    Class<?> endpointType = this.applicationContext.getType(beanName);
    Object target = this.applicationContext.getBean(beanName);
    DiscoveredEndpoint endpoint = createEndpoint(target, endpointType);
    String id = endpoint.getInfo().getId();
    DiscoveredEndpoint previous = endpointsById.putIfAbsent(id, endpoint);
    Assert.state(previous == null,
            () -> "Found two endpoints with the id '" + id + "': " + endpoint + " and " + previous);
    endpoints.put(endpointType, endpoint);
}

From source file:org.springframework.boot.actuate.endpoint.annotation.AnnotationEndpointDiscoverer.java

private DiscoveredEndpoint createEndpoint(Object target, Class<?> endpointType) {
    AnnotationAttributes annotationAttributes = AnnotatedElementUtils
            .findMergedAnnotationAttributes(endpointType, Endpoint.class, true, true);
    String id = annotationAttributes.getString("id");
    Assert.state(StringUtils.hasText(id), "No @Endpoint id attribute specified for " + endpointType.getName());
    boolean enabledByDefault = (Boolean) annotationAttributes.get("enableByDefault");
    Collection<T> operations = this.operationsFactory.createOperations(id, target, endpointType).values();
    EndpointInfo<T> endpointInfo = new EndpointInfo<>(id, enabledByDefault, operations);
    boolean exposed = isEndpointExposed(endpointType, endpointInfo);
    return new DiscoveredEndpoint(endpointType, endpointInfo, exposed);
}