Skip to content

Commit

Permalink
Change relevant Assert calls to throw IllegalStateException
Browse files Browse the repository at this point in the history
Change certain Assert class from `assert...` to `assertState`
so that a more appropriate `IllegalStateException` is thrown.

Fixes spring-projectsgh-43779
  • Loading branch information
philwebb committed Jan 12, 2025
1 parent 29baaf3 commit f08188d
Show file tree
Hide file tree
Showing 76 changed files with 201 additions and 188 deletions.
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -69,7 +69,7 @@ private <S extends AvailabilityState> void assertAllEnumsMapped(Class<S> stateTy
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);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -209,7 +209,7 @@ private OpenJ9DiagnosticsMXBeanHeapDumper() {

@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));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -28,6 +28,7 @@

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;

/**
Expand Down Expand Up @@ -67,7 +68,7 @@ void createWhenStatusMappingIsNullThrowsException() {

@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");
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -57,6 +57,7 @@
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;

/**
Expand Down Expand Up @@ -170,7 +171,7 @@ protected boolean isEnabled(AnnotationMetadata metadata) {
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;
}
Expand All @@ -195,7 +196,7 @@ protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, A
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.");
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -112,10 +112,10 @@ public JobLauncherApplicationRunner(JobLauncher jobLauncher, JobExplorer jobExpl

@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 + "'");
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -102,7 +102,7 @@ static class CacheManagerValidator implements InitializingBean {

@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() + "')");
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -250,8 +250,8 @@ private ConfigurableListableBeanFactory getSearchBeanFactory(Spec<?> spec) {
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;
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -45,7 +45,7 @@ public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeM
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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -583,7 +583,7 @@ static class Extension<E extends ConfigurationExtension> {
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;
});
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -52,7 +52,7 @@ public Resource resolveConfigLocation() {
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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ private void configurePropertyNamingStrategyField(Jackson2ObjectMapperBuilder bu
// 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));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -96,7 +96,8 @@ private XADataSource createXaDataSourceInstance(String className) {
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) {
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -175,8 +175,8 @@ private RSAPrivateKey readPrivateKey(Resource location) {
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) {
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -127,7 +127,7 @@ private static PemSslStore getPemSslStore(String propertyName, PemSslBundlePrope
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;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -91,7 +91,7 @@

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;

Expand Down Expand Up @@ -484,15 +484,15 @@ void whenTheUserDefinesAJobNameThatDoesNotExistWithJobInstancesFailsFast() {
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'");
}

@Test
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'");
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -272,7 +272,7 @@ protected void start(FailureHandler failureHandler) throws Exception {
}

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);
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -97,7 +97,8 @@ private Map<ContainerPort, Integer> buildMappingsForHostNetworking(Config config
@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;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -102,7 +102,7 @@ public List<RunningService> getRunningServices() {
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);
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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();
}

Expand Down Expand Up @@ -112,7 +112,7 @@ public static DockerComposeFile find(File workingDirectory) {
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);
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -27,6 +27,7 @@

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}.
Expand Down Expand Up @@ -104,7 +105,7 @@ void findWhenWorkingDirectoryDoesNotExistReturnsNull() {
@Test
void findWhenWorkingDirectoryIsNotDirectoryThrowsException() throws Exception {
File file = createTempFile("iamafile");
assertThatIllegalArgumentException().isThrownBy(() -> DockerComposeFile.find(file))
assertThatIllegalStateException().isThrownBy(() -> DockerComposeFile.find(file))
.withMessageEndingWith("is not a directory");
}

Expand Down
Loading

0 comments on commit f08188d

Please sign in to comment.