Change relevant Assert calls to throw IllegalStateException

Change certain Assert class from `assert...` to `assertState`
so that a more appropriate `IllegalStateException` is thrown.

Fixes gh-43779
This commit is contained in:
Phillip Webb 2025-01-10 23:01:17 -08:00
parent 29baaf32e6
commit f08188d5cf
76 changed files with 201 additions and 188 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -69,7 +69,7 @@ public class AvailabilityStateHealthIndicator extends AbstractHealthIndicator {
if (!this.statusMappings.containsKey(null) && Enum.class.isAssignableFrom(stateType)) {
EnumSet elements = EnumSet.allOf((Class) stateType);
for (Object element : elements) {
Assert.isTrue(this.statusMappings.containsKey(element),
Assert.state(this.statusMappings.containsKey(element),
() -> "StatusMappings does not include " + element);
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -209,7 +209,7 @@ public class HeapDumpWebEndpoint {
@Override
public File dumpHeap(Boolean live) throws IOException, InterruptedException {
Assert.isNull(live, "OpenJ9DiagnosticsMXBean does not support live parameter when dumping the heap");
Assert.state(live == null, "OpenJ9DiagnosticsMXBean does not support live parameter when dumping the heap");
return new File(
(String) ReflectionUtils.invokeMethod(this.dumpHeapMethod, this.diagnosticMXBean, "heap", null));
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -28,6 +28,7 @@ import org.springframework.boot.availability.LivenessState;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.BDDMockito.given;
/**
@ -67,7 +68,7 @@ class AvailabilityStateHealthIndicatorTests {
@Test
void createWhenStatusMappingDoesNotCoverAllEnumsThrowsException() {
assertThatIllegalArgumentException()
assertThatIllegalStateException()
.isThrownBy(() -> new AvailabilityStateHealthIndicator(this.applicationAvailability, LivenessState.class,
(statusMappings) -> statusMappings.add(LivenessState.CORRECT, Status.UP)))
.withMessage("StatusMappings does not include BROKEN");

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -57,6 +57,7 @@ import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
/**
@ -170,7 +171,7 @@ public class AutoConfigurationImportSelector implements DeferredImportSelector,
protected AnnotationAttributes getAttributes(AnnotationMetadata metadata) {
String name = getAnnotationClass().getName();
AnnotationAttributes attributes = AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(name, true));
Assert.notNull(attributes, () -> "No auto-configuration attributes found. Is " + metadata.getClassName()
Assert.state(attributes != null, () -> "No auto-configuration attributes found. Is " + metadata.getClassName()
+ " annotated with " + ClassUtils.getShortName(name) + "?");
return attributes;
}
@ -195,7 +196,7 @@ public class AutoConfigurationImportSelector implements DeferredImportSelector,
ImportCandidates importCandidates = ImportCandidates.load(this.autoConfigurationAnnotation,
getBeanClassLoader());
List<String> configurations = importCandidates.getCandidates();
Assert.notEmpty(configurations,
Assert.state(!CollectionUtils.isEmpty(configurations),
"No auto configuration classes found in " + "META-INF/spring/"
+ this.autoConfigurationAnnotation.getName() + ".imports. If you "
+ "are using a custom packaging, make sure that file is correct.");

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -112,10 +112,10 @@ public class JobLauncherApplicationRunner
@Override
public void afterPropertiesSet() {
Assert.isTrue(this.jobs.size() <= 1 || StringUtils.hasText(this.jobName),
Assert.state(this.jobs.size() <= 1 || StringUtils.hasText(this.jobName),
"Job name must be specified in case of multiple jobs");
if (StringUtils.hasText(this.jobName)) {
Assert.isTrue(isLocalJob(this.jobName) || isRegisteredJob(this.jobName),
Assert.state(isLocalJob(this.jobName) || isRegisteredJob(this.jobName),
() -> "No job found with name '" + this.jobName + "'");
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -102,7 +102,7 @@ public class CacheAutoConfiguration {
@Override
public void afterPropertiesSet() {
Assert.notNull(this.cacheManager.getIfAvailable(),
Assert.state(this.cacheManager.getIfAvailable() != null,
() -> "No cache manager could be auto-configured, check your configuration (caching type is '"
+ this.cacheProperties.getType() + "')");
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -250,8 +250,8 @@ class OnBeanCondition extends FilteringSpringBootCondition implements Configurat
ConfigurableListableBeanFactory beanFactory = spec.getContext().getBeanFactory();
if (spec.getStrategy() == SearchStrategy.ANCESTORS) {
BeanFactory parent = beanFactory.getParentBeanFactory();
Assert.isInstanceOf(ConfigurableListableBeanFactory.class, parent,
"Unable to use SearchStrategy.ANCESTORS");
Assert.state(parent instanceof ConfigurableListableBeanFactory,
"Unable to use SearchStrategy.ANCESTORS without ConfigurableListableBeanFactory");
beanFactory = (ConfigurableListableBeanFactory) parent;
}
return beanFactory;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -45,7 +45,7 @@ class OnResourceCondition extends SpringBootCondition {
ResourceLoader loader = context.getResourceLoader();
List<String> locations = new ArrayList<>();
collectValues(locations, attributes.get("resources"));
Assert.isTrue(!locations.isEmpty(),
Assert.state(!locations.isEmpty(),
"@ConditionalOnResource annotations must specify at least one resource location");
List<String> missing = new ArrayList<>();
for (String location : locations) {

View File

@ -583,7 +583,7 @@ public class FlywayAutoConfiguration {
Extension(FluentConfiguration configuration, Class<E> type, String name) {
this.extension = SingletonSupplier.of(() -> {
E extension = configuration.getPluginRegister().getPlugin(type);
Assert.notNull(extension, () -> "Flyway %s extension missing".formatted(name));
Assert.state(extension != null, () -> "Flyway %s extension missing".formatted(name));
return extension;
});
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -52,7 +52,7 @@ public class HazelcastProperties {
if (this.config == null) {
return null;
}
Assert.isTrue(this.config.exists(),
Assert.state(this.config.exists(),
() -> "Hazelcast configuration does not exist '" + this.config.getDescription() + "'");
return this.config;
}

View File

@ -292,7 +292,7 @@ public class JacksonAutoConfiguration {
// Find the field (this way we automatically support new constants
// that may be added by Jackson in the future)
Field field = findPropertyNamingStrategyField(fieldName);
Assert.notNull(field, () -> "Constant named '" + fieldName + "' not found");
Assert.state(field != null, () -> "Constant named '" + fieldName + "' not found");
try {
builder.propertyNamingStrategy((PropertyNamingStrategy) field.get(null));
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -96,7 +96,8 @@ public class XADataSourceAutoConfiguration implements BeanClassLoaderAware {
try {
Class<?> dataSourceClass = ClassUtils.forName(className, this.classLoader);
Object instance = BeanUtils.instantiateClass(dataSourceClass);
Assert.isInstanceOf(XADataSource.class, instance);
Assert.state(instance instanceof XADataSource,
() -> "DataSource class " + className + " is not an XADataSource");
return (XADataSource) instance;
}
catch (Exception ex) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -175,8 +175,8 @@ class Saml2RelyingPartyRegistrationConfiguration {
try (InputStream inputStream = location.getInputStream()) {
PemContent pemContent = PemContent.load(inputStream);
PrivateKey privateKey = pemContent.getPrivateKey();
Assert.isInstanceOf(RSAPrivateKey.class, privateKey,
"PrivateKey in resource '" + location + "' must be an RSAPrivateKey");
Assert.state(privateKey instanceof RSAPrivateKey,
() -> "PrivateKey in resource '" + location + "' must be an RSAPrivateKey");
return (RSAPrivateKey) privateKey;
}
catch (Exception ex) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -53,7 +53,7 @@ class CertificateMatcher {
Assert.notNull(privateKey, "Private key must not be null");
this.privateKey = privateKey;
this.signature = createSignature(privateKey);
Assert.notNull(this.signature, "Failed to create signature");
Assert.state(this.signature != null, "Failed to create signature");
this.generatedSignature = sign(this.signature, privateKey);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -127,7 +127,7 @@ public final class PropertiesSslBundle implements SslBundle {
if (properties.isVerifyKeys()) {
CertificateMatcher certificateMatcher = new CertificateMatcher(pemSslStore.privateKey());
Assert.state(certificateMatcher.matchesAny(pemSslStore.certificates()),
"Private key in %s matches none of the certificates in the chain".formatted(propertyName));
() -> "Private key in %s matches none of the certificates in the chain".formatted(propertyName));
}
return pemSslStore;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -91,7 +91,7 @@ import org.springframework.transaction.PlatformTransactionManager;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -484,7 +484,7 @@ class BatchAutoConfigurationTests {
JobLauncherApplicationRunner runner = createInstance();
runner.setJobs(Arrays.asList(mockJob("one"), mockJob("two")));
runner.setJobName("three");
assertThatIllegalArgumentException().isThrownBy(runner::afterPropertiesSet)
assertThatIllegalStateException().isThrownBy(runner::afterPropertiesSet)
.withMessage("No job found with name 'three'");
}
@ -492,7 +492,7 @@ class BatchAutoConfigurationTests {
void whenTheUserDefinesAJobNameThatDoesNotExistWithRegisteredJobFailsFast() {
JobLauncherApplicationRunner runner = createInstance("one", "two");
runner.setJobName("three");
assertThatIllegalArgumentException().isThrownBy(runner::afterPropertiesSet)
assertThatIllegalStateException().isThrownBy(runner::afterPropertiesSet)
.withMessage("No job found with name 'three'");
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -272,7 +272,7 @@ public class Restarter {
}
private Throwable doStart() throws Exception {
Assert.notNull(this.mainClassName, "Unable to find the main class to restart");
Assert.state(this.mainClassName != null, "Unable to find the main class to restart");
URL[] urls = this.urls.toArray(new URL[0]);
ClassLoaderFiles updatedFiles = new ClassLoaderFiles(this.classLoaderFiles);
ClassLoader classLoader = new RestartClassLoader(this.applicationClassLoader, urls, updatedFiles);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -97,7 +97,8 @@ class DefaultConnectionPorts implements ConnectionPorts {
@Override
public int get(int containerPort) {
Integer hostPort = this.portMappings.get(containerPort);
Assert.state(hostPort != null, "No host port mapping found for container port %s".formatted(containerPort));
Assert.state(hostPort != null,
() -> "No host port mapping found for container port %s".formatted(containerPort));
return hostPort;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -102,7 +102,7 @@ class DefaultDockerCompose implements DockerCompose {
Map<String, DockerCliInspectResponse> inspected = inspect(runningPsResponses);
for (DockerCliComposePsResponse psResponse : runningPsResponses) {
DockerCliInspectResponse inspectResponse = inspectContainer(psResponse.id(), inspected);
Assert.notNull(inspectResponse, () -> "Failed to inspect container '%s'".formatted(psResponse.id()));
Assert.state(inspectResponse != null, () -> "Failed to inspect container '%s'".formatted(psResponse.id()));
result.add(new DefaultRunningService(this.hostname, dockerComposeFile, psResponse, inspectResponse));
}
return Collections.unmodifiableList(result);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -47,7 +47,7 @@ public final class DockerComposeFile {
private final List<File> files;
private DockerComposeFile(List<File> files) {
Assert.state(!files.isEmpty(), "Files must not be empty");
Assert.isTrue(!files.isEmpty(), "'files' must not be empty");
this.files = files.stream().map(DockerComposeFile::toCanonicalFile).toList();
}
@ -112,7 +112,7 @@ public final class DockerComposeFile {
if (!base.exists()) {
return null;
}
Assert.isTrue(base.isDirectory(), () -> "'%s' is not a directory".formatted(base));
Assert.state(base.isDirectory(), () -> "'%s' is not a directory".formatted(base));
Path basePath = base.toPath();
for (String candidate : SEARCH_ORDER) {
Path resolved = basePath.resolve(candidate);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -27,6 +27,7 @@ import org.springframework.util.FileCopyUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* Tests for {@link DockerComposeFile}.
@ -104,7 +105,7 @@ class DockerComposeFileTests {
@Test
void findWhenWorkingDirectoryIsNotDirectoryThrowsException() throws Exception {
File file = createTempFile("iamafile");
assertThatIllegalArgumentException().isThrownBy(() -> DockerComposeFile.find(file))
assertThatIllegalStateException().isThrownBy(() -> DockerComposeFile.find(file))
.withMessageEndingWith("is not a directory");
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -65,7 +65,7 @@ class BuilderBuildpack implements Buildpack {
.of(unambiguous ? reference.getSubReference(PREFIX) : reference.toString());
BuildpackMetadata buildpackMetadata = findBuildpackMetadata(context, builderReference);
if (unambiguous) {
Assert.isTrue(buildpackMetadata != null, () -> "Buildpack '" + reference + "' not found in builder");
Assert.state(buildpackMetadata != null, () -> "Buildpack '" + reference + "' not found in builder");
}
return (buildpackMetadata != null) ? new BuilderBuildpack(buildpackMetadata) : null;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -158,7 +158,7 @@ class BuilderMetadata extends MappedObject {
static BuilderMetadata fromImageConfig(ImageConfig imageConfig) throws IOException {
Assert.notNull(imageConfig, "ImageConfig must not be null");
String json = imageConfig.getLabels().get(LABEL_NAME);
Assert.notNull(json, () -> "No '" + LABEL_NAME + "' label found in image config labels '"
Assert.state(json != null, () -> "No '" + LABEL_NAME + "' label found in image config labels '"
+ StringUtils.collectionToCommaDelimitedString(imageConfig.getLabels().keySet()) + "'");
return fromJson(json);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -77,7 +77,7 @@ final class BuildpackLayersMetadata extends MappedObject {
static BuildpackLayersMetadata fromImageConfig(ImageConfig imageConfig) throws IOException {
Assert.notNull(imageConfig, "ImageConfig must not be null");
String json = imageConfig.getLabels().get(LABEL_NAME);
Assert.notNull(json, () -> "No '" + LABEL_NAME + "' label found in image config labels '"
Assert.state(json != null, () -> "No '" + LABEL_NAME + "' label found in image config labels '"
+ StringUtils.collectionToCommaDelimitedString(imageConfig.getLabels().keySet()) + "'");
return fromJson(json);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -94,7 +94,7 @@ final class BuildpackMetadata extends MappedObject {
static BuildpackMetadata fromImageConfig(ImageConfig imageConfig) throws IOException {
Assert.notNull(imageConfig, "ImageConfig must not be null");
String json = imageConfig.getLabels().get(LABEL_NAME);
Assert.notNull(json, () -> "No '" + LABEL_NAME + "' label found in image config labels '"
Assert.state(json != null, () -> "No '" + LABEL_NAME + "' label found in image config labels '"
+ StringUtils.collectionToCommaDelimitedString(imageConfig.getLabels().keySet()) + "'");
return fromJson(json);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -56,7 +56,7 @@ final class DirectoryBuildpack implements Buildpack {
private BuildpackCoordinates findBuildpackCoordinates(Path path) {
Path buildpackToml = path.resolve("buildpack.toml");
Assert.isTrue(Files.exists(buildpackToml),
Assert.state(Files.exists(buildpackToml),
() -> "Buildpack descriptor 'buildpack.toml' is required in buildpack '" + path + "'");
try {
try (InputStream inputStream = Files.newInputStream(buildpackToml)) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -127,7 +127,8 @@ class ExportedImageTar implements Closeable {
entry = tar.getNextEntry();
}
Assert.state(index != null || manifest != null,
"Exported image '%s' does not contain 'index.json' or 'manifest.json'".formatted(reference));
() -> "Exported image '%s' does not contain 'index.json' or 'manifest.json'"
.formatted(reference));
return (index != null) ? new IndexLayerArchiveFactory(tarFile, index)
: new ManifestLayerArchiveFactory(tarFile, manifest);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -445,7 +445,7 @@ final class PemPrivateKeyParser {
public static final String PBES2_ALGORITHM = "PBES2";
static PKCS8EncodedKeySpec decrypt(byte[] bytes, String password) {
Assert.notNull(password, "Password is required for an encrypted private key");
Assert.state(password != null, "Password is required for an encrypted private key");
try {
EncryptedPrivateKeyInfo keyInfo = new EncryptedPrivateKeyInfo(bytes);
AlgorithmParameters algorithmParameters = keyInfo.getAlgParameters();

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -35,6 +35,7 @@ import org.springframework.boot.buildpack.platform.docker.configuration.DockerHo
import org.springframework.boot.buildpack.platform.docker.configuration.ResolvedDockerHost;
import org.springframework.boot.buildpack.platform.docker.ssl.SslContextFactory;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* {@link HttpClientTransport} that talks to a remote Docker.
@ -85,8 +86,8 @@ final class RemoteHttpClientTransport extends HttpClientTransport {
private static TlsSocketStrategy getTlsSocketStrategy(DockerHost host, SslContextFactory sslContextFactory) {
String directory = host.getCertificatePath();
Assert.hasText(directory,
() -> "Docker host TLS verification requires trust material location to be specified with certificate path");
Assert.state(StringUtils.hasText(directory),
"Docker host TLS verification requires trust material location to be specified with certificate path");
SSLContext sslContext = sslContextFactory.forDirectory(directory);
return new DefaultClientTlsStrategy(sslContext);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -27,7 +27,7 @@ import org.springframework.boot.buildpack.platform.docker.type.Layer;
import org.springframework.boot.buildpack.platform.json.AbstractJsonTests;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -86,7 +86,7 @@ class BuilderBuildpackTests extends AbstractJsonTests {
@Test
void resolveWhenFullyQualifiedBuildpackWithVersionNotInBuilderThrowsException() {
BuildpackReference reference = BuildpackReference.of("urn:cnb:builder:example/buildpack1@1.2.3");
assertThatIllegalArgumentException().isThrownBy(() -> BuilderBuildpack.resolve(this.resolverContext, reference))
assertThatIllegalStateException().isThrownBy(() -> BuilderBuildpack.resolve(this.resolverContext, reference))
.withMessageContaining("'urn:cnb:builder:example/buildpack1@1.2.3'")
.withMessageContaining("not found in builder");
}
@ -94,7 +94,7 @@ class BuilderBuildpackTests extends AbstractJsonTests {
@Test
void resolveWhenFullyQualifiedBuildpackWithoutVersionNotInBuilderThrowsException() {
BuildpackReference reference = BuildpackReference.of("urn:cnb:builder:example/buildpack1");
assertThatIllegalArgumentException().isThrownBy(() -> BuilderBuildpack.resolve(this.resolverContext, reference))
assertThatIllegalStateException().isThrownBy(() -> BuilderBuildpack.resolve(this.resolverContext, reference))
.withMessageContaining("'urn:cnb:builder:example/buildpack1'")
.withMessageContaining("not found in builder");
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -28,6 +28,7 @@ import org.springframework.boot.buildpack.platform.json.AbstractJsonTests;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -105,7 +106,7 @@ class BuilderMetadataTests extends AbstractJsonTests {
ImageConfig imageConfig = mock(ImageConfig.class);
given(image.getConfig()).willReturn(imageConfig);
given(imageConfig.getLabels()).willReturn(Collections.singletonMap("alpha", "a"));
assertThatIllegalArgumentException().isThrownBy(() -> BuilderMetadata.fromImage(image))
assertThatIllegalStateException().isThrownBy(() -> BuilderMetadata.fromImage(image))
.withMessage("No 'io.buildpacks.builder.metadata' label found in image config labels 'alpha'");
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -517,7 +517,7 @@ class BuilderTests {
Builder builder = new Builder(BuildLog.to(out), docker, null);
BuildpackReference reference = BuildpackReference.of("urn:cnb:builder:example/buildpack@1.2.3");
BuildRequest request = getTestRequest().withBuildpacks(reference);
assertThatIllegalArgumentException().isThrownBy(() -> builder.build(request))
assertThatIllegalStateException().isThrownBy(() -> builder.build(request))
.withMessageContaining("'urn:cnb:builder:example/buildpack@1.2.3'")
.withMessageContaining("not found in builder");
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -27,6 +27,7 @@ import org.springframework.boot.buildpack.platform.json.AbstractJsonTests;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -70,7 +71,7 @@ class BuildpackLayersMetadataTests extends AbstractJsonTests {
ImageConfig imageConfig = mock(ImageConfig.class);
given(image.getConfig()).willReturn(imageConfig);
given(imageConfig.getLabels()).willReturn(Collections.singletonMap("alpha", "a"));
assertThatIllegalArgumentException().isThrownBy(() -> BuildpackLayersMetadata.fromImage(image))
assertThatIllegalStateException().isThrownBy(() -> BuildpackLayersMetadata.fromImage(image))
.withMessage("No 'io.buildpacks.buildpack.layers' label found in image config labels 'alpha'");
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -27,6 +27,7 @@ import org.springframework.boot.buildpack.platform.json.AbstractJsonTests;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -64,7 +65,7 @@ class BuildpackMetadataTests extends AbstractJsonTests {
ImageConfig imageConfig = mock(ImageConfig.class);
given(image.getConfig()).willReturn(imageConfig);
given(imageConfig.getLabels()).willReturn(Collections.singletonMap("alpha", "a"));
assertThatIllegalArgumentException().isThrownBy(() -> BuildpackMetadata.fromImage(image))
assertThatIllegalStateException().isThrownBy(() -> BuildpackMetadata.fromImage(image))
.withMessage("No 'io.buildpacks.buildpackage.metadata' label found in image config labels 'alpha'");
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -37,7 +37,7 @@ import org.junit.jupiter.api.condition.OS;
import org.junit.jupiter.api.io.TempDir;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.Mockito.mock;
@ -89,8 +89,7 @@ class DirectoryBuildpackTests {
void resolveWhenDirectoryWithoutBuildpackTomlThrowsException() throws Exception {
Files.createDirectories(this.buildpackDir.toPath());
BuildpackReference reference = BuildpackReference.of(this.buildpackDir.toString());
assertThatIllegalArgumentException()
.isThrownBy(() -> DirectoryBuildpack.resolve(this.resolverContext, reference))
assertThatIllegalStateException().isThrownBy(() -> DirectoryBuildpack.resolve(this.resolverContext, reference))
.withMessageContaining("Buildpack descriptor 'buildpack.toml' is required")
.withMessageContaining(this.buildpackDir.getAbsolutePath());
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -43,6 +43,7 @@ import org.springframework.boot.buildpack.platform.json.AbstractJsonTests;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.ArgumentMatchers.any;
@ -156,7 +157,7 @@ class ImageBuildpackTests extends AbstractJsonTests {
BuildpackResolverContext resolverContext = mock(BuildpackResolverContext.class);
given(resolverContext.fetchImage(any(), any())).willReturn(image);
BuildpackReference reference = BuildpackReference.of("docker://example/buildpack1:latest");
assertThatIllegalArgumentException().isThrownBy(() -> ImageBuildpack.resolve(resolverContext, reference))
assertThatIllegalStateException().isThrownBy(() -> ImageBuildpack.resolve(resolverContext, reference))
.withMessageContaining("No 'io.buildpacks.buildpackage.metadata' label found");
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -28,7 +28,7 @@ import org.springframework.boot.buildpack.platform.docker.configuration.Resolved
import org.springframework.boot.buildpack.platform.docker.ssl.SslContextFactory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -92,7 +92,7 @@ class RemoteHttpClientTransportTests {
void createIfPossibleWhenTlsVerifyWithMissingCertPathThrowsException() {
ResolvedDockerHost dockerHost = ResolvedDockerHost
.from(DockerHostConfiguration.forAddress("tcp://192.168.1.2:2376", true, null));
assertThatIllegalArgumentException().isThrownBy(() -> RemoteHttpClientTransport.createIfPossible(dockerHost))
assertThatIllegalStateException().isThrownBy(() -> RemoteHttpClientTransport.createIfPossible(dockerHost))
.withMessageContaining("Docker host TLS verification requires trust material");
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -220,7 +220,7 @@ public class InitCommand extends OptionParsingCommand {
protected ProjectGenerationRequest createProjectGenerationRequest(OptionSet options) {
List<?> nonOptionArguments = new ArrayList<Object>(options.nonOptionArguments());
Assert.isTrue(nonOptionArguments.size() <= 1, "Only the target location may be specified");
Assert.state(nonOptionArguments.size() <= 1, "Only the target location may be specified");
ProjectGenerationRequest request = new ProjectGenerationRequest();
request.setServiceUrl(options.valueOf(this.target));
if (options.has(this.bootVersion)) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -128,13 +128,13 @@ class IndexedJarStructure implements JarStructure {
}
private String toStructureDependency(String libEntryName) {
Assert.state(libEntryName.startsWith(this.libLocation), "Invalid library location " + libEntryName);
Assert.state(libEntryName.startsWith(this.libLocation), () -> "Invalid library location " + libEntryName);
return libEntryName.substring(this.libLocation.length());
}
private static String getMandatoryAttribute(Manifest manifest, String attribute) {
String value = manifest.getMainAttributes().getValue(attribute);
Assert.state(value != null, "Manifest attribute '" + attribute + "' is mandatory");
Assert.state(value != null, () -> "Manifest attribute '" + attribute + "' is mandatory");
return value;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -60,7 +60,7 @@ class IndexedLayers implements Layers {
this.layers.put(line.substring(3, line.length() - 2), contents);
}
else if (line.startsWith(" - ")) {
Assert.notNull(contents, "Contents must not be null. Check if the index file is malformed!");
Assert.state(contents != null, "Contents must not be null. Check if the index file is malformed!");
contents.add(line.substring(5, line.length() - 1));
}
else {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -154,7 +154,7 @@ class PropertyMigration {
ConfigurationPropertyName oldName = property.getName();
ConfigurationPropertyName oldPrefix = ConfigurationPropertyName.of(metadata.getId());
Assert.state(oldPrefix.isAncestorOf(oldName),
String.format("'%s' is not an ancestor of '%s'", oldPrefix, oldName));
() -> "'%s' is not an ancestor of '%s'".formatted(oldPrefix, oldName));
ConfigurationPropertyName newPrefix = ConfigurationPropertyName.of(replacement.getId());
return newPrefix.append(oldName.subName(oldPrefix.getNumberOfElements()));
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -69,7 +69,7 @@ class DisabledIfProcessUnavailableCondition implements ExecutionCondition {
ProcessBuilder processBuilder = new ProcessBuilder(command);
try {
Process process = processBuilder.start();
Assert.isTrue(process.waitFor(30, TimeUnit.SECONDS), "Process did not exit within 30 seconds");
Assert.state(process.waitFor(30, TimeUnit.SECONDS), "Process did not exit within 30 seconds");
Assert.state(process.exitValue() == 0, () -> "Process exited with %d".formatted(process.exitValue()));
process.destroy();
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -410,7 +410,7 @@ public class SpringApplication {
if (!AotDetector.useGeneratedArtifacts()) {
// Load the sources
Set<Object> sources = getAllSources();
Assert.notEmpty(sources, "Sources must not be empty");
Assert.state(!ObjectUtils.isEmpty(sources), "No sources defined");
load(context, sources.toArray(new Object[0]));
}
listeners.contextLoaded(context);
@ -608,7 +608,7 @@ public class SpringApplication {
for (ApplicationContextInitializer initializer : getInitializers()) {
Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(initializer.getClass(),
ApplicationContextInitializer.class);
Assert.isInstanceOf(requiredType, context, "Unable to call initializer.");
Assert.state(requiredType.isInstance(context), "Unable to call initializer");
initializer.initialize(context);
}
}

View File

@ -65,7 +65,7 @@ public class SpringApplicationAotProcessor extends ContextAotProcessor {
public static void main(String[] args) throws Exception {
int requiredArgs = 6;
Assert.isTrue(args.length >= requiredArgs, () -> "Usage: " + SpringApplicationAotProcessor.class.getName()
Assert.state(args.length >= requiredArgs, () -> "Usage: " + SpringApplicationAotProcessor.class.getName()
+ " <applicationMainClass> <sourceOutput> <resourceOutput> <classOutput> <groupId> <artifactId> <originalArgs...>");
Class<?> application = Class.forName(args[0]);
Settings settings = Settings.builder()
@ -110,7 +110,7 @@ public class SpringApplicationAotProcessor extends ContextAotProcessor {
}
catch (AbandonedRunException ex) {
ApplicationContext context = ex.getApplicationContext();
Assert.isInstanceOf(GenericApplicationContext.class, context,
Assert.state(context instanceof GenericApplicationContext,
() -> "AOT processing requires a GenericApplicationContext but got a "
+ context.getClass().getName());
return (GenericApplicationContext) context;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -60,7 +60,7 @@ public class ConfigTreeConfigDataLocationResolver implements ConfigDataLocationR
}
private List<ConfigTreeConfigDataResource> resolve(String location) throws IOException {
Assert.isTrue(location.endsWith("/"),
Assert.state(location.endsWith("/"),
() -> String.format("Config tree location '%s' must end with '/'", location));
if (!this.resourceLoader.isPattern(location)) {
return Collections.singletonList(new ConfigTreeConfigDataResource(location));

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -91,7 +91,7 @@ public class BufferingApplicationStartup implements ApplicationStartup {
* already.
*/
public void startRecording() {
Assert.state(this.events.isEmpty(), "Cannot restart recording once steps have been buffered.");
Assert.state(this.events.isEmpty(), "Cannot restart recording once steps have been buffered");
this.startTime = this.clock.instant();
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -264,7 +264,7 @@ public enum PeriodStyle {
}
private int intValue(Period value) {
Assert.notNull(this.intValue, () -> "intValue cannot be extracted from " + name());
Assert.state(this.intValue != null, () -> "intValue cannot be extracted from " + name());
return this.intValue.apply(value);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -195,11 +195,11 @@ public class RandomValuePropertySource extends PropertySource<Random> {
String[] tokens = StringUtils.commaDelimitedListToStringArray(value);
T min = parse.apply(tokens[0]);
if (tokens.length == 1) {
Assert.isTrue(min.compareTo(zero) > 0, "Bound must be positive.");
Assert.state(min.compareTo(zero) > 0, "Bound must be positive.");
return new Range<>(value, zero, min);
}
T max = parse.apply(tokens[1]);
Assert.isTrue(min.compareTo(max) < 0, "Lower bound must be less than upper bound.");
Assert.state(min.compareTo(max) < 0, "Lower bound must be less than upper bound.");
return new Range<>(value, min, max);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -61,9 +61,9 @@ public class HikariCheckpointRestoreLifecycle implements Lifecycle {
static {
Field closeConnectionExecutor = ReflectionUtils.findField(HikariPool.class, "closeConnectionExecutor");
Assert.notNull(closeConnectionExecutor, "Unable to locate closeConnectionExecutor for HikariPool");
Assert.isAssignable(ThreadPoolExecutor.class, closeConnectionExecutor.getType(),
"Expected ThreadPoolExecutor for closeConnectionExecutor but found %s"
Assert.state(closeConnectionExecutor != null, "Unable to locate closeConnectionExecutor for HikariPool");
Assert.state(ThreadPoolExecutor.class.isAssignableFrom(closeConnectionExecutor.getType()),
() -> "Expected ThreadPoolExecutor for closeConnectionExecutor but found %s"
.formatted(closeConnectionExecutor.getType()));
ReflectionUtils.makeAccessible(closeConnectionExecutor);
CLOSE_CONNECTION_EXECUTOR = closeConnectionExecutor;
@ -104,7 +104,7 @@ public class HikariCheckpointRestoreLifecycle implements Lifecycle {
this.hasOpenConnections = (pool) -> {
ThreadPoolExecutor closeConnectionExecutor = (ThreadPoolExecutor) ReflectionUtils
.getField(CLOSE_CONNECTION_EXECUTOR, pool);
Assert.notNull(closeConnectionExecutor, "CloseConnectionExecutor was null");
Assert.state(closeConnectionExecutor != null, "'closeConnectionExecutor' was null");
return closeConnectionExecutor.getActiveCount() > 0;
};
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -184,7 +184,7 @@ class JsonValueWriter {
<E> void writeElement(E element) {
ActiveSeries activeSeries = this.activeSeries.peek();
Assert.notNull(activeSeries, "No series has been started");
Assert.state(activeSeries != null, "No series has been started");
this.path = activeSeries.updatePath(this.path);
activeSeries.incrementIndexAndAddCommaIfRequired();
write(element);
@ -223,7 +223,7 @@ class JsonValueWriter {
if (!isFilteredPath()) {
String processedName = processName(name.toString());
ActiveSeries activeSeries = this.activeSeries.peek();
Assert.notNull(activeSeries, "No series has been started");
Assert.state(activeSeries != null, "No series has been started");
activeSeries.incrementIndexAndAddCommaIfRequired();
Assert.state(activeSeries.addName(processedName),
() -> "The name '" + processedName + "' has already been written");

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -190,7 +190,7 @@ public final class LoggerConfiguration {
* @throws IllegalStateException if this is a {@link #isCustom() custom} level
*/
public LogLevel getLevel() {
Assert.state(this.logLevel != null, "Unable to provide LogLevel for '" + this.name + "'");
Assert.state(this.logLevel != null, () -> "Unable to provide LogLevel for '" + this.name + "'");
return this.logLevel;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -409,7 +409,7 @@ public class LogbackLoggingSystem extends AbstractLoggingSystem implements BeanF
private LoggerContext getLoggerContext() {
ILoggerFactory factory = getLoggerFactory();
Assert.isInstanceOf(LoggerContext.class, factory,
Assert.state(factory instanceof LoggerContext,
() -> String.format(
"LoggerFactory is not a Logback LoggerContext but Logback is on "
+ "the classpath. Either remove Logback or the competing "

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -147,7 +147,7 @@ public class StructuredLogFormatterFactory<E> {
private void checkTypeArgument(Object formatter) {
Class<?> typeArgument = GenericTypeResolver.resolveTypeArgument(formatter.getClass(),
StructuredLogFormatter.class);
Assert.isTrue(this.logEventType.equals(typeArgument),
Assert.state(this.logEventType.equals(typeArgument),
() -> "Type argument of %s must be %s but was %s".formatted(formatter.getClass().getName(),
this.logEventType.getName(), (typeArgument != null) ? typeArgument.getName() : "null"));

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -99,7 +99,7 @@ public enum EmbeddedDatabaseConnection {
*/
public static boolean isEmbedded(ConnectionFactory connectionFactory) {
OptionsCapableConnectionFactory optionsCapable = OptionsCapableConnectionFactory.unwrapFrom(connectionFactory);
Assert.notNull(optionsCapable,
Assert.state(optionsCapable != null,
() -> "Cannot determine database's type as ConnectionFactory is not options-capable. To be "
+ "options-capable, a ConnectionFactory should be created with "
+ ConnectionFactoryBuilder.class.getName());

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -445,7 +445,7 @@ final class PemPrivateKeyParser {
public static final String PBES2_ALGORITHM = "PBES2";
static PKCS8EncodedKeySpec decrypt(byte[] bytes, String password) {
Assert.notNull(password, "Password is required for an encrypted private key");
Assert.state(password != null, "Password is required for an encrypted private key");
try {
EncryptedPrivateKeyInfo keyInfo = new EncryptedPrivateKeyInfo(bytes);
AlgorithmParameters algorithmParameters = keyInfo.getAlgParameters();

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -29,6 +29,7 @@ import java.util.function.Supplier;
import org.springframework.boot.ssl.SslStoreBundle;
import org.springframework.core.style.ToStringCreator;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.util.function.SingletonSupplier;
@ -89,7 +90,7 @@ public class PemSslStoreBundle implements SslStoreBundle {
}
try {
List<X509Certificate> certificates = pemSslStore.certificates();
Assert.notEmpty(certificates, "Certificates must not be empty");
Assert.state(!ObjectUtils.isEmpty(certificates), "Certificates must not be empty");
String alias = (pemSslStore.alias() != null) ? pemSslStore.alias() : DEFAULT_ALIAS;
KeyStore store = createKeyStore(pemSslStore.type());
PrivateKey privateKey = pemSslStore.privateKey();

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -182,7 +182,7 @@ public class Instantiator<T> {
public <A> A getArg(Class<A> type) {
Assert.notNull(type, "'type' must not be null");
Function<Class<?>, Object> parameter = getAvailableParameter(type);
Assert.isTrue(parameter != null, "Unknown argument type " + type.getName());
Assert.state(parameter != null, "Unknown argument type " + type.getName());
return (A) parameter.apply(this.type);
}
@ -193,7 +193,7 @@ public class Instantiator<T> {
private T instantiate(TypeSupplier typeSupplier) {
try {
Class<?> type = typeSupplier.get();
Assert.isAssignable(this.type, type);
Assert.state(this.type.isAssignableFrom(type), () -> type + " is not assignable to " + this.type);
return instantiate(type);
}
catch (Throwable ex) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -162,7 +162,7 @@ public class NettyWebServer implements WebServer {
}
if (this.resourceFactory != null) {
LoopResources resources = this.resourceFactory.getLoopResources();
Assert.notNull(resources, "No LoopResources: is ReactorResourceFactory not initialized yet?");
Assert.state(resources != null, "No LoopResources: is ReactorResourceFactory not initialized yet?");
server = server.runOn(resources);
}
if (this.lifecycleTimeout != null) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -175,7 +175,7 @@ public class UndertowWebServer implements WebServer {
this.closeables.add(closeable);
}
if (handler instanceof GracefulShutdownHandler shutdownHandler) {
Assert.isNull(this.gracefulShutdown, "Only a single GracefulShutdownHandler can be defined");
Assert.state(this.gracefulShutdown == null, "Only a single GracefulShutdownHandler can be defined");
this.gracefulShutdown = shutdownHandler;
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -95,8 +95,9 @@ public class DelegatingFilterProxyRegistrationBean extends AbstractFilterRegistr
}
private WebApplicationContext getWebApplicationContext() {
Assert.notNull(this.applicationContext, "ApplicationContext be injected");
Assert.isInstanceOf(WebApplicationContext.class, this.applicationContext);
Assert.state(this.applicationContext != null, "ApplicationContext has not been injected");
Assert.state(this.applicationContext instanceof WebApplicationContext,
"Injected ApplicationContext is not a WebApplicationContext");
return (WebApplicationContext) this.applicationContext;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -52,7 +52,7 @@ abstract class ServletComponentHandler {
String[] value = (String[]) attributes.get("value");
String[] urlPatterns = (String[]) attributes.get("urlPatterns");
if (urlPatterns.length > 0) {
Assert.state(value.length == 0, "The urlPatterns and value attributes are mutually exclusive.");
Assert.state(value.length == 0, "The urlPatterns and value attributes are mutually exclusive");
return urlPatterns;
}
return value;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -168,7 +168,7 @@ public class ServletRegistrationBean<T extends Servlet> extends DynamicRegistrat
@Override
protected String getDescription() {
Assert.notNull(this.servlet, "Servlet must not be null");
Assert.state(this.servlet != null, "Unable to return description for null servlet");
return "servlet " + getServletName();
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -30,7 +30,7 @@ import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* Tests for {@link SpringApplication} main method.
@ -45,7 +45,7 @@ class SimpleMainTests {
@Test
void emptyApplicationContext() {
assertThatIllegalArgumentException().isThrownBy(() -> SpringApplication.main(getArgs()));
assertThatIllegalStateException().isThrownBy(() -> SpringApplication.main(getArgs()));
}
@Test

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -26,7 +26,6 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.aot.AbstractAotProcessor.Settings;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
@ -84,8 +83,7 @@ class SpringApplicationAotProcessorTests {
@Test
void invokeMainWithMissingArguments() {
assertThatIllegalArgumentException()
.isThrownBy(() -> SpringApplicationAotProcessor.main(new String[] { "Test" }))
assertThatIllegalStateException().isThrownBy(() -> SpringApplicationAotProcessor.main(new String[] { "Test" }))
.withMessageContaining("Usage:");
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -213,8 +213,8 @@ class SpringApplicationTests {
@Test
void sourcesMustNotBeEmpty() {
assertThatIllegalArgumentException().isThrownBy(() -> new SpringApplication().run())
.withMessageContaining("Sources must not be empty");
assertThatIllegalStateException().isThrownBy(() -> new SpringApplication().run())
.withMessageContaining("No sources defined");
}
@Test

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -88,7 +88,7 @@ class BufferingApplicationStartupTests {
BufferingApplicationStartup applicationStartup = new BufferingApplicationStartup(2);
applicationStartup.start("first").end();
assertThatIllegalStateException().isThrownBy(applicationStartup::startRecording)
.withMessage("Cannot restart recording once steps have been buffered.");
.withMessage("Cannot restart recording once steps have been buffered");
}
@Test

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -28,7 +28,7 @@ import org.springframework.core.env.SystemEnvironmentPropertySource;
import org.springframework.mock.env.MockEnvironment;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.spy;
@ -76,7 +76,7 @@ class RandomValuePropertySourceTests {
@Test
void intRangeWhenLowerBoundEqualsUpperBoundShouldFailWithIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.source.getProperty("random.int[4,4]"))
assertThatIllegalStateException().isThrownBy(() -> this.source.getProperty("random.int[4,4]"))
.withMessage("Lower bound must be less than upper bound.");
}
@ -95,13 +95,13 @@ class RandomValuePropertySourceTests {
@Test
void intMaxZero() {
assertThatIllegalArgumentException().isThrownBy(() -> this.source.getProperty("random.int(0)"))
assertThatIllegalStateException().isThrownBy(() -> this.source.getProperty("random.int(0)"))
.withMessage("Bound must be positive.");
}
@Test
void intNegativeBound() {
assertThatIllegalArgumentException().isThrownBy(() -> this.source.getProperty("random.int(-5)"))
assertThatIllegalStateException().isThrownBy(() -> this.source.getProperty("random.int(-5)"))
.withMessage("Bound must be positive.");
}
@ -119,7 +119,7 @@ class RandomValuePropertySourceTests {
@Test
void longRangeWhenLowerBoundEqualsUpperBoundShouldFailWithIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.source.getProperty("random.long[4,4]"))
assertThatIllegalStateException().isThrownBy(() -> this.source.getProperty("random.long[4,4]"))
.withMessage("Lower bound must be less than upper bound.");
}
@ -138,13 +138,13 @@ class RandomValuePropertySourceTests {
@Test
void longMaxZero() {
assertThatIllegalArgumentException().isThrownBy(() -> this.source.getProperty("random.long(0)"))
assertThatIllegalStateException().isThrownBy(() -> this.source.getProperty("random.long(0)"))
.withMessage("Bound must be positive.");
}
@Test
void longNegativeBound() {
assertThatIllegalArgumentException().isThrownBy(() -> this.source.getProperty("random.long(-5)"))
assertThatIllegalStateException().isThrownBy(() -> this.source.getProperty("random.long(-5)"))
.withMessage("Bound must be positive.");
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -33,6 +33,7 @@ import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* Tests for {@link StructuredLogLayout}.
@ -93,14 +94,14 @@ class StructuredLoggingLayoutTests extends AbstractStructuredLoggingTests {
@Test
void shouldCheckTypeArgument() {
assertThatIllegalArgumentException().isThrownBy(
assertThatIllegalStateException().isThrownBy(
() -> newBuilder().setFormat(CustomLog4j2StructuredLoggingFormatterWrongType.class.getName()).build())
.withMessageContaining("must be org.apache.logging.log4j.core.LogEvent but was java.lang.String");
}
@Test
void shouldCheckTypeArgumentWithRawType() {
assertThatIllegalArgumentException()
assertThatIllegalStateException()
.isThrownBy(
() -> newBuilder().setFormat(CustomLog4j2StructuredLoggingFormatterRawType.class.getName()).build())
.withMessageContaining("must be org.apache.logging.log4j.core.LogEvent but was null");

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -35,6 +35,7 @@ import org.springframework.mock.env.MockEnvironment;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* Tests for {@link StructuredLogEncoder}.
@ -113,7 +114,7 @@ class StructuredLogEncoderTests extends AbstractStructuredLoggingTests {
@Test
void shouldCheckTypeArgument() {
assertThatIllegalArgumentException().isThrownBy(() -> {
assertThatIllegalStateException().isThrownBy(() -> {
this.encoder.setFormat(CustomLogbackStructuredLoggingFormatterWrongType.class.getName());
this.encoder.start();
}).withMessageContaining("must be ch.qos.logback.classic.spi.ILoggingEvent but was java.lang.String");
@ -121,7 +122,7 @@ class StructuredLogEncoderTests extends AbstractStructuredLoggingTests {
@Test
void shouldCheckTypeArgumentWithRawType() {
assertThatIllegalArgumentException().isThrownBy(() -> {
assertThatIllegalStateException().isThrownBy(() -> {
this.encoder.setFormat(CustomLogbackStructuredLoggingFormatterRawType.class.getName());
this.encoder.start();
}).withMessageContaining("must be ch.qos.logback.classic.spi.ILoggingEvent but was null");
@ -133,8 +134,8 @@ class StructuredLogEncoderTests extends AbstractStructuredLoggingTests {
this.encoder.setFormat("does-not-exist");
this.encoder.start();
})
.withMessageContaining(
"Unknown format 'does-not-exist'. Values can be a valid fully-qualified class name or one of the common formats: [ecs, gelf, logstash]");
.withMessageContaining("Unknown format 'does-not-exist'. Values can be a valid fully-qualified "
+ "class name or one of the common formats: [ecs, gelf, logstash]");
}
private String encode(LoggingEvent event) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -31,6 +31,7 @@ import org.springframework.mock.env.MockEnvironment;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -83,7 +84,7 @@ class StructuredLogFormatterFactoryTests {
@Test
void getUsingClassNameWhenHasGenericMismatch() {
assertThatIllegalArgumentException().isThrownBy(() -> this.factory.get(DifferentFormatter.class.getName()))
assertThatIllegalStateException().isThrownBy(() -> this.factory.get(DifferentFormatter.class.getName()))
.withMessage("Type argument of org.springframework.boot.logging.structured."
+ "StructuredLogFormatterFactoryTests$DifferentFormatter "
+ "must be org.springframework.boot.logging.structured."

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -29,7 +29,7 @@ import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* Tests for {@link EmbeddedDatabaseConnection}.
@ -85,7 +85,7 @@ class EmbeddedDatabaseConnectionTests {
@Test
void whenConnectionFactoryIsNotOptionsCapableThenIsEmbeddedThrows() {
assertThatIllegalArgumentException()
assertThatIllegalStateException()
.isThrownBy(() -> EmbeddedDatabaseConnection
.isEmbedded(ConnectionFactories.get("r2dbc:pool:h2:mem:///" + UUID.randomUUID())))
.withMessage("Cannot determine database's type as ConnectionFactory is not options-capable. To be "

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -140,7 +140,7 @@ class InstantiatorTests {
@Test
void getArgWhenUnknownThrowsException() {
Instantiator<?> instantiator = createInstantiator(WithMultipleConstructors.class);
assertThatIllegalArgumentException().isThrownBy(() -> instantiator.getArg(InputStream.class))
assertThatIllegalStateException().isThrownBy(() -> instantiator.getArg(InputStream.class))
.withMessageStartingWith("Unknown argument type");
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2024 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -135,8 +135,8 @@ class ServletRegistrationBeanTests {
@Test
void setServletMustNotBeNull() {
ServletRegistrationBean<MockServlet> bean = new ServletRegistrationBean<>();
assertThatIllegalArgumentException().isThrownBy(() -> bean.onStartup(this.servletContext))
.withMessageContaining("Servlet must not be null");
assertThatIllegalStateException().isThrownBy(() -> bean.onStartup(this.servletContext))
.withMessageContaining("Unable to return description for null servlet");
}
@Test

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -130,7 +130,7 @@ class WebFilterHandlerTests {
void urlPatternsDeclaredTwice() {
assertThatIllegalStateException()
.isThrownBy(() -> handleBeanDefinitionForClass(UrlPatternsDeclaredTwiceFilter.class))
.withMessageContaining("The urlPatterns and value attributes are mutually exclusive.");
.withMessageContaining("The urlPatterns and value attributes are mutually exclusive");
}
private AnnotatedBeanDefinition createBeanDefinition(Class<?> filterClass) throws IOException {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -105,7 +105,7 @@ class WebServletHandlerTests {
void urlPatternsDeclaredTwice() {
assertThatIllegalStateException()
.isThrownBy(() -> handleBeanDefinitionForClass(UrlPatternsDeclaredTwiceServlet.class))
.withMessageContaining("The urlPatterns and value attributes are mutually exclusive.");
.withMessageContaining("The urlPatterns and value attributes are mutually exclusive");
}
private AnnotatedBeanDefinition createBeanDefinition(Class<?> servletClass) throws IOException {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -40,7 +40,7 @@ public class GradleBuildInjectionExtension implements BeforeEachCallback {
this.gradleBuild = new GradleBuild();
this.gradleBuild.gradleVersion(GradleVersions.minimumCompatible());
String bootVersion = System.getProperty("springBootVersion");
Assert.notNull(bootVersion, "Property 'springBootVersion' must be set in build environment");
Assert.state(bootVersion != null, "Property 'springBootVersion' must be set in build environment");
this.gradleBuild.bootVersion(bootVersion);
}