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.cloud.context.scope.GenericScope.java

public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    beanFactory.registerScope(name, this);
    setSerializationId(beanFactory);//from w w  w .j  a v  a  2s.  c om

    this.beanFactory = beanFactory;

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

    if (!autoProxy) {
        // No need to try and create proxies
        return;
    }

    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.cloud.gateway.test.support.AbstractHttpServer.java

@Override
public final void afterPropertiesSet() throws Exception {
    Assert.notNull(this.host, "Host must not be null");
    Assert.isTrue(this.port >= 0, "Port must not be a negative number");
    Assert.isTrue(this.httpHandler != null || this.handlerMap != null, "No HttpHandler configured");
    Assert.state(!this.running, "Cannot reconfigure while running");

    synchronized (this.lifecycleMonitor) {
        initServer();//from   w  ww .ja v a2  s  .c o m
    }
}

From source file:org.springframework.cloud.gcp.storage.integration.GcsSession.java

@Override
public boolean remove(String path) throws IOException {
    String[] tokens = getBucketAndObjectFromPath(path);
    Assert.state(tokens.length == 1 || tokens.length == 2,
            "Path must be in the form of [bucket] or [bucket]/[blob name]");

    return (tokens.length == 1) ? this.gcs.delete(tokens[0]) : this.gcs.delete(tokens[0], tokens[1]);
}

From source file:org.springframework.cloud.gcp.storage.integration.GcsSession.java

@Override
public void read(String source, OutputStream outputStream) throws IOException {
    String[] tokens = getBucketAndObjectFromPath(source);
    Assert.state(tokens.length == 2, "Can only read files, not buckets.");

    try (OutputStream os = outputStream) {
        os.write(this.gcs.readAllBytes(tokens[0], tokens[1]));
    }/*from  w w  w  .  j av a 2 s .c  om*/
}

From source file:org.springframework.cloud.gcp.storage.integration.GcsSession.java

@Override
public void write(InputStream inputStream, String destination) throws IOException {
    String[] tokens = getBucketAndObjectFromPath(destination);
    Assert.state(tokens.length == 2, "Can only write to files, not buckets.");

    BlobInfo gcsBlobInfo = BlobInfo.newBuilder(BlobId.of(tokens[0], tokens[1])).build();

    try (InputStream is = inputStream) {
        try (WriteChannel channel = this.gcs.writer(gcsBlobInfo)) {
            channel.write(ByteBuffer.wrap(StreamUtils.copyToByteArray(is)));
        }/*from  ww w  . j  a v  a 2  s  .c o  m*/
    }
}

From source file:org.springframework.cloud.gcp.storage.integration.GcsSession.java

@Override
public InputStream readRaw(String source) throws IOException {
    String[] tokens = getBucketAndObjectFromPath(source);
    Assert.state(tokens.length == 2, "Can only write to files, not buckets.");
    return Channels.newInputStream(this.gcs.reader(tokens[0], tokens[1]));
}

From source file:org.springframework.cloud.stream.app.pmml.processor.PmmlProcessorConfiguration.java

@PostConstruct
public void setUp() throws IOException, SAXException, JAXBException {
    try (InputStream is = properties.getModelLocation().getInputStream()) {
        Source transformedSource = ImportFilter.apply(new InputSource(is));
        pmml = JAXBUtil.unmarshalPMML(transformedSource);
        Assert.state(!pmml.getModels().isEmpty(),
                "The provided PMML file at " + properties.getModelLocation() + " does not contain any model");
    }//from www  .  jav  a 2 s.  com
}

From source file:org.springframework.cloud.stream.reactive.StreamEmitterAnnotationBeanPostProcessor.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private void invokeSetupMethodOnToTargetChannel(Method method, Object bean, String outboundName) {
    Object[] arguments = new Object[method.getParameterCount()];
    Object targetBean = null;/*w w w. j a va  2  s.com*/
    for (int parameterIndex = 0; parameterIndex < arguments.length; parameterIndex++) {
        MethodParameter methodParameter = new SynthesizingMethodParameter(method, parameterIndex);
        Class<?> parameterType = methodParameter.getParameterType();
        Object targetReferenceValue = null;
        if (methodParameter.hasParameterAnnotation(Output.class)) {
            targetReferenceValue = AnnotationUtils
                    .getValue(methodParameter.getParameterAnnotation(Output.class));
        } else if (arguments.length == 1 && StringUtils.hasText(outboundName)) {
            targetReferenceValue = outboundName;
        }
        if (targetReferenceValue != null) {
            targetBean = this.applicationContext.getBean((String) targetReferenceValue);
            for (StreamListenerParameterAdapter<?, Object> streamListenerParameterAdapter : this.streamListenerParameterAdapters) {
                if (streamListenerParameterAdapter.supports(targetBean.getClass(), methodParameter)) {
                    arguments[parameterIndex] = streamListenerParameterAdapter.adapt(targetBean,
                            methodParameter);
                    if (arguments[parameterIndex] instanceof FluxSender) {
                        closeableFluxResources.add((FluxSender) arguments[parameterIndex]);
                    }
                    break;
                }
            }
            Assert.notNull(arguments[parameterIndex], "Cannot convert argument " + parameterIndex + " of "
                    + method + "from " + targetBean.getClass() + " to " + parameterType);
        } else {
            throw new IllegalStateException(StreamEmitterErrorMessages.ATLEAST_ONE_OUTPUT);
        }
    }
    Object result;
    try {
        result = method.invoke(bean, arguments);
    } catch (Exception e) {
        throw new BeanInitializationException("Cannot setup StreamEmitter for " + method, e);
    }

    if (!Void.TYPE.equals(method.getReturnType())) {
        if (targetBean == null) {
            targetBean = this.applicationContext.getBean(outboundName);
        }
        boolean streamListenerResultAdapterFound = false;
        for (StreamListenerResultAdapter streamListenerResultAdapter : this.streamListenerResultAdapters) {
            if (streamListenerResultAdapter.supports(result.getClass(), targetBean.getClass())) {
                Closeable fluxDisposable = streamListenerResultAdapter.adapt(result, targetBean);
                closeableFluxResources.add(fluxDisposable);
                streamListenerResultAdapterFound = true;
                break;
            }
        }
        Assert.state(streamListenerResultAdapterFound,
                StreamEmitterErrorMessages.CANNOT_CONVERT_RETURN_TYPE_TO_ANY_AVAILABLE_RESULT_ADAPTERS);
    }
}

From source file:org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.java

/**
 * Read the given {@link BeanMethod}, registering bean definitions
 * with the BeanDefinitionRegistry based on its contents.
 *///  w  ww  . ja v a  2 s  .co  m
private void loadBeanDefinitionsForBeanMethod(BeanMethod beanMethod) {
    ConfigurationClass configClass = beanMethod.getConfigurationClass();
    MethodMetadata metadata = beanMethod.getMetadata();
    String methodName = metadata.getMethodName();

    // Do we need to mark the bean as skipped by its condition?
    if (this.conditionEvaluator.shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN)) {
        configClass.skippedBeanMethods.add(methodName);
        return;
    }
    if (configClass.skippedBeanMethods.contains(methodName)) {
        return;
    }

    AnnotationAttributes bean = AnnotationConfigUtils.attributesFor(metadata, Bean.class);
    Assert.state(bean != null, "No @Bean annotation attributes");

    // Consider name and any aliases
    List<String> names = new ArrayList<>(Arrays.asList(bean.getStringArray("name")));
    String beanName = (!names.isEmpty() ? names.remove(0) : methodName);

    // Register aliases even when overridden
    for (String alias : names) {
        this.registry.registerAlias(beanName, alias);
    }

    // Has this effectively been overridden before (e.g. via XML)?
    if (isOverriddenByExistingDefinition(beanMethod, beanName)) {
        if (beanName.equals(beanMethod.getConfigurationClass().getBeanName())) {
            throw new BeanDefinitionStoreException(
                    beanMethod.getConfigurationClass().getResource().getDescription(), beanName,
                    "Bean name derived from @Bean method '" + beanMethod.getMetadata().getMethodName()
                            + "' clashes with bean name for containing configuration class; please make those names unique!");
        }
        return;
    }

    ConfigurationClassBeanDefinition beanDef = new ConfigurationClassBeanDefinition(configClass, metadata);
    beanDef.setResource(configClass.getResource());
    beanDef.setSource(this.sourceExtractor.extractSource(metadata, configClass.getResource()));

    if (metadata.isStatic()) {
        // static @Bean method
        beanDef.setBeanClassName(configClass.getMetadata().getClassName());
        beanDef.setFactoryMethodName(methodName);
    } else {
        // instance @Bean method
        beanDef.setFactoryBeanName(configClass.getBeanName());
        beanDef.setUniqueFactoryMethodName(methodName);
    }
    beanDef.setAutowireMode(RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
    beanDef.setAttribute(RequiredAnnotationBeanPostProcessor.SKIP_REQUIRED_CHECK_ATTRIBUTE, Boolean.TRUE);

    AnnotationConfigUtils.processCommonDefinitionAnnotations(beanDef, metadata);

    Autowire autowire = bean.getEnum("autowire");
    if (autowire.isAutowire()) {
        beanDef.setAutowireMode(autowire.value());
    }

    String initMethodName = bean.getString("initMethod");
    if (StringUtils.hasText(initMethodName)) {
        beanDef.setInitMethodName(initMethodName);
    }

    String destroyMethodName = bean.getString("destroyMethod");
    beanDef.setDestroyMethodName(destroyMethodName);

    // Consider scoping
    ScopedProxyMode proxyMode = ScopedProxyMode.NO;
    AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(metadata, Scope.class);
    if (attributes != null) {
        beanDef.setScope(attributes.getString("value"));
        proxyMode = attributes.getEnum("proxyMode");
        if (proxyMode == ScopedProxyMode.DEFAULT) {
            proxyMode = ScopedProxyMode.NO;
        }
    }

    // Replace the original bean definition with the target one, if necessary
    BeanDefinition beanDefToRegister = beanDef;
    if (proxyMode != ScopedProxyMode.NO) {
        BeanDefinitionHolder proxyDef = ScopedProxyCreator.createScopedProxy(
                new BeanDefinitionHolder(beanDef, beanName), this.registry,
                proxyMode == ScopedProxyMode.TARGET_CLASS);
        beanDefToRegister = new ConfigurationClassBeanDefinition(
                (RootBeanDefinition) proxyDef.getBeanDefinition(), configClass, metadata);
    }

    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Registering bean definition for @Bean method %s.%s()",
                configClass.getMetadata().getClassName(), beanName));
    }

    this.registry.registerBeanDefinition(beanName, beanDefToRegister);
}

From source file:org.springframework.context.event.EventListenerMethodProcessor.java

private ConfigurableApplicationContext getApplicationContext() {
    Assert.state(this.applicationContext != null, "No ApplicationContext set");
    return this.applicationContext;
}