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.amqp.rabbit.listener.SimpleMessageListenerContainer.java

/**
 * Avoid the possibility of not configuring the CachingConnectionFactory in sync with the number of concurrent
 * consumers./*from  w  w  w . j av  a  2  s  . c o m*/
 */
@Override
protected void validateConfiguration() {

    super.validateConfiguration();

    Assert.state(!(getAcknowledgeMode().isAutoAck() && this.transactionManager != null),
            "The acknowledgeMode is NONE (autoack in Rabbit terms) which is not consistent with having an "
                    + "external transaction manager. Either use a different AcknowledgeMode or make sure "
                    + "the transactionManager is null.");

}

From source file:org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.java

/**
 * Re-initializes this container's Rabbit message consumers, if not initialized already. Then submits each consumer
 * to this container's task executor.// w w  w . j a v a  2 s .co  m
 * @throws Exception Any Exception.
 */
@Override
protected void doStart() throws Exception {
    if (getMessageListener() instanceof ListenerContainerAware) {
        Collection<String> expectedQueueNames = ((ListenerContainerAware) getMessageListener())
                .expectedQueueNames();
        if (expectedQueueNames != null) {
            String[] queueNames = getQueueNames();
            Assert.state(expectedQueueNames.size() == queueNames.length,
                    "Listener expects us to be listening on '" + expectedQueueNames + "'; our queues: "
                            + Arrays.asList(queueNames));
            boolean found = false;
            for (String queueName : queueNames) {
                if (expectedQueueNames.contains(queueName)) {
                    found = true;
                } else {
                    found = false;
                    break;
                }
            }
            Assert.state(found, "Listener expects us to be listening on '" + expectedQueueNames
                    + "'; our queues: " + Arrays.asList(queueNames));
        }
    }
    if (this.rabbitAdmin == null && this.getApplicationContext() != null) {
        Map<String, RabbitAdmin> admins = this.getApplicationContext().getBeansOfType(RabbitAdmin.class);
        if (admins.size() == 1) {
            this.rabbitAdmin = admins.values().iterator().next();
        } else {
            if (this.autoDeclare || this.mismatchedQueuesFatal) {
                if (logger.isDebugEnabled()) {
                    logger.debug(
                            "For 'autoDeclare' and 'mismatchedQueuesFatal' to work, there must be exactly one "
                                    + "RabbitAdmin in the context or you must inject one into this container; found: "
                                    + admins.size() + " for container " + this.toString());
                }
            }
            if (this.mismatchedQueuesFatal) {
                throw new IllegalStateException("When 'mismatchedQueuesFatal' is 'true', there must be exactly "
                        + "one RabbitAdmin in the context or you must inject one into this container; found: "
                        + admins.size() + " for container " + this.toString());
            }
        }
    }
    checkMismatchedQueues();
    super.doStart();
    synchronized (this.consumersMonitor) {
        int newConsumers = initializeConsumers();
        if (this.consumers == null) {
            if (logger.isInfoEnabled()) {
                logger.info("Consumers were initialized and then cleared "
                        + "(presumably the container was stopped concurrently)");
            }
            return;
        }
        if (newConsumers <= 0) {
            if (logger.isInfoEnabled()) {
                logger.info("Consumers are already running");
            }
            return;
        }
        Set<AsyncMessageProcessingConsumer> processors = new HashSet<AsyncMessageProcessingConsumer>();
        for (BlockingQueueConsumer consumer : this.consumers.keySet()) {
            AsyncMessageProcessingConsumer processor = new AsyncMessageProcessingConsumer(consumer);
            processors.add(processor);
            this.taskExecutor.execute(processor);
        }
        for (AsyncMessageProcessingConsumer processor : processors) {
            FatalListenerStartupException startupException = processor.getStartupException();
            if (startupException != null) {
                throw new AmqpIllegalStateException("Fatal exception on listener startup", startupException);
            }
        }
    }
}

From source file:org.springframework.amqp.rabbit.stocks.context.RefreshScope.java

public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    beanFactory.registerScope(name, this);
    setSerializationId(beanFactory);// w  w  w. jav a  2s  .  co m

    this.beanFactory = beanFactory;

    evaluationContext = new StandardEvaluationContext();
    evaluationContext.addPropertyAccessor(new BeanFactoryAccessor());

    Assert.state(beanFactory instanceof BeanDefinitionRegistry,
            "BeanFactory was not a BeanDefinitionRegistry, so RefreshScope cannot be used.");
    BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

    for (String beanName : beanFactory.getBeanDefinitionNames()) {
        BeanDefinition definition = beanFactory.getBeanDefinition(beanName);
        // Replace this or any of its inner beans with scoped proxy if it
        // has this scope
        boolean scoped = name.equals(definition.getScope());
        Scopifier scopifier = new Scopifier(registry, name, proxyTargetClass, scoped);
        scopifier.visitBeanDefinition(definition);
        if (scoped) {
            createScopedProxy(beanName, definition, registry, proxyTargetClass);
        }
    }

}

From source file:org.springframework.aop.aspectj.AspectJExpressionPointcut.java

private String resolveExpression() {
    String expression = getExpression();
    Assert.state(expression != null, "No expression set");
    return expression;
}

From source file:org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.java

/**
 * Resolves the specified interceptor names to Advisor objects.
 * @see #setInterceptorNames/*from   w  ww .j  av a2s.  c  o m*/
 */
private Advisor[] resolveInterceptorNames() {
    BeanFactory bf = this.beanFactory;
    ConfigurableBeanFactory cbf = (bf instanceof ConfigurableBeanFactory ? (ConfigurableBeanFactory) bf : null);
    List<Advisor> advisors = new ArrayList<>();
    for (String beanName : this.interceptorNames) {
        if (cbf == null || !cbf.isCurrentlyInCreation(beanName)) {
            Assert.state(bf != null, "BeanFactory required for resolving interceptor names");
            Object next = bf.getBean(beanName);
            advisors.add(this.advisorAdapterRegistry.wrap(next));
        }
    }
    return advisors.toArray(new Advisor[advisors.size()]);
}

From source file:org.springframework.aop.framework.CglibAopProxy.java

@Override
public Object getProxy(@Nullable ClassLoader classLoader) {
    if (logger.isDebugEnabled()) {
        logger.debug("Creating CGLIB proxy: target source is " + this.advised.getTargetSource());
    }/*from   w  w  w.j a va2 s.  c  om*/

    try {
        Class<?> rootClass = this.advised.getTargetClass();
        Assert.state(rootClass != null, "Target class must be available for creating a CGLIB proxy");

        Class<?> proxySuperClass = rootClass;
        if (ClassUtils.isCglibProxyClass(rootClass)) {
            proxySuperClass = rootClass.getSuperclass();
            Class<?>[] additionalInterfaces = rootClass.getInterfaces();
            for (Class<?> additionalInterface : additionalInterfaces) {
                this.advised.addInterface(additionalInterface);
            }
        }

        // Validate the class, writing log messages as necessary.
        validateClassIfNecessary(proxySuperClass, classLoader);

        // Configure CGLIB Enhancer...
        Enhancer enhancer = createEnhancer();
        if (classLoader != null) {
            enhancer.setClassLoader(classLoader);
            if (classLoader instanceof SmartClassLoader
                    && ((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) {
                enhancer.setUseCache(false);
            }
        }
        enhancer.setSuperclass(proxySuperClass);
        enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
        enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
        enhancer.setStrategy(new ClassLoaderAwareUndeclaredThrowableStrategy(classLoader));

        Callback[] callbacks = getCallbacks(rootClass);
        Class<?>[] types = new Class<?>[callbacks.length];
        for (int x = 0; x < types.length; x++) {
            types[x] = callbacks[x].getClass();
        }
        // fixedInterceptorMap only populated at this point, after getCallbacks call above
        enhancer.setCallbackFilter(new ProxyCallbackFilter(this.advised.getConfigurationOnlyCopy(),
                this.fixedInterceptorMap, this.fixedInterceptorOffset));
        enhancer.setCallbackTypes(types);

        // Generate the proxy class and create a proxy instance.
        return createProxyClassAndInstance(enhancer, callbacks);
    } catch (CodeGenerationException | IllegalArgumentException ex) {
        throw new AopConfigException(
                "Could not generate CGLIB subclass of class [" + this.advised.getTargetClass() + "]: "
                        + "Common causes of this problem include using a final class or a non-visible class",
                ex);
    } catch (Throwable ex) {
        // TargetSource.getTarget() failed
        throw new AopConfigException("Unexpected AOP exception", ex);
    }
}

From source file:org.springframework.aop.framework.ProxyFactoryBean.java

/**
 * Look at bean factory metadata to work out whether this bean name,
 * which concludes the interceptorNames list, is an Advisor or Advice,
 * or may be a target./*from   ww w  .j a  v a 2 s.  c  o m*/
 * @param beanName bean name to check
 * @return {@code true} if it's an Advisor or Advice
 */
private boolean isNamedBeanAnAdvisorOrAdvice(String beanName) {
    Assert.state(this.beanFactory != null, "No BeanFactory set");
    Class<?> namedBeanClass = this.beanFactory.getType(beanName);
    if (namedBeanClass != null) {
        return (Advisor.class.isAssignableFrom(namedBeanClass)
                || Advice.class.isAssignableFrom(namedBeanClass));
    }
    // Treat it as an target bean if we can't tell.
    if (logger.isDebugEnabled()) {
        logger.debug("Could not determine type of bean with name '" + beanName
                + "' - assuming it is neither an Advisor nor an Advice");
    }
    return false;
}

From source file:org.springframework.aop.target.CommonsPool2TargetSource.java

/**
 * Borrows an object from the {@code ObjectPool}.
 *//*from  w  w  w .  j av  a 2s.c om*/
@Override
public Object getTarget() throws Exception {
    Assert.state(this.pool != null, "No Commons ObjectPool available");
    return this.pool.borrowObject();
}

From source file:org.springframework.batch.admin.integration.StringToFileAdapter.java

public void afterPropertiesSet() {
    Assert.state(fileService != null, "FileService must be provided");
}

From source file:org.springframework.batch.admin.service.LocalFileService.java

public void afterPropertiesSet() throws Exception {
    Assert.state(fileSender != null, "A FileSender must be provided");
    if (!outputDir.exists()) {
        Assert.state(outputDir.mkdirs(), "Cannot create output directory " + outputDir);
    }/*  w w  w. j  a  v a  2s . c om*/
    Assert.state(outputDir.exists(), "Output directory does not exist " + outputDir);
    Assert.state(outputDir.isDirectory(), "Output file is not a directory " + outputDir);
}