Use AutoClosables with try-with-resources

Closes gh-33538
pull/33545/head
Moritz Halbritter 2 years ago
parent 725337f976
commit f36e2ecb7b

@ -34,6 +34,7 @@ import java.util.function.Predicate;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
@ -68,8 +69,10 @@ public class CheckClasspathForConflicts extends DefaultTask {
for (File file : this.classpath) {
if (file.isDirectory()) {
Path root = file.toPath();
Files.walk(root).filter(Files::isRegularFile)
.forEach((entry) -> classpathContents.add(root.relativize(entry).toString(), root.toString()));
try (Stream<Path> pathStream = Files.walk(root)) {
pathStream.filter(Files::isRegularFile).forEach(
(entry) -> classpathContents.add(root.relativize(entry).toString(), root.toString()));
}
}
else {
try (JarFile jar = new JarFile(file)) {

@ -178,11 +178,15 @@ class RabbitAutoConfigurationTests {
com.rabbitmq.client.ConnectionFactory rcf = mock(com.rabbitmq.client.ConnectionFactory.class);
given(rcf.newConnection(isNull(), eq(addresses), anyString())).willReturn(mock(Connection.class));
ReflectionTestUtils.setField(connectionFactory, "rabbitConnectionFactory", rcf);
connectionFactory.createConnection();
then(rcf).should().newConnection(isNull(), eq(addresses), eq("test#0"));
try (org.springframework.amqp.rabbit.connection.Connection connection = connectionFactory
.createConnection()) {
then(rcf).should().newConnection(isNull(), eq(addresses), eq("test#0"));
}
connectionFactory.resetConnection();
connectionFactory.createConnection();
then(rcf).should().newConnection(isNull(), eq(addresses), eq("test#1"));
try (org.springframework.amqp.rabbit.connection.Connection connection = connectionFactory
.createConnection()) {
then(rcf).should().newConnection(isNull(), eq(addresses), eq("test#1"));
}
});
}

@ -205,8 +205,9 @@ class MultipartAutoConfigurationTests {
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
ClientHttpRequest request = requestFactory.createRequest(
new URI("http://localhost:" + this.context.getWebServer().getPort() + "/"), HttpMethod.GET);
ClientHttpResponse response = request.execute();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
try (ClientHttpResponse response = request.execute()) {
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
}
}
private void verifyServletWorks() {

@ -111,7 +111,7 @@ public class DevToolsDataSourceAutoConfiguration {
DERBY(null, new HashSet<>(Arrays.asList("org.apache.derby.jdbc.EmbeddedDriver")), (dataSource) -> {
String url = dataSource.getConnection().getMetaData().getURL();
try {
new EmbeddedDriver().connect(url + ";drop=true", new Properties());
new EmbeddedDriver().connect(url + ";drop=true", new Properties()).close();
}
catch (SQLException ex) {
if (!"08006".equals(ex.getSQLState())) {

@ -110,10 +110,11 @@ public class ClassPathChangeUploader implements ApplicationListener<ClassPathCha
headers.setContentLength(bytes.length);
FileCopyUtils.copy(bytes, request.getBody());
logUpload(event);
ClientHttpResponse response = request.execute();
HttpStatusCode statusCode = response.getStatusCode();
Assert.state(statusCode == HttpStatus.OK,
() -> "Unexpected " + statusCode + " response uploading class files");
try (ClientHttpResponse response = request.execute()) {
HttpStatusCode statusCode = response.getStatusCode();
Assert.state(statusCode == HttpStatus.OK,
() -> "Unexpected " + statusCode + " response uploading class files");
}
return;
}
catch (SocketException ex) {

@ -103,8 +103,9 @@ class DelayedLiveReloadTrigger implements Runnable {
private boolean isUp() {
try {
ClientHttpRequest request = createRequest();
ClientHttpResponse response = request.execute();
return response.getStatusCode() == HttpStatus.OK;
try (ClientHttpResponse response = request.execute()) {
return response.getStatusCode() == HttpStatus.OK;
}
}
catch (Exception ex) {
return false;

@ -139,9 +139,10 @@ class HttpTunnelConnectionTests {
@Test
void connectFailureLogsWarning(CapturedOutput output) throws Exception {
this.requestFactory.willRespond(new ConnectException());
TunnelChannel tunnel = openTunnel(true);
assertThat(tunnel.isOpen()).isFalse();
assertThat(output).contains("Failed to connect to remote application at http://localhost:12345");
try (TunnelChannel tunnel = openTunnel(true)) {
assertThat(tunnel.isOpen()).isFalse();
assertThat(output).contains("Failed to connect to remote application at http://localhost:12345");
}
}
private void write(TunnelChannel channel, String string) throws IOException {

@ -53,34 +53,37 @@ class SocketTargetServerConnectionTests {
void readData() throws Exception {
this.server.willSend("hello".getBytes());
this.server.start();
ByteChannel channel = this.connection.open(DEFAULT_TIMEOUT);
ByteBuffer buffer = ByteBuffer.allocate(5);
channel.read(buffer);
assertThat(buffer.array()).isEqualTo("hello".getBytes());
try (ByteChannel channel = this.connection.open(DEFAULT_TIMEOUT)) {
ByteBuffer buffer = ByteBuffer.allocate(5);
channel.read(buffer);
assertThat(buffer.array()).isEqualTo("hello".getBytes());
}
}
@Test
void writeData() throws Exception {
this.server.expect("hello".getBytes());
this.server.start();
ByteChannel channel = this.connection.open(DEFAULT_TIMEOUT);
ByteBuffer buffer = ByteBuffer.wrap("hello".getBytes());
channel.write(buffer);
this.server.closeAndVerify();
try (ByteChannel channel = this.connection.open(DEFAULT_TIMEOUT)) {
ByteBuffer buffer = ByteBuffer.wrap("hello".getBytes());
channel.write(buffer);
this.server.closeAndVerify();
}
}
@Test
void timeout() throws Exception {
this.server.delay(1000);
this.server.start();
ByteChannel channel = this.connection.open(10);
long startTime = System.currentTimeMillis();
assertThatExceptionOfType(SocketTimeoutException.class).isThrownBy(() -> channel.read(ByteBuffer.allocate(5)))
.satisfies((ex) -> {
long runTime = System.currentTimeMillis() - startTime;
assertThat(runTime).isGreaterThanOrEqualTo(10L);
assertThat(runTime).isLessThan(10000L);
});
try (ByteChannel channel = this.connection.open(10)) {
long startTime = System.currentTimeMillis();
assertThatExceptionOfType(SocketTimeoutException.class)
.isThrownBy(() -> channel.read(ByteBuffer.allocate(5))).satisfies((ex) -> {
long runTime = System.currentTimeMillis() - startTime;
assertThat(runTime).isGreaterThanOrEqualTo(10L);
assertThat(runTime).isLessThan(10000L);
});
}
}
static class MockServer {

@ -57,35 +57,43 @@ class BuildpackCoordinatesTests extends AbstractJsonTests {
}
@Test
void fromTomlWhenMissingIDThrowsException() {
InputStream coordinates = createTomlStream(null, null, true, false);
assertThatIllegalArgumentException().isThrownBy(() -> BuildpackCoordinates.fromToml(coordinates, this.archive))
.withMessageContaining("Buildpack descriptor must contain ID")
.withMessageContaining(this.archive.toString());
void fromTomlWhenMissingIDThrowsException() throws IOException {
try (InputStream coordinates = createTomlStream(null, null, true, false)) {
assertThatIllegalArgumentException()
.isThrownBy(() -> BuildpackCoordinates.fromToml(coordinates, this.archive))
.withMessageContaining("Buildpack descriptor must contain ID")
.withMessageContaining(this.archive.toString());
}
}
@Test
void fromTomlWhenMissingVersionThrowsException() {
InputStream coordinates = createTomlStream("example/buildpack1", null, true, false);
assertThatIllegalArgumentException().isThrownBy(() -> BuildpackCoordinates.fromToml(coordinates, this.archive))
.withMessageContaining("Buildpack descriptor must contain version")
.withMessageContaining(this.archive.toString());
void fromTomlWhenMissingVersionThrowsException() throws IOException {
try (InputStream coordinates = createTomlStream("example/buildpack1", null, true, false)) {
assertThatIllegalArgumentException()
.isThrownBy(() -> BuildpackCoordinates.fromToml(coordinates, this.archive))
.withMessageContaining("Buildpack descriptor must contain version")
.withMessageContaining(this.archive.toString());
}
}
@Test
void fromTomlWhenMissingStacksAndOrderThrowsException() {
InputStream coordinates = createTomlStream("example/buildpack1", "0.0.1", false, false);
assertThatIllegalArgumentException().isThrownBy(() -> BuildpackCoordinates.fromToml(coordinates, this.archive))
.withMessageContaining("Buildpack descriptor must contain either 'stacks' or 'order'")
.withMessageContaining(this.archive.toString());
void fromTomlWhenMissingStacksAndOrderThrowsException() throws IOException {
try (InputStream coordinates = createTomlStream("example/buildpack1", "0.0.1", false, false)) {
assertThatIllegalArgumentException()
.isThrownBy(() -> BuildpackCoordinates.fromToml(coordinates, this.archive))
.withMessageContaining("Buildpack descriptor must contain either 'stacks' or 'order'")
.withMessageContaining(this.archive.toString());
}
}
@Test
void fromTomlWhenContainsBothStacksAndOrderThrowsException() {
InputStream coordinates = createTomlStream("example/buildpack1", "0.0.1", true, true);
assertThatIllegalArgumentException().isThrownBy(() -> BuildpackCoordinates.fromToml(coordinates, this.archive))
.withMessageContaining("Buildpack descriptor must not contain both 'stacks' and 'order'")
.withMessageContaining(this.archive.toString());
void fromTomlWhenContainsBothStacksAndOrderThrowsException() throws IOException {
try (InputStream coordinates = createTomlStream("example/buildpack1", "0.0.1", true, true)) {
assertThatIllegalArgumentException()
.isThrownBy(() -> BuildpackCoordinates.fromToml(coordinates, this.archive))
.withMessageContaining("Buildpack descriptor must not contain both 'stacks' and 'order'")
.withMessageContaining(this.archive.toString());
}
}
@Test

@ -585,8 +585,12 @@ abstract class AbstractBootArchiveIntegrationTests {
for (String layerName : layerNames) {
File layer = new File(root, layerName);
assertThat(layer).isDirectory();
extractedLayers.put(layerName, Files.walk(layer.toPath()).filter((path) -> path.toFile().isFile())
.map(layer.toPath()::relativize).map(Path::toString).map(StringUtils::cleanPath).toList());
List<String> files;
try (Stream<Path> pathStream = Files.walk(layer.toPath())) {
files = pathStream.filter((path) -> path.toFile().isFile()).map(layer.toPath()::relativize)
.map(Path::toString).map(StringUtils::cleanPath).toList();
}
extractedLayers.put(layerName, files);
}
return extractedLayers;
}

@ -294,9 +294,10 @@ class JarFileTests {
void getEntryUrlStream() throws Exception {
URL url = new URL(this.jarFile.getUrl(), "1.dat");
url.openConnection();
InputStream stream = url.openStream();
assertThat(stream.read()).isEqualTo(1);
assertThat(stream.read()).isEqualTo(-1);
try (InputStream stream = url.openStream()) {
assertThat(stream.read()).isEqualTo(1);
assertThat(stream.read()).isEqualTo(-1);
}
}
@Test

@ -20,6 +20,7 @@ import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.TestTemplate;
@ -173,10 +174,10 @@ public class AotTests {
});
}
Stream<Path> collectRelativePaths(Path sourceDirectory) {
try {
return Files.walk(sourceDirectory).filter(Files::isRegularFile)
.map((path) -> path.subpath(sourceDirectory.getNameCount(), path.getNameCount()));
List<Path> collectRelativePaths(Path sourceDirectory) {
try (Stream<Path> pathStream = Files.walk(sourceDirectory)) {
return pathStream.filter(Files::isRegularFile)
.map((path) -> path.subpath(sourceDirectory.getNameCount(), path.getNameCount())).toList();
}
catch (IOException ex) {
throw new IllegalStateException(ex);

@ -47,6 +47,8 @@ class MavenBuildExtension implements TestTemplateInvocationContextProvider {
@Override
public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContexts(ExtensionContext context) {
try {
// Returning a stream which must be closed here is fine, as JUnit will take
// care of closing it
return Files.list(Paths.get("build/maven-binaries")).map(MavenVersionTestTemplateInvocationContext::new);
}
catch (IOException ex) {

@ -28,6 +28,7 @@ import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Stream;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticListener;
@ -124,7 +125,10 @@ public abstract class AbstractAotMojo extends AbstractDependencyFilterMojo {
protected final void compileSourceFiles(URL[] classPath, File sourcesDirectory, File outputDirectory)
throws Exception {
List<Path> sourceFiles = Files.walk(sourcesDirectory.toPath()).filter(Files::isRegularFile).toList();
List<Path> sourceFiles;
try (Stream<Path> pathStream = Files.walk(sourcesDirectory.toPath())) {
sourceFiles = pathStream.filter(Files::isRegularFile).toList();
}
if (sourceFiles.isEmpty()) {
return;
}
@ -167,8 +171,13 @@ public abstract class AbstractAotMojo extends AbstractDependencyFilterMojo {
}
protected final void copyAll(Path from, Path to) throws IOException {
List<Path> files = (Files.exists(from)) ? Files.walk(from).filter(Files::isRegularFile).toList()
: Collections.emptyList();
if (!Files.exists(from)) {
return;
}
List<Path> files;
try (Stream<Path> pathStream = Files.walk(from)) {
files = pathStream.filter(Files::isRegularFile).toList();
}
for (Path file : files) {
String relativeFileName = file.subpath(from.getNameCount(), file.getNameCount()).toString();
getLog().debug("Copying '" + relativeFileName + "' to " + to);

@ -30,6 +30,7 @@ import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Stream;
import org.springframework.boot.convert.ApplicationConversionService;
import org.springframework.boot.origin.Origin;
@ -204,16 +205,18 @@ public class ConfigTreePropertySource extends EnumerablePropertySource<Path> imp
static Map<String, PropertyFile> findAll(Path sourceDirectory, Set<Option> options) {
try {
Map<String, PropertyFile> propertyFiles = new TreeMap<>();
Files.find(sourceDirectory, MAX_DEPTH, PropertyFile::isPropertyFile, FileVisitOption.FOLLOW_LINKS)
.forEach((path) -> {
String name = getName(sourceDirectory.relativize(path));
if (StringUtils.hasText(name)) {
if (options.contains(Option.USE_LOWERCASE_NAMES)) {
name = name.toLowerCase();
}
propertyFiles.put(name, new PropertyFile(path, options));
try (Stream<Path> pathStream = Files.find(sourceDirectory, MAX_DEPTH, PropertyFile::isPropertyFile,
FileVisitOption.FOLLOW_LINKS)) {
pathStream.forEach((path) -> {
String name = getName(sourceDirectory.relativize(path));
if (StringUtils.hasText(name)) {
if (options.contains(Option.USE_LOWERCASE_NAMES)) {
name = name.toLowerCase();
}
});
propertyFiles.put(name, new PropertyFile(path, options));
}
});
}
return Collections.unmodifiableMap(propertyFiles);
}
catch (IOException ex) {

@ -17,6 +17,7 @@
package org.springframework.boot.origin;
import java.io.IOException;
import java.nio.channels.ReadableByteChannel;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -100,8 +101,9 @@ class OriginTrackedResourceTests {
@Test
void readableChannelDelegatesToResource() throws IOException {
this.tracked.readableChannel();
then(this.resource).should().readableChannel();
try (ReadableByteChannel ignore = this.tracked.readableChannel()) {
then(this.resource).should().readableChannel();
}
}
@Test

Loading…
Cancel
Save