Polish "Use try-with-resources to close resources automatically"

- Apply code formatting
- Use try-with-resources in many other places that were missed in the
  pull request

Closes gh-8045
pull/7316/merge
Andy Wilkinson 8 years ago
parent 3e797c326a
commit d5438c299c

@ -132,7 +132,8 @@ public class EndpointDocumentation {
@Test @Test
public void auditEvents() throws Exception { public void auditEvents() throws Exception {
this.mockMvc this.mockMvc
.perform(get("/application/auditevents").param("after", "2016-11-01T10:00:00+0000") .perform(get("/application/auditevents")
.param("after", "2016-11-01T10:00:00+0000")
.accept(ActuatorMediaTypes.APPLICATION_ACTUATOR_V2_JSON)) .accept(ActuatorMediaTypes.APPLICATION_ACTUATOR_V2_JSON))
.andExpect(status().isOk()).andDo(document("auditevents")); .andExpect(status().isOk()).andDo(document("auditevents"));
} }
@ -188,15 +189,11 @@ public class EndpointDocumentation {
} }
File file = new File(RESTDOCS_OUTPUT_DIR + "/endpoints.adoc"); File file = new File(RESTDOCS_OUTPUT_DIR + "/endpoints.adoc");
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
PrintWriter writer = new PrintWriter(file, "UTF-8"); try (PrintWriter writer = new PrintWriter(file, "UTF-8")) {
try {
Template template = this.templates.createTemplate( Template template = this.templates.createTemplate(
new File("src/restdoc/resources/templates/endpoints.adoc.tpl")); new File("src/restdoc/resources/templates/endpoints.adoc.tpl"));
template.make(model).writeTo(writer); template.make(model).writeTo(writer);
} }
finally {
writer.close();
}
} }
private Collection<? extends MvcEndpoint> getEndpoints() { private Collection<? extends MvcEndpoint> getEndpoints() {

@ -51,7 +51,7 @@ import org.springframework.web.bind.annotation.ResponseStatus;
* *
* @author Lari Hotari * @author Lari Hotari
* @author Phillip Webb * @author Phillip Webb
* @author rajakolli * @author Raja Kolli
* @since 1.4.0 * @since 1.4.0
*/ */
@ConfigurationProperties(prefix = "endpoints.heapdump") @ConfigurationProperties(prefix = "endpoints.heapdump")
@ -146,9 +146,9 @@ public class HeapdumpMvcEndpoint extends AbstractNamedMvcEndpoint {
response.setHeader("Content-Disposition", response.setHeader("Content-Disposition",
"attachment; filename=\"" + (heapDumpFile.getName() + ".gz") + "\""); "attachment; filename=\"" + (heapDumpFile.getName() + ".gz") + "\"");
try (InputStream in = new FileInputStream(heapDumpFile); try (InputStream in = new FileInputStream(heapDumpFile);
GZIPOutputStream out = new GZIPOutputStream(response.getOutputStream())) { GZIPOutputStream out = new GZIPOutputStream(response.getOutputStream())) {
StreamUtils.copy(in, out); StreamUtils.copy(in, out);
out.finish(); out.finish();
} }
catch (NullPointerException | FileNotFoundException ex) { catch (NullPointerException | FileNotFoundException ex) {
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2016 the original author or authors. * Copyright 2012-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -35,15 +35,11 @@ public class JmsHealthIndicator extends AbstractHealthIndicator {
@Override @Override
protected void doHealthCheck(Health.Builder builder) throws Exception { protected void doHealthCheck(Health.Builder builder) throws Exception {
Connection connection = this.connectionFactory.createConnection(); try (Connection connection = this.connectionFactory.createConnection()) {
try {
connection.start(); connection.start();
builder.up().withDetail("provider", builder.up().withDetail("provider",
connection.getMetaData().getJMSProviderName()); connection.getMetaData().getJMSProviderName());
} }
finally {
connection.close();
}
} }
} }

@ -61,6 +61,7 @@ import static org.assertj.core.api.Assertions.offset;
* *
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Eddú Meléndez * @author Eddú Meléndez
* @author Raja Kolli
*/ */
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({ "rawtypes", "unchecked" })
public class CacheStatisticsAutoConfigurationTests { public class CacheStatisticsAutoConfigurationTests {

@ -338,9 +338,8 @@ public class EndpointWebMvcAutoConfigurationTests {
@Test @Test
public void specificPortsViaPropertiesWithClash() throws Exception { public void specificPortsViaPropertiesWithClash() throws Exception {
int managementPort = ports.get().management; int managementPort = ports.get().management;
ServerSocket serverSocket = new ServerSocket(); try (ServerSocket serverSocket = new ServerSocket()) {
serverSocket.bind(new InetSocketAddress(managementPort)); serverSocket.bind(new InetSocketAddress(managementPort));
try {
EnvironmentTestUtils.addEnvironment(this.applicationContext, EnvironmentTestUtils.addEnvironment(this.applicationContext,
"server.port:" + ports.get().server, "server.port:" + ports.get().server,
"management.port:" + ports.get().management); "management.port:" + ports.get().management);
@ -350,9 +349,6 @@ public class EndpointWebMvcAutoConfigurationTests {
this.thrown.expect(WebServerException.class); this.thrown.expect(WebServerException.class);
this.applicationContext.refresh(); this.applicationContext.refresh();
} }
finally {
serverSocket.close();
}
} }
@Test @Test
@ -683,23 +679,17 @@ public class EndpointWebMvcAutoConfigurationTests {
httpClient); httpClient);
ClientHttpRequest request = requestFactory.createRequest( ClientHttpRequest request = requestFactory.createRequest(
new URI(scheme + "://localhost:" + port + url), HttpMethod.GET); new URI(scheme + "://localhost:" + port + url), HttpMethod.GET);
try { try (ClientHttpResponse response = request.execute()) {
ClientHttpResponse response = request.execute();
if (HttpStatus.NOT_FOUND.equals(response.getStatusCode())) { if (HttpStatus.NOT_FOUND.equals(response.getStatusCode())) {
throw new FileNotFoundException(); throw new FileNotFoundException();
} }
try { String actual = StreamUtils.copyToString(response.getBody(),
String actual = StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8"));
Charset.forName("UTF-8")); if (expected instanceof Matcher) {
if (expected instanceof Matcher) { assertThat(actual).is(Matched.by((Matcher<?>) expected));
assertThat(actual).is(Matched.by((Matcher<?>) expected));
}
else {
assertThat(actual).isEqualTo(expected);
}
} }
finally { else {
response.close(); assertThat(actual).isEqualTo(expected);
} }
} }
catch (Exception ex) { catch (Exception ex) {

@ -39,9 +39,8 @@ public class TomcatPublicMetricsTests {
@Test @Test
public void tomcatMetrics() throws Exception { public void tomcatMetrics() throws Exception {
AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext( try (AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext(
Config.class); Config.class)) {
try {
TomcatPublicMetrics tomcatMetrics = context TomcatPublicMetrics tomcatMetrics = context
.getBean(TomcatPublicMetrics.class); .getBean(TomcatPublicMetrics.class);
Iterator<Metric<?>> metrics = tomcatMetrics.metrics().iterator(); Iterator<Metric<?>> metrics = tomcatMetrics.metrics().iterator();
@ -49,9 +48,6 @@ public class TomcatPublicMetricsTests {
assertThat(metrics.next().getName()).isEqualTo("httpsessions.active"); assertThat(metrics.next().getName()).isEqualTo("httpsessions.active");
assertThat(metrics.hasNext()).isFalse(); assertThat(metrics.hasNext()).isFalse();
} }
finally {
context.close();
}
} }
@Configuration @Configuration

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2016 the original author or authors. * Copyright 2012-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -62,18 +62,14 @@ public class MetricCopyExporterTests {
@Test @Test
public void counterWithGaugeWriter() throws Exception { public void counterWithGaugeWriter() throws Exception {
SimpleGaugeWriter writer = new SimpleGaugeWriter(); SimpleGaugeWriter writer = new SimpleGaugeWriter();
MetricCopyExporter exporter = new MetricCopyExporter(this.reader, writer); try (MetricCopyExporter customExporter = new MetricCopyExporter(this.reader, writer)) {
try {
this.reader.increment(new Delta<Number>("counter.foo", 2)); this.reader.increment(new Delta<Number>("counter.foo", 2));
exporter.export(); customExporter.export();
this.reader.increment(new Delta<Number>("counter.foo", 3)); this.reader.increment(new Delta<Number>("counter.foo", 3));
exporter.export(); customExporter.export();
exporter.flush(); customExporter.flush();
assertThat(writer.getValue().getValue()).isEqualTo(5L); assertThat(writer.getValue().getValue()).isEqualTo(5L);
} }
finally {
exporter.close();
}
} }
@Test @Test

@ -40,6 +40,7 @@ import org.springframework.util.CollectionUtils;
* *
* @author Eddú Meléndez * @author Eddú Meléndez
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Raja Kolli
* @since 1.3.0 * @since 1.3.0
*/ */
@Configuration @Configuration

@ -57,6 +57,7 @@ import org.springframework.util.StringUtils;
* *
* @author Eddú Meléndez * @author Eddú Meléndez
* @author Mathieu Ouellet * @author Mathieu Ouellet
* @author Raja Kolli
* @since 1.5.0 * @since 1.5.0
*/ */
@Configuration @Configuration

@ -127,8 +127,8 @@ public class SpringApplicationAdminJmxAutoConfigurationTests {
assertThat(this.context).isInstanceOf(ServletWebServerApplicationContext.class); assertThat(this.context).isInstanceOf(ServletWebServerApplicationContext.class);
assertThat(this.mBeanServer.getAttribute(createDefaultObjectName(), assertThat(this.mBeanServer.getAttribute(createDefaultObjectName(),
"EmbeddedWebApplication")).isEqualTo(Boolean.TRUE); "EmbeddedWebApplication")).isEqualTo(Boolean.TRUE);
int expected = ((ServletWebServerApplicationContext) this.context) int expected = ((ServletWebServerApplicationContext) this.context).getWebServer()
.getWebServer().getPort(); .getPort();
String actual = getProperty(createDefaultObjectName(), "local.server.port"); String actual = getProperty(createDefaultObjectName(), "local.server.port");
assertThat(actual).isEqualTo(String.valueOf(expected)); assertThat(actual).isEqualTo(String.valueOf(expected));
} }
@ -142,26 +142,17 @@ public class SpringApplicationAdminJmxAutoConfigurationTests {
.child(JmxAutoConfiguration.class, .child(JmxAutoConfiguration.class,
SpringApplicationAdminJmxAutoConfiguration.class) SpringApplicationAdminJmxAutoConfiguration.class)
.web(WebApplicationType.NONE); .web(WebApplicationType.NONE);
ConfigurableApplicationContext parent = null;
ConfigurableApplicationContext child = null;
try { try (ConfigurableApplicationContext parent = parentBuilder
parent = parentBuilder.run("--" + ENABLE_ADMIN_PROP); .run("--" + ENABLE_ADMIN_PROP);
child = childBuilder.run("--" + ENABLE_ADMIN_PROP); ConfigurableApplicationContext child = childBuilder
.run("--" + ENABLE_ADMIN_PROP)) {
BeanFactoryUtils.beanOfType(parent.getBeanFactory(), BeanFactoryUtils.beanOfType(parent.getBeanFactory(),
SpringApplicationAdminMXBeanRegistrar.class); SpringApplicationAdminMXBeanRegistrar.class);
this.thrown.expect(NoSuchBeanDefinitionException.class); this.thrown.expect(NoSuchBeanDefinitionException.class);
BeanFactoryUtils.beanOfType(child.getBeanFactory(), BeanFactoryUtils.beanOfType(child.getBeanFactory(),
SpringApplicationAdminMXBeanRegistrar.class); SpringApplicationAdminMXBeanRegistrar.class);
} }
finally {
if (parent != null) {
parent.close();
}
if (child != null) {
child.close();
}
}
} }
private ObjectName createDefaultObjectName() { private ObjectName createDefaultObjectName() {

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2016 the original author or authors. * Copyright 2012-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -145,17 +145,13 @@ public class ConditionalOnSingleCandidateTests {
@Test @Test
public void singleCandidateMultipleCandidatesInContextHierarchy() { public void singleCandidateMultipleCandidatesInContextHierarchy() {
load(FooPrimaryConfiguration.class, BarConfiguration.class); load(FooPrimaryConfiguration.class, BarConfiguration.class);
AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext(); try (AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext()) {
child.setParent(this.context); child.setParent(this.context);
child.register(OnBeanSingleCandidateConfiguration.class); child.register(OnBeanSingleCandidateConfiguration.class);
try {
child.refresh(); child.refresh();
assertThat(child.containsBean("baz")).isTrue(); assertThat(child.containsBean("baz")).isTrue();
assertThat(child.getBean("baz")).isEqualTo("foo"); assertThat(child.getBean("baz")).isEqualTo("foo");
} }
finally {
child.close();
}
} }
private void load(Class<?>... classes) { private void load(Class<?>... classes) {

@ -143,9 +143,8 @@ public class MessageSourceAutoConfigurationTests {
@Test @Test
public void existingMessageSourceInParentIsIgnored() { public void existingMessageSourceInParentIsIgnored() {
ConfigurableApplicationContext parent = new AnnotationConfigApplicationContext(); try (ConfigurableApplicationContext parent = new AnnotationConfigApplicationContext()) {
parent.refresh(); parent.refresh();
try {
this.context = new AnnotationConfigApplicationContext(); this.context = new AnnotationConfigApplicationContext();
this.context.setParent(parent); this.context.setParent(parent);
EnvironmentTestUtils.addEnvironment(this.context, EnvironmentTestUtils.addEnvironment(this.context,
@ -156,9 +155,6 @@ public class MessageSourceAutoConfigurationTests {
assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)) assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK))
.isEqualTo("bar"); .isEqualTo("bar");
} }
finally {
parent.close();
}
} }
private void load(String... environment) { private void load(String... environment) {

@ -83,14 +83,10 @@ public class CassandraDataAutoConfigurationIntegrationTests {
} }
private void createTestKeyspaceIfNotExists() { private void createTestKeyspaceIfNotExists() {
Session session = this.cassandra.getCluster().connect(); try (Session session = this.cassandra.getCluster().connect()) {
try {
session.execute("CREATE KEYSPACE IF NOT EXISTS boot_test" session.execute("CREATE KEYSPACE IF NOT EXISTS boot_test"
+ " WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };"); + " WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };");
} }
finally {
session.close();
}
} }
} }

@ -235,20 +235,16 @@ public class NoSuchBeanDefinitionFailureAnalyzerTests {
} }
private FatalBeanException createFailure(Class<?> config, String... environment) { private FatalBeanException createFailure(Class<?> config, String... environment) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
this.analyzer.setBeanFactory(context.getBeanFactory()); this.analyzer.setBeanFactory(context.getBeanFactory());
EnvironmentTestUtils.addEnvironment(context, environment); EnvironmentTestUtils.addEnvironment(context, environment);
context.register(config); context.register(config);
try {
context.refresh(); context.refresh();
return null; return null;
} }
catch (FatalBeanException ex) { catch (FatalBeanException ex) {
return ex; return ex;
} }
finally {
context.close();
}
} }
private FailureAnalysis analyzeFailure(Exception failure) { private FailureAnalysis analyzeFailure(Exception failure) {

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2016 the original author or authors. * Copyright 2012-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -177,18 +177,14 @@ public class FreeMarkerAutoConfigurationTests {
@Test @Test
public void renderNonWebAppTemplate() throws Exception { public void renderNonWebAppTemplate() throws Exception {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( try (AnnotationConfigApplicationContext customContext = new AnnotationConfigApplicationContext(
FreeMarkerAutoConfiguration.class); FreeMarkerAutoConfiguration.class)) {
try { freemarker.template.Configuration freemarker = customContext
freemarker.template.Configuration freemarker = context
.getBean(freemarker.template.Configuration.class); .getBean(freemarker.template.Configuration.class);
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
freemarker.getTemplate("message.ftl").process(this, writer); freemarker.getTemplate("message.ftl").process(this, writer);
assertThat(writer.toString()).contains("Hello World"); assertThat(writer.toString()).contains("Hello World");
} }
finally {
context.close();
}
} }
@Test @Test

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2016 the original author or authors. * Copyright 2012-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -56,22 +56,17 @@ public class EmbeddedDataSourceConfigurationTests {
@Test @Test
public void generateUniqueName() throws Exception { public void generateUniqueName() throws Exception {
this.context = load("spring.datasource.generate-unique-name=true"); this.context = load("spring.datasource.generate-unique-name=true");
AnnotationConfigApplicationContext context2 = load( try (AnnotationConfigApplicationContext context2 = load(
"spring.datasource.generate-unique-name=true"); "spring.datasource.generate-unique-name=true")) {
try {
DataSource dataSource = this.context.getBean(DataSource.class); DataSource dataSource = this.context.getBean(DataSource.class);
DataSource dataSource2 = context2.getBean(DataSource.class); DataSource dataSource2 = context2.getBean(DataSource.class);
assertThat(getDatabaseName(dataSource)) assertThat(getDatabaseName(dataSource))
.isNotEqualTo(getDatabaseName(dataSource2)); .isNotEqualTo(getDatabaseName(dataSource2));
} }
finally {
context2.close();
}
} }
private String getDatabaseName(DataSource dataSource) throws SQLException { private String getDatabaseName(DataSource dataSource) throws SQLException {
Connection connection = dataSource.getConnection(); try (Connection connection = dataSource.getConnection()) {
try {
ResultSet catalogs = connection.getMetaData().getCatalogs(); ResultSet catalogs = connection.getMetaData().getCatalogs();
if (catalogs.next()) { if (catalogs.next()) {
return catalogs.getString(1); return catalogs.getString(1);
@ -80,9 +75,6 @@ public class EmbeddedDataSourceConfigurationTests {
throw new IllegalStateException("Unable to get database name"); throw new IllegalStateException("Unable to get database name");
} }
} }
finally {
connection.close();
}
} }
private AnnotationConfigApplicationContext load(String... environment) { private AnnotationConfigApplicationContext load(String... environment) {

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2016 the original author or authors. * Copyright 2012-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -234,9 +234,8 @@ public class ArtemisAutoConfigurationTests {
@Test @Test
public void severalEmbeddedBrokers() { public void severalEmbeddedBrokers() {
load(EmptyConfiguration.class, "spring.artemis.embedded.queues=Queue1"); load(EmptyConfiguration.class, "spring.artemis.embedded.queues=Queue1");
AnnotationConfigApplicationContext anotherContext = doLoad( try (AnnotationConfigApplicationContext anotherContext = doLoad(
EmptyConfiguration.class, "spring.artemis.embedded.queues=Queue2"); EmptyConfiguration.class, "spring.artemis.embedded.queues=Queue2")) {
try {
ArtemisProperties properties = this.context.getBean(ArtemisProperties.class); ArtemisProperties properties = this.context.getBean(ArtemisProperties.class);
ArtemisProperties anotherProperties = anotherContext ArtemisProperties anotherProperties = anotherContext
.getBean(ArtemisProperties.class); .getBean(ArtemisProperties.class);
@ -249,29 +248,23 @@ public class ArtemisAutoConfigurationTests {
anotherChecker.checkQueue("Queue2", true); anotherChecker.checkQueue("Queue2", true);
anotherChecker.checkQueue("Queue1", true); anotherChecker.checkQueue("Queue1", true);
} }
finally {
anotherContext.close();
}
} }
@Test @Test
public void connectToASpecificEmbeddedBroker() { public void connectToASpecificEmbeddedBroker() {
load(EmptyConfiguration.class, "spring.artemis.embedded.serverId=93", load(EmptyConfiguration.class, "spring.artemis.embedded.serverId=93",
"spring.artemis.embedded.queues=Queue1"); "spring.artemis.embedded.queues=Queue1");
AnnotationConfigApplicationContext anotherContext = doLoad(
try (AnnotationConfigApplicationContext anotherContext = doLoad(
EmptyConfiguration.class, "spring.artemis.mode=embedded", EmptyConfiguration.class, "spring.artemis.mode=embedded",
"spring.artemis.embedded.serverId=93", // Connect to the "main" broker "spring.artemis.embedded.serverId=93", /* Connect to the "main" broker */
"spring.artemis.embedded.enabled=false"); // do not start a specific one "spring.artemis.embedded.enabled=false" /* do not start a specific one */)) {
try {
DestinationChecker checker = new DestinationChecker(this.context); DestinationChecker checker = new DestinationChecker(this.context);
checker.checkQueue("Queue1", true); checker.checkQueue("Queue1", true);
DestinationChecker anotherChecker = new DestinationChecker(anotherContext); DestinationChecker anotherChecker = new DestinationChecker(anotherContext);
anotherChecker.checkQueue("Queue1", true); anotherChecker.checkQueue("Queue1", true);
} }
finally {
anotherContext.close();
}
} }
private TransportConfiguration assertInVmConnectionFactory( private TransportConfiguration assertInVmConnectionFactory(

@ -108,9 +108,8 @@ public class EmbeddedMongoAutoConfigurationTests {
@Test @Test
public void portIsAvailableInParentContext() { public void portIsAvailableInParentContext() {
ConfigurableApplicationContext parent = new AnnotationConfigApplicationContext(); try (ConfigurableApplicationContext parent = new AnnotationConfigApplicationContext()) {
parent.refresh(); parent.refresh();
try {
this.context = new AnnotationConfigApplicationContext(); this.context = new AnnotationConfigApplicationContext();
this.context.setParent(parent); this.context.setParent(parent);
this.context.register(EmbeddedMongoAutoConfiguration.class, this.context.register(EmbeddedMongoAutoConfiguration.class,
@ -119,9 +118,6 @@ public class EmbeddedMongoAutoConfigurationTests {
assertThat(parent.getEnvironment().getProperty("local.mongo.port")) assertThat(parent.getEnvironment().getProperty("local.mongo.port"))
.isNotNull(); .isNotNull();
} }
finally {
parent.close();
}
} }
@Test @Test

@ -108,16 +108,12 @@ public class SecurityAutoConfigurationTests {
@Test @Test
public void testFilterIsNotRegisteredInNonWeb() throws Exception { public void testFilterIsNotRegisteredInNonWeb() throws Exception {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); try (AnnotationConfigApplicationContext customContext = new AnnotationConfigApplicationContext()) {
context.register(SecurityAutoConfiguration.class, customContext.register(SecurityAutoConfiguration.class,
SecurityFilterAutoConfiguration.class, SecurityFilterAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class); PropertyPlaceholderAutoConfiguration.class);
try { customContext.refresh();
context.refresh(); assertThat(customContext.containsBean("securityFilterChainRegistration")).isFalse();
assertThat(context.containsBean("securityFilterChainRegistration")).isFalse();
}
finally {
context.close();
} }
} }

@ -58,8 +58,7 @@ public class SecurityFilterAutoConfigurationEarlyInitializationTests {
@Test @Test
public void testSecurityFilterDoesNotCauseEarlyInitialization() throws Exception { public void testSecurityFilterDoesNotCauseEarlyInitialization() throws Exception {
AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext(); try (AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext()) {
try {
EnvironmentTestUtils.addEnvironment(context, "server.port:0", EnvironmentTestUtils.addEnvironment(context, "server.port:0",
"security.user.password:password"); "security.user.password:password");
context.register(Config.class); context.register(Config.class);
@ -70,10 +69,6 @@ public class SecurityFilterAutoConfigurationEarlyInitializationTests {
// If early initialization occurred a ConverterNotFoundException is thrown // If early initialization occurred a ConverterNotFoundException is thrown
} }
finally {
context.close();
}
} }
@Configuration @Configuration

@ -44,16 +44,11 @@ public class SecurityFilterAutoConfigurationTests {
@Test @Test
public void filterAutoConfigurationWorksWithoutSecurityAutoConfiguration() public void filterAutoConfigurationWorksWithoutSecurityAutoConfiguration()
throws Exception { throws Exception {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); try (AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext()) {
context.setServletContext(new MockServletContext()); context.setServletContext(new MockServletContext());
try {
context.register(Config.class); context.register(Config.class);
context.refresh(); context.refresh();
} }
finally {
context.close();
}
} }
@Configuration @Configuration

@ -173,20 +173,17 @@ public class ThymeleafServletAutoConfigurationTests {
@Test @Test
public void renderNonWebAppTemplate() throws Exception { public void renderNonWebAppTemplate() throws Exception {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( try (AnnotationConfigApplicationContext customContext = new AnnotationConfigApplicationContext(
ThymeleafAutoConfiguration.class, ThymeleafAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class); PropertyPlaceholderAutoConfiguration.class)) {
assertThat(context.getBeanNamesForType(ViewResolver.class).length).isEqualTo(0); assertThat(customContext.getBeanNamesForType(ViewResolver.class).length)
try { .isEqualTo(0);
TemplateEngine engine = context.getBean(TemplateEngine.class); TemplateEngine engine = customContext.getBean(TemplateEngine.class);
Context attrs = new Context(Locale.UK, Context attrs = new Context(Locale.UK,
Collections.singletonMap("greeting", "Hello World")); Collections.singletonMap("greeting", "Hello World"));
String result = engine.process("message", attrs); String result = engine.process("message", attrs);
assertThat(result).contains("Hello World"); assertThat(result).contains("Hello World");
} }
finally {
context.close();
}
} }
@Test @Test

@ -79,8 +79,7 @@ public final class CommandLineInvoker {
} }
})[0]; })[0];
ZipInputStream input = new ZipInputStream(new FileInputStream(zip)); try (ZipInputStream input = new ZipInputStream(new FileInputStream(zip))) {
try {
ZipEntry entry; ZipEntry entry;
while ((entry = input.getNextEntry()) != null) { while ((entry = input.getNextEntry()) != null) {
File file = new File(unpacked, entry.getName()); File file = new File(unpacked, entry.getName());
@ -89,22 +88,15 @@ public final class CommandLineInvoker {
} }
else { else {
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
FileOutputStream output = new FileOutputStream(file); try (FileOutputStream output = new FileOutputStream(file)) {
try {
StreamUtils.copy(input, output); StreamUtils.copy(input, output);
if (entry.getName().endsWith("/bin/spring")) { if (entry.getName().endsWith("/bin/spring")) {
file.setExecutable(true); file.setExecutable(true);
} }
} }
finally {
output.close();
}
} }
} }
} }
finally {
input.close();
}
} }
File bin = new File(unpacked.listFiles()[0], "bin"); File bin = new File(unpacked.listFiles()[0], "bin");
File launchScript = new File(bin, isWindows() ? "spring.bat" : "spring"); File launchScript = new File(bin, isWindows() ? "spring.bat" : "spring");

@ -187,8 +187,7 @@ abstract class ArchiveCommand extends OptionParsingCommand {
List<MatchedResource> classpathEntries, List<URL> dependencies) List<MatchedResource> classpathEntries, List<URL> dependencies)
throws FileNotFoundException, IOException, URISyntaxException { throws FileNotFoundException, IOException, URISyntaxException {
final List<Library> libraries; final List<Library> libraries;
JarWriter writer = new JarWriter(file); try (JarWriter writer = new JarWriter(file)) {
try {
addManifest(writer, compiledClasses); addManifest(writer, compiledClasses);
addCliClasses(writer); addCliClasses(writer);
for (Class<?> compiledClass : compiledClasses) { for (Class<?> compiledClass : compiledClasses) {
@ -196,9 +195,6 @@ abstract class ArchiveCommand extends OptionParsingCommand {
} }
libraries = addClasspathEntries(writer, classpathEntries); libraries = addClasspathEntries(writer, classpathEntries);
} }
finally {
writer.close();
}
libraries.addAll(createLibraries(dependencies)); libraries.addAll(createLibraries(dependencies));
Repackager repackager = new Repackager(file); Repackager repackager = new Repackager(file);
repackager.setMainClass(PackagedSpringApplicationLauncher.class.getName()); repackager.setMainClass(PackagedSpringApplicationLauncher.class.getName());

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2015 the original author or authors. * Copyright 2012-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -31,7 +31,6 @@ import org.springframework.util.StreamUtils;
* Helper class used to generate the project. * Helper class used to generate the project.
* *
* @author Stephane Nicoll * @author Stephane Nicoll
* @since 1.2.0
*/ */
class ProjectGenerator { class ProjectGenerator {
@ -106,17 +105,13 @@ class ProjectGenerator {
if (!outputFolder.exists()) { if (!outputFolder.exists()) {
outputFolder.mkdirs(); outputFolder.mkdirs();
} }
ZipInputStream zipStream = new ZipInputStream( try (ZipInputStream zipStream = new ZipInputStream(
new ByteArrayInputStream(entity.getContent())); new ByteArrayInputStream(entity.getContent()))) {
try {
extractFromStream(zipStream, overwrite, outputFolder); extractFromStream(zipStream, overwrite, outputFolder);
fixExecutableFlag(outputFolder, "mvnw"); fixExecutableFlag(outputFolder, "mvnw");
fixExecutableFlag(outputFolder, "gradlew"); fixExecutableFlag(outputFolder, "gradlew");
Log.info("Project extracted to '" + outputFolder.getAbsolutePath() + "'"); Log.info("Project extracted to '" + outputFolder.getAbsolutePath() + "'");
} }
finally {
zipStream.close();
}
} }
private void extractFromStream(ZipInputStream zipStream, boolean overwrite, private void extractFromStream(ZipInputStream zipStream, boolean overwrite,

@ -36,7 +36,6 @@ import org.springframework.boot.cli.compiler.GroovyCompilerConfiguration;
* *
* @author Dave Syer * @author Dave Syer
* @author Andy Wilkinson * @author Andy Wilkinson
* @since 1.2.0
*/ */
class GroovyGrabDependencyResolver implements DependencyResolver { class GroovyGrabDependencyResolver implements DependencyResolver {
@ -70,18 +69,14 @@ class GroovyGrabDependencyResolver implements DependencyResolver {
private String createSources(List<String> artifactIdentifiers) throws IOException { private String createSources(List<String> artifactIdentifiers) throws IOException {
File file = File.createTempFile("SpringCLIDependency", ".groovy"); File file = File.createTempFile("SpringCLIDependency", ".groovy");
file.deleteOnExit(); file.deleteOnExit();
OutputStreamWriter stream = new OutputStreamWriter(new FileOutputStream(file), try (OutputStreamWriter stream = new OutputStreamWriter(
"UTF-8"); new FileOutputStream(file), "UTF-8")) {
try {
for (String artifactIdentifier : artifactIdentifiers) { for (String artifactIdentifier : artifactIdentifiers) {
stream.write("@Grab('" + artifactIdentifier + "')"); stream.write("@Grab('" + artifactIdentifier + "')");
} }
// Dummy class to force compiler to do grab // Dummy class to force compiler to do grab
stream.write("class Installer {}"); stream.write("class Installer {}");
} }
finally {
stream.close();
}
// Windows paths get tricky unless you work with URI // Windows paths get tricky unless you work with URI
return file.getAbsoluteFile().toURI().toString(); return file.getAbsoluteFile().toURI().toString();
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2016 the original author or authors. * Copyright 2012-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -38,7 +38,6 @@ import org.springframework.util.SystemPropertyUtils;
* Shared logic for the {@link InstallCommand} and {@link UninstallCommand}. * Shared logic for the {@link InstallCommand} and {@link UninstallCommand}.
* *
* @author Andy Wilkinson * @author Andy Wilkinson
* @since 1.2.0
*/ */
class Installer { class Installer {
@ -82,13 +81,9 @@ class Installer {
} }
private void saveInstallCounts() throws IOException { private void saveInstallCounts() throws IOException {
FileWriter writer = new FileWriter(getInstalled()); try (FileWriter writer = new FileWriter(getInstalled())) {
try {
this.installCounts.store(writer, null); this.installCounts.store(writer, null);
} }
finally {
writer.close();
}
} }
public void install(List<String> artifactIdentifiers) throws Exception { public void install(List<String> artifactIdentifiers) throws Exception {

@ -98,14 +98,10 @@ public class ExtendedGroovyClassLoader extends GroovyClassLoader {
private Class<?> findSharedClass(String name) { private Class<?> findSharedClass(String name) {
try { try {
String path = name.replace('.', '/').concat(".class"); String path = name.replace('.', '/').concat(".class");
InputStream inputStream = getParent().getResourceAsStream(path); try (InputStream inputStream = getParent().getResourceAsStream(path)) {
if (inputStream != null) { if (inputStream != null) {
try {
return defineClass(name, FileCopyUtils.copyToByteArray(inputStream)); return defineClass(name, FileCopyUtils.copyToByteArray(inputStream));
} }
finally {
inputStream.close();
}
} }
return null; return null;
} }

@ -365,18 +365,14 @@ public class InitCommandTests extends AbstractHttpClientMockTests {
private byte[] createFakeZipArchive(String fileName, String content) private byte[] createFakeZipArchive(String fileName, String content)
throws IOException { throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(bos); ZipOutputStream zos = new ZipOutputStream(bos)) {
try {
ZipEntry entry = new ZipEntry(fileName); ZipEntry entry = new ZipEntry(fileName);
zos.putNextEntry(entry); zos.putNextEntry(entry);
zos.write(content.getBytes()); zos.write(content.getBytes());
zos.closeEntry(); zos.closeEntry();
return bos.toByteArray();
} }
finally {
bos.close();
}
return bos.toByteArray();
} }
private static class TestableInitCommandOptionHandler private static class TestableInitCommandOptionHandler

@ -92,14 +92,10 @@ public class InitializrServiceMetadataTests {
private static JSONObject readJson(String version) throws IOException, JSONException { private static JSONObject readJson(String version) throws IOException, JSONException {
Resource resource = new ClassPathResource( Resource resource = new ClassPathResource(
"metadata/service-metadata-" + version + ".json"); "metadata/service-metadata-" + version + ".json");
InputStream stream = resource.getInputStream(); try (InputStream stream = resource.getInputStream()) {
try {
return new JSONObject( return new JSONObject(
StreamUtils.copyToString(stream, Charset.forName("UTF-8"))); StreamUtils.copyToString(stream, Charset.forName("UTF-8")));
} }
finally {
stream.close();
}
} }
} }

@ -282,16 +282,10 @@ public class LiveReloadServer {
private void handle() throws Exception { private void handle() throws Exception {
try { try {
try { try (OutputStream outputStream = this.socket.getOutputStream()) {
OutputStream outputStream = this.socket.getOutputStream(); Connection connection = createConnection(this.socket,
try { this.inputStream, outputStream);
Connection connection = createConnection(this.socket, runConnection(connection);
this.inputStream, outputStream);
runConnection(connection);
}
finally {
outputStream.close();
}
} }
finally { finally {
this.inputStream.close(); this.inputStream.close();

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2016 the original author or authors. * Copyright 2012-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -152,16 +152,12 @@ public class TunnelClient implements SmartInitializingSingleton {
public void run() { public void run() {
try { try {
while (this.acceptConnections) { while (this.acceptConnections) {
SocketChannel socket = this.serverSocketChannel.accept(); try (SocketChannel socket = this.serverSocketChannel.accept()) {
try {
handleConnection(socket); handleConnection(socket);
} }
catch (AsynchronousCloseException ex) { catch (AsynchronousCloseException ex) {
// Connection has been closed. Keep the server running // Connection has been closed. Keep the server running
} }
finally {
socket.close();
}
} }
} }
catch (Exception ex) { catch (Exception ex) {

@ -27,8 +27,7 @@ public final class Verify {
} }
public static void verify(File file, String entry) throws Exception { public static void verify(File file, String entry) throws Exception {
ZipFile zipFile = new ZipFile(file); try (ZipFile zipFile = new ZipFile(file)) {
try {
Enumeration<? extends ZipEntry> entries = zipFile.entries(); Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) { while (entries.hasMoreElements()) {
if (entries.nextElement().getName().equals(entry)) { if (entries.nextElement().getName().equals(entry)) {
@ -37,9 +36,6 @@ public final class Verify {
} }
throw new AssertionError("No entry " + entry); throw new AssertionError("No entry " + entry);
} }
finally {
zipFile.close();
}
} }
} }

@ -97,14 +97,10 @@ public class SampleIntegrationApplicationTests {
} }
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
for (Resource resource : resources) { for (Resource resource : resources) {
InputStream inputStream = resource.getInputStream(); try (InputStream inputStream = resource.getInputStream()) {
try {
builder.append(new String( builder.append(new String(
StreamUtils.copyToByteArray(inputStream))); StreamUtils.copyToByteArray(inputStream)));
} }
finally {
inputStream.close();
}
} }
return builder.toString(); return builder.toString();
} }

@ -64,21 +64,14 @@ public class SampleJettyApplicationTests {
HttpHeaders requestHeaders = new HttpHeaders(); HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("Accept-Encoding", "gzip"); requestHeaders.set("Accept-Encoding", "gzip");
HttpEntity<?> requestEntity = new HttpEntity<>(requestHeaders); HttpEntity<?> requestEntity = new HttpEntity<>(requestHeaders);
ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET, ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET,
requestEntity, byte[].class); requestEntity, byte[].class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
try (GZIPInputStream inflater = new GZIPInputStream(
GZIPInputStream inflater = new GZIPInputStream( new ByteArrayInputStream(entity.getBody()))) {
new ByteArrayInputStream(entity.getBody()));
try {
assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))) assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8")))
.isEqualTo("Hello World"); .isEqualTo("Hello World");
} }
finally {
inflater.close();
}
} }
} }

@ -75,15 +75,11 @@ public class SampleTomcatApplicationTests {
ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET, ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET,
requestEntity, byte[].class); requestEntity, byte[].class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
GZIPInputStream inflater = new GZIPInputStream( try (GZIPInputStream inflater = new GZIPInputStream(
new ByteArrayInputStream(entity.getBody())); new ByteArrayInputStream(entity.getBody()))) {
try {
assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))) assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8")))
.isEqualTo("Hello World"); .isEqualTo("Hello World");
} }
finally {
inflater.close();
}
} }
@Test @Test

@ -70,15 +70,12 @@ public class SampleUndertowApplicationTests {
ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET, ResponseEntity<byte[]> entity = this.restTemplate.exchange("/", HttpMethod.GET,
requestEntity, byte[].class); requestEntity, byte[].class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
GZIPInputStream inflater = new GZIPInputStream(
new ByteArrayInputStream(entity.getBody())); try (GZIPInputStream inflater = new GZIPInputStream(
try { new ByteArrayInputStream(entity.getBody()))) {
assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))) assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8")))
.isEqualTo("Hello World"); .isEqualTo("Hello World");
} }
finally {
inflater.close();
}
} }
private void assertOkResponse(String path, String body) { private void assertOkResponse(String path, String body) {

@ -60,16 +60,12 @@ public class TestDatabaseAutoConfigurationTests {
DataSource datasource = this.context.getBean(DataSource.class); DataSource datasource = this.context.getBean(DataSource.class);
JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource); JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource);
jdbcTemplate.execute("create table example (id int, name varchar);"); jdbcTemplate.execute("create table example (id int, name varchar);");
ConfigurableApplicationContext anotherContext = doLoad( try (ConfigurableApplicationContext anotherContext = doLoad(
ExistingDataSourceConfiguration.class); ExistingDataSourceConfiguration.class)) {
try {
DataSource anotherDatasource = anotherContext.getBean(DataSource.class); DataSource anotherDatasource = anotherContext.getBean(DataSource.class);
JdbcTemplate anotherJdbcTemplate = new JdbcTemplate(anotherDatasource); JdbcTemplate anotherJdbcTemplate = new JdbcTemplate(anotherDatasource);
anotherJdbcTemplate.execute("create table example (id int, name varchar);"); anotherJdbcTemplate.execute("create table example (id int, name varchar);");
} }
finally {
anotherContext.close();
}
} }
private void load(Class<?> config, String... environment) { private void load(Class<?> config, String... environment) {

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2016 the original author or authors. * Copyright 2012-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -42,25 +42,13 @@ class ContentContainingCondition extends Condition<File> {
@Override @Override
public boolean matches(File value) { public boolean matches(File value) {
Reader reader = null; try (Reader reader = new FileReader(value)) {
try {
reader = new FileReader(value);
String content = FileCopyUtils.copyToString(reader); String content = FileCopyUtils.copyToString(reader);
return content.contains(this.toContain); return content.contains(this.toContain);
} }
catch (IOException ex) { catch (IOException ex) {
throw new IllegalStateException(ex); throw new IllegalStateException(ex);
} }
finally {
if (reader != null) {
try {
reader.close();
}
catch (IOException ex) {
// Ignore
}
}
}
} }
} }

@ -201,13 +201,9 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor {
if (!this.properties.isEmpty()) { if (!this.properties.isEmpty()) {
FileObject file = this.processingEnv.getFiler() FileObject file = this.processingEnv.getFiler()
.createResource(StandardLocation.CLASS_OUTPUT, "", PROPERTIES_PATH); .createResource(StandardLocation.CLASS_OUTPUT, "", PROPERTIES_PATH);
OutputStream outputStream = file.openOutputStream(); try (OutputStream outputStream = file.openOutputStream()) {
try {
this.properties.store(outputStream, null); this.properties.store(outputStream, null);
} }
finally {
outputStream.close();
}
} }
} }

@ -62,15 +62,11 @@ public class TestConditionMetadataAnnotationProcessor
if (!file.exists()) { if (!file.exists()) {
return null; return null;
} }
FileInputStream inputStream = new FileInputStream(file); try (FileInputStream inputStream = new FileInputStream(file)) {
try {
Properties properties = new Properties(); Properties properties = new Properties();
properties.load(inputStream); properties.load(inputStream);
return properties; return properties;
} }
finally {
inputStream.close();
}
} }
} }

@ -40,8 +40,7 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
@Test @Test
public void simpleRepository() throws IOException { public void simpleRepository() throws IOException {
InputStream foo = getInputStreamFor("foo"); try (InputStream foo = getInputStreamFor("foo")) {
try {
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder
.create(foo).build(); .create(foo).build();
validateFoo(repo); validateFoo(repo);
@ -50,15 +49,11 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
"spring.foo.counter"); "spring.foo.counter");
assertThat(repo.getAllProperties()).hasSize(3); assertThat(repo.getAllProperties()).hasSize(3);
} }
finally {
foo.close();
}
} }
@Test @Test
public void hintsOnMaps() throws IOException { public void hintsOnMaps() throws IOException {
InputStream map = getInputStreamFor("map"); try (InputStream map = getInputStreamFor("map")) {
try {
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder
.create(map).build(); .create(map).build();
validateMap(repo); validateMap(repo);
@ -67,16 +62,12 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
"spring.map.keys", "spring.map.values"); "spring.map.keys", "spring.map.values");
assertThat(repo.getAllProperties()).hasSize(4); assertThat(repo.getAllProperties()).hasSize(4);
} }
finally {
map.close();
}
} }
@Test @Test
public void severalRepositoriesNoConflict() throws IOException { public void severalRepositoriesNoConflict() throws IOException {
InputStream foo = getInputStreamFor("foo"); try (InputStream foo = getInputStreamFor("foo");
InputStream bar = getInputStreamFor("bar"); InputStream bar = getInputStreamFor("bar")) {
try {
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder
.create(foo, bar).build(); .create(foo, bar).build();
validateFoo(repo); validateFoo(repo);
@ -87,17 +78,12 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
"spring.bar.counter"); "spring.bar.counter");
assertThat(repo.getAllProperties()).hasSize(6); assertThat(repo.getAllProperties()).hasSize(6);
} }
finally {
foo.close();
bar.close();
}
} }
@Test @Test
public void repositoryWithRoot() throws IOException { public void repositoryWithRoot() throws IOException {
InputStream foo = getInputStreamFor("foo"); try (InputStream foo = getInputStreamFor("foo");
InputStream root = getInputStreamFor("root"); InputStream root = getInputStreamFor("root")) {
try {
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder
.create(foo, root).build(); .create(foo, root).build();
validateFoo(repo); validateFoo(repo);
@ -107,17 +93,12 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
"spring.foo.counter", "spring.root.name", "spring.root2.name"); "spring.foo.counter", "spring.root.name", "spring.root2.name");
assertThat(repo.getAllProperties()).hasSize(5); assertThat(repo.getAllProperties()).hasSize(5);
} }
finally {
foo.close();
root.close();
}
} }
@Test @Test
public void severalRepositoriesIdenticalGroups() throws IOException { public void severalRepositoriesIdenticalGroups() throws IOException {
InputStream foo = getInputStreamFor("foo"); try (InputStream foo = getInputStreamFor("foo");
InputStream foo2 = getInputStreamFor("foo2"); InputStream foo2 = getInputStreamFor("foo2")) {
try {
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder
.create(foo, foo2).build(); .create(foo, foo2).build();
assertThat(repo.getAllGroups()).hasSize(1); assertThat(repo.getAllGroups()).hasSize(1);
@ -132,16 +113,11 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
"spring.foo.counter", "spring.foo.enabled", "spring.foo.type"); "spring.foo.counter", "spring.foo.enabled", "spring.foo.type");
assertThat(repo.getAllProperties()).hasSize(5); assertThat(repo.getAllProperties()).hasSize(5);
} }
finally {
foo.close();
foo2.close();
}
} }
@Test @Test
public void emptyGroups() throws IOException { public void emptyGroups() throws IOException {
InputStream in = getInputStreamFor("empty-groups"); try (InputStream in = getInputStreamFor("empty-groups")) {
try {
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder
.create(in).build(); .create(in).build();
validateEmptyGroup(repo); validateEmptyGroup(repo);
@ -149,16 +125,12 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
contains(repo.getAllProperties(), "name", "title"); contains(repo.getAllProperties(), "name", "title");
assertThat(repo.getAllProperties()).hasSize(2); assertThat(repo.getAllProperties()).hasSize(2);
} }
finally {
in.close();
}
} }
@Test @Test
public void builderInstancesAreIsolated() throws IOException { public void builderInstancesAreIsolated() throws IOException {
InputStream foo = getInputStreamFor("foo"); try (InputStream foo = getInputStreamFor("foo");
InputStream bar = getInputStreamFor("bar"); InputStream bar = getInputStreamFor("bar")) {
try {
ConfigurationMetadataRepositoryJsonBuilder builder = ConfigurationMetadataRepositoryJsonBuilder ConfigurationMetadataRepositoryJsonBuilder builder = ConfigurationMetadataRepositoryJsonBuilder
.create(); .create();
ConfigurationMetadataRepository firstRepo = builder.withJsonResource(foo) ConfigurationMetadataRepository firstRepo = builder.withJsonResource(foo)
@ -175,10 +147,6 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
assertThat(secondRepo.getAllGroups()).hasSize(2); assertThat(secondRepo.getAllGroups()).hasSize(2);
assertThat(secondRepo.getAllProperties()).hasSize(6); assertThat(secondRepo.getAllProperties()).hasSize(6);
} }
finally {
foo.close();
bar.close();
}
} }
private void validateFoo(ConfigurationMetadataRepository repo) { private void validateFoo(ConfigurationMetadataRepository repo) {

@ -64,13 +64,10 @@ public class MetadataStore {
public void writeMetadata(ConfigurationMetadata metadata) throws IOException { public void writeMetadata(ConfigurationMetadata metadata) throws IOException {
if (!metadata.getItems().isEmpty()) { if (!metadata.getItems().isEmpty()) {
OutputStream outputStream = createMetadataResource().openOutputStream(); try (OutputStream outputStream = createMetadataResource()
try { .openOutputStream()) {
new JsonMarshaller().write(metadata, outputStream); new JsonMarshaller().write(metadata, outputStream);
} }
finally {
outputStream.close();
}
} }
} }

@ -815,13 +815,9 @@ public class ConfigurationMetadataAnnotationProcessorTests {
} }
private void writeMetadata(File metadataFile, JSONObject metadata) throws Exception { private void writeMetadata(File metadataFile, JSONObject metadata) throws Exception {
FileWriter writer = new FileWriter(metadataFile); try (FileWriter writer = new FileWriter(metadataFile)) {
try {
writer.append(metadata.toString(2)); writer.append(metadata.toString(2));
} }
finally {
writer.close();
}
} }
private static class AdditionalMetadata { private static class AdditionalMetadata {

@ -83,12 +83,11 @@ final class ApplicationPluginAction implements PluginApplicationAction {
} }
private String loadResource(String name) { private String loadResource(String name) {
InputStreamReader reader = new InputStreamReader( try (InputStreamReader reader = new InputStreamReader(
getClass().getResourceAsStream(name)); getClass().getResourceAsStream(name));) {
char[] buffer = new char[4096]; char[] buffer = new char[4096];
int read = 0; int read = 0;
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
try {
while ((read = reader.read(buffer)) > 0) { while ((read = reader.read(buffer)) > 0) {
writer.write(buffer, 0, read); writer.write(buffer, 0, read);
} }
@ -97,14 +96,6 @@ final class ApplicationPluginAction implements PluginApplicationAction {
catch (IOException ex) { catch (IOException ex) {
throw new GradleException("Failed to read '" + name + "'", ex); throw new GradleException("Failed to read '" + name + "'", ex);
} }
finally {
try {
reader.close();
}
catch (IOException ex) {
// Continue
}
}
} }
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2016 the original author or authors. * Copyright 2012-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -48,18 +48,9 @@ public final class BuildPropertiesWriter {
public void writeBuildProperties(ProjectDetails projectDetails) throws IOException { public void writeBuildProperties(ProjectDetails projectDetails) throws IOException {
Properties properties = createBuildInfo(projectDetails); Properties properties = createBuildInfo(projectDetails);
createFileIfNecessary(this.outputFile); createFileIfNecessary(this.outputFile);
FileOutputStream outputStream = new FileOutputStream(this.outputFile); try (FileOutputStream outputStream = new FileOutputStream(this.outputFile)) {
try {
properties.store(outputStream, "Properties"); properties.store(outputStream, "Properties");
} }
finally {
try {
outputStream.close();
}
catch (IOException ex) {
// Continue
}
}
} }
private void createFileIfNecessary(File file) throws IOException { private void createFileIfNecessary(File file) throws IOException {

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2016 the original author or authors. * Copyright 2012-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -64,18 +64,14 @@ public abstract class FileUtils {
*/ */
public static String sha1Hash(File file) throws IOException { public static String sha1Hash(File file) throws IOException {
try { try {
DigestInputStream inputStream = new DigestInputStream( try (DigestInputStream inputStream = new DigestInputStream(
new FileInputStream(file), MessageDigest.getInstance("SHA-1")); new FileInputStream(file), MessageDigest.getInstance("SHA-1"))) {
try {
byte[] buffer = new byte[4098]; byte[] buffer = new byte[4098];
while (inputStream.read(buffer) != -1) { while (inputStream.read(buffer) != -1) {
// Read the entire stream // Read the entire stream
} }
return bytesToHex(inputStream.getMessageDigest().digest()); return bytesToHex(inputStream.getMessageDigest().digest());
} }
finally {
inputStream.close();
}
} }
catch (NoSuchAlgorithmException ex) { catch (NoSuchAlgorithmException ex) {
throw new IllegalStateException(ex); throw new IllegalStateException(ex);

@ -49,7 +49,7 @@ import java.util.zip.ZipEntry;
* @author Phillip Webb * @author Phillip Webb
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
public class JarWriter implements LoaderClassesWriter { public class JarWriter implements LoaderClassesWriter, AutoCloseable {
private static final String NESTED_LOADER_JAR = "META-INF/loader/spring-boot-loader.jar"; private static final String NESTED_LOADER_JAR = "META-INF/loader/spring-boot-loader.jar";
@ -128,23 +128,24 @@ public class JarWriter implements LoaderClassesWriter {
Enumeration<JarEntry> entries = jarFile.entries(); Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) { while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement(); JarEntry entry = entries.nextElement();
ZipHeaderPeekInputStream inputStream = new ZipHeaderPeekInputStream( setUpStoredEntryIfNecessary(jarFile, entry);
jarFile.getInputStream(entry)); try (ZipHeaderPeekInputStream inputStream = new ZipHeaderPeekInputStream(
try { jarFile.getInputStream(entry))) {
if (inputStream.hasZipHeader() && entry.getMethod() != ZipEntry.STORED) {
new CrcAndSize(inputStream).setupStoredEntry(entry);
inputStream.close();
inputStream = new ZipHeaderPeekInputStream(
jarFile.getInputStream(entry));
}
EntryWriter entryWriter = new InputStreamEntryWriter(inputStream, true); EntryWriter entryWriter = new InputStreamEntryWriter(inputStream, true);
JarEntry transformedEntry = entryTransformer.transform(entry); JarEntry transformedEntry = entryTransformer.transform(entry);
if (transformedEntry != null) { if (transformedEntry != null) {
writeEntry(transformedEntry, entryWriter); writeEntry(transformedEntry, entryWriter);
} }
} }
finally { }
inputStream.close(); }
private void setUpStoredEntryIfNecessary(JarFile jarFile, JarEntry entry)
throws IOException {
try (ZipHeaderPeekInputStream inputStream = new ZipHeaderPeekInputStream(
jarFile.getInputStream(entry))) {
if (inputStream.hasZipHeader() && entry.getMethod() != ZipEntry.STORED) {
new CrcAndSize(inputStream).setupStoredEntry(entry);
} }
} }
} }
@ -234,6 +235,7 @@ public class JarWriter implements LoaderClassesWriter {
* Close the writer. * Close the writer.
* @throws IOException if the file cannot be closed * @throws IOException if the file cannot be closed
*/ */
@Override
public void close() throws IOException { public void close() throws IOException {
this.jarOutput.close(); this.jarOutput.close();
} }

@ -141,8 +141,7 @@ public abstract class MainClassFinder {
while (!stack.isEmpty()) { while (!stack.isEmpty()) {
File file = stack.pop(); File file = stack.pop();
if (file.isFile()) { if (file.isFile()) {
InputStream inputStream = new FileInputStream(file); try (InputStream inputStream = new FileInputStream(file)) {
try {
ClassDescriptor classDescriptor = createClassDescriptor(inputStream); ClassDescriptor classDescriptor = createClassDescriptor(inputStream);
if (classDescriptor != null && classDescriptor.isMainMethodFound()) { if (classDescriptor != null && classDescriptor.isMainMethodFound()) {
String className = convertToClassName(file.getAbsolutePath(), String className = convertToClassName(file.getAbsolutePath(),
@ -154,9 +153,6 @@ public abstract class MainClassFinder {
} }
} }
} }
finally {
inputStream.close();
}
} }
if (file.isDirectory()) { if (file.isDirectory()) {
pushAllSorted(stack, file.listFiles(PACKAGE_FOLDER_FILTER)); pushAllSorted(stack, file.listFiles(PACKAGE_FOLDER_FILTER));
@ -240,9 +236,8 @@ public abstract class MainClassFinder {
List<JarEntry> classEntries = getClassEntries(jarFile, classesLocation); List<JarEntry> classEntries = getClassEntries(jarFile, classesLocation);
Collections.sort(classEntries, new ClassEntryComparator()); Collections.sort(classEntries, new ClassEntryComparator());
for (JarEntry entry : classEntries) { for (JarEntry entry : classEntries) {
InputStream inputStream = new BufferedInputStream( try (InputStream inputStream = new BufferedInputStream(
jarFile.getInputStream(entry)); jarFile.getInputStream(entry))) {
try {
ClassDescriptor classDescriptor = createClassDescriptor(inputStream); ClassDescriptor classDescriptor = createClassDescriptor(inputStream);
if (classDescriptor != null && classDescriptor.isMainMethodFound()) { if (classDescriptor != null && classDescriptor.isMainMethodFound()) {
String className = convertToClassName(entry.getName(), String className = convertToClassName(entry.getName(),
@ -254,9 +249,6 @@ public abstract class MainClassFinder {
} }
} }
} }
finally {
inputStream.close();
}
} }
return null; return null;
} }

@ -184,13 +184,9 @@ public class Repackager {
} }
destination.delete(); destination.delete();
try { try {
JarFile jarFileSource = new JarFile(workingSource); try (JarFile jarFileSource = new JarFile(workingSource)) {
try {
repackage(jarFileSource, destination, libraries, launchScript); repackage(jarFileSource, destination, libraries, launchScript);
} }
finally {
jarFileSource.close();
}
} }
finally { finally {
if (!this.backupSource && !this.source.equals(workingSource)) { if (!this.backupSource && !this.source.equals(workingSource)) {
@ -221,21 +217,16 @@ public class Repackager {
} }
private boolean alreadyRepackaged() throws IOException { private boolean alreadyRepackaged() throws IOException {
JarFile jarFile = new JarFile(this.source); try (JarFile jarFile = new JarFile(this.source)) {
try {
Manifest manifest = jarFile.getManifest(); Manifest manifest = jarFile.getManifest();
return (manifest != null && manifest.getMainAttributes() return (manifest != null && manifest.getMainAttributes()
.getValue(BOOT_VERSION_ATTRIBUTE) != null); .getValue(BOOT_VERSION_ATTRIBUTE) != null);
} }
finally {
jarFile.close();
}
} }
private void repackage(JarFile sourceJar, File destination, Libraries libraries, private void repackage(JarFile sourceJar, File destination, Libraries libraries,
LaunchScript launchScript) throws IOException { LaunchScript launchScript) throws IOException {
JarWriter writer = new JarWriter(destination, launchScript); try (JarWriter writer = new JarWriter(destination, launchScript)) {
try {
final List<Library> unpackLibraries = new ArrayList<>(); final List<Library> unpackLibraries = new ArrayList<>();
final List<Library> standardLibraries = new ArrayList<>(); final List<Library> standardLibraries = new ArrayList<>();
libraries.doWithLibraries(new LibraryCallback() { libraries.doWithLibraries(new LibraryCallback() {
@ -256,14 +247,6 @@ public class Repackager {
}); });
repackage(sourceJar, writer, unpackLibraries, standardLibraries); repackage(sourceJar, writer, unpackLibraries, standardLibraries);
} }
finally {
try {
writer.close();
}
catch (Exception ex) {
// Ignore
}
}
} }
private void repackage(JarFile sourceJar, JarWriter writer, private void repackage(JarFile sourceJar, JarWriter writer,
@ -309,13 +292,9 @@ public class Repackager {
private boolean isZip(File file) { private boolean isZip(File file) {
try { try {
FileInputStream fileInputStream = new FileInputStream(file); try (FileInputStream fileInputStream = new FileInputStream(file)) {
try {
return isZip(fileInputStream); return isZip(fileInputStream);
} }
finally {
fileInputStream.close();
}
} }
catch (IOException ex) { catch (IOException ex) {
return false; return false;

@ -102,13 +102,9 @@ public class FileUtilsTests {
@Test @Test
public void hash() throws Exception { public void hash() throws Exception {
File file = this.temporaryFolder.newFile(); File file = this.temporaryFolder.newFile();
OutputStream outputStream = new FileOutputStream(file); try (OutputStream outputStream = new FileOutputStream(file)) {
try {
outputStream.write(new byte[] { 1, 2, 3 }); outputStream.write(new byte[] { 1, 2, 3 });
} }
finally {
outputStream.close();
}
assertThat(FileUtils.sha1Hash(file)) assertThat(FileUtils.sha1Hash(file))
.isEqualTo("7037807198c22a7d2b0807371d763779a84fdfcf"); .isEqualTo("7037807198c22a7d2b0807371d763779a84fdfcf");
} }

@ -455,17 +455,14 @@ public class RepackagerTests {
callback.library(new Library(nestedFile, LibraryScope.COMPILE)); callback.library(new Library(nestedFile, LibraryScope.COMPILE));
} }
}); });
JarFile jarFile = new JarFile(file);
try { try (JarFile jarFile = new JarFile(file)) {
assertThat( assertThat(
jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getMethod()) jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getMethod())
.isEqualTo(ZipEntry.STORED); .isEqualTo(ZipEntry.STORED);
assertThat(jarFile.getEntry("BOOT-INF/classes/test/nested.jar").getMethod()) assertThat(jarFile.getEntry("BOOT-INF/classes/test/nested.jar").getMethod())
.isEqualTo(ZipEntry.STORED); .isEqualTo(ZipEntry.STORED);
} }
finally {
jarFile.close();
}
} }
@Test @Test
@ -508,15 +505,12 @@ public class RepackagerTests {
} }
}); });
JarFile jarFile = new JarFile(file);
try { try (JarFile jarFile = new JarFile(file)) {
assertThat( assertThat(
jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getComment()) jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getComment())
.startsWith("UNPACK:"); .startsWith("UNPACK:");
} }
finally {
jarFile.close();
}
} }
@Test @Test
@ -542,14 +536,10 @@ public class RepackagerTests {
} }
}); });
JarFile jarFile = new JarFile(file); try (JarFile jarFile = new JarFile(file)) {
try {
assertThat(jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getSize()) assertThat(jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getSize())
.isEqualTo(sourceLength); .isEqualTo(sourceLength);
} }
finally {
jarFile.close();
}
} }
@Test @Test
@ -561,13 +551,9 @@ public class RepackagerTests {
File dest = this.temporaryFolder.newFile("dest.jar"); File dest = this.temporaryFolder.newFile("dest.jar");
Repackager repackager = new Repackager(source); Repackager repackager = new Repackager(source);
repackager.repackage(dest, NO_LIBRARIES); repackager.repackage(dest, NO_LIBRARIES);
JarFile jarFile = new JarFile(dest); try (JarFile jarFile = new JarFile(dest)) {
try {
assertThat(jarFile.getEntry("META-INF/INDEX.LIST")).isNull(); assertThat(jarFile.getEntry("META-INF/INDEX.LIST")).isNull();
} }
finally {
jarFile.close();
}
} }
@Test @Test
@ -603,14 +589,10 @@ public class RepackagerTests {
File dest = this.temporaryFolder.newFile("dest.jar"); File dest = this.temporaryFolder.newFile("dest.jar");
Repackager repackager = new Repackager(source); Repackager repackager = new Repackager(source);
repackager.repackage(dest, NO_LIBRARIES); repackager.repackage(dest, NO_LIBRARIES);
JarFile jarFile = new JarFile(dest); try (JarFile jarFile = new JarFile(dest)) {
try {
assertThat(jarFile.getEntry("META-INF/aop.xml")).isNull(); assertThat(jarFile.getEntry("META-INF/aop.xml")).isNull();
assertThat(jarFile.getEntry("BOOT-INF/classes/META-INF/aop.xml")).isNotNull(); assertThat(jarFile.getEntry("BOOT-INF/classes/META-INF/aop.xml")).isNotNull();
} }
finally {
jarFile.close();
}
} }
private boolean hasLauncherClasses(File file) throws IOException { private boolean hasLauncherClasses(File file) throws IOException {
@ -623,23 +605,15 @@ public class RepackagerTests {
} }
private JarEntry getEntry(File file, String name) throws IOException { private JarEntry getEntry(File file, String name) throws IOException {
JarFile jarFile = new JarFile(file); try (JarFile jarFile = new JarFile(file)) {
try {
return jarFile.getJarEntry(name); return jarFile.getJarEntry(name);
} }
finally {
jarFile.close();
}
} }
private Manifest getManifest(File file) throws IOException { private Manifest getManifest(File file) throws IOException {
JarFile jarFile = new JarFile(file); try (JarFile jarFile = new JarFile(file)) {
try {
return jarFile.getManifest(); return jarFile.getManifest();
} }
finally {
jarFile.close();
}
} }
private static class MockLauncherScript implements LaunchScript { private static class MockLauncherScript implements LaunchScript {

@ -65,25 +65,17 @@ public class TestJarFile {
public void addFile(String filename, File fileToCopy) throws IOException { public void addFile(String filename, File fileToCopy) throws IOException {
File file = getFilePath(filename); File file = getFilePath(filename);
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
InputStream inputStream = new FileInputStream(fileToCopy); try (InputStream inputStream = new FileInputStream(fileToCopy)) {
try {
copyToFile(inputStream, file); copyToFile(inputStream, file);
} }
finally {
inputStream.close();
}
} }
public void addManifest(Manifest manifest) throws IOException { public void addManifest(Manifest manifest) throws IOException {
File manifestFile = new File(this.jarSource, "META-INF/MANIFEST.MF"); File manifestFile = new File(this.jarSource, "META-INF/MANIFEST.MF");
manifestFile.getParentFile().mkdirs(); manifestFile.getParentFile().mkdirs();
OutputStream outputStream = new FileOutputStream(manifestFile); try (OutputStream outputStream = new FileOutputStream(manifestFile)) {
try {
manifest.write(outputStream); manifest.write(outputStream);
} }
finally {
outputStream.close();
}
} }
private File getFilePath(String filename) { private File getFilePath(String filename) {
@ -97,13 +89,9 @@ public class TestJarFile {
private void copyToFile(InputStream inputStream, File file) private void copyToFile(InputStream inputStream, File file)
throws FileNotFoundException, IOException { throws FileNotFoundException, IOException {
OutputStream outputStream = new FileOutputStream(file); try (OutputStream outputStream = new FileOutputStream(file)) {
try {
copy(inputStream, outputStream); copy(inputStream, outputStream);
} }
finally {
outputStream.close();
}
} }
private void copy(InputStream in, OutputStream out) throws IOException { private void copy(InputStream in, OutputStream out) throws IOException {

@ -164,35 +164,34 @@ public class PropertiesLauncher extends Launcher {
} }
} }
for (String config : configs) { for (String config : configs) {
InputStream resource = getResource(config); try (InputStream resource = getResource(config)) {
if (resource != null) { if (resource != null) {
debug("Found: " + config); debug("Found: " + config);
try { loadResource(resource);
this.properties.load(resource); // Load the first one we find
return;
} }
finally { else {
resource.close(); debug("Not found: " + config);
}
for (Object key : Collections.list(this.properties.propertyNames())) {
String text = this.properties.getProperty((String) key);
String value = SystemPropertyUtils
.resolvePlaceholders(this.properties, text);
if (value != null) {
this.properties.put(key, value);
}
}
if ("true".equals(getProperty(SET_SYSTEM_PROPERTIES))) {
debug("Adding resolved properties to System properties");
for (Object key : Collections.list(this.properties.propertyNames())) {
String value = this.properties.getProperty((String) key);
System.setProperty((String) key, value);
}
} }
// Load the first one we find
return;
} }
else { }
debug("Not found: " + config); }
private void loadResource(InputStream resource) throws IOException, Exception {
this.properties.load(resource);
for (Object key : Collections.list(this.properties.propertyNames())) {
String text = this.properties.getProperty((String) key);
String value = SystemPropertyUtils.resolvePlaceholders(this.properties, text);
if (value != null) {
this.properties.put(key, value);
}
}
if ("true".equals(getProperty(SET_SYSTEM_PROPERTIES))) {
debug("Adding resolved properties to System properties");
for (Object key : Collections.list(this.properties.propertyNames())) {
String value = this.properties.getProperty((String) key);
System.setProperty((String) key, value);
} }
} }
} }

@ -91,13 +91,9 @@ public class ExplodedArchive implements Archive {
@Override @Override
public Manifest getManifest() throws IOException { public Manifest getManifest() throws IOException {
if (this.manifest == null && this.manifestFile.exists()) { if (this.manifest == null && this.manifestFile.exists()) {
FileInputStream inputStream = new FileInputStream(this.manifestFile); try (FileInputStream inputStream = new FileInputStream(this.manifestFile)) {
try {
this.manifest = new Manifest(inputStream); this.manifest = new Manifest(inputStream);
} }
finally {
inputStream.close();
}
} }
return this.manifest; return this.manifest;
} }

@ -145,23 +145,15 @@ public class JarFileArchive implements Archive {
} }
private void unpack(JarEntry entry, File file) throws IOException { private void unpack(JarEntry entry, File file) throws IOException {
InputStream inputStream = this.jarFile.getInputStream(entry, ResourceAccess.ONCE); try (InputStream inputStream = this.jarFile.getInputStream(entry,
try { ResourceAccess.ONCE);
OutputStream outputStream = new FileOutputStream(file); OutputStream outputStream = new FileOutputStream(file)) {
try { byte[] buffer = new byte[BUFFER_SIZE];
byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1;
int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) {
while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead);
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
}
finally {
outputStream.close();
} }
} outputStream.flush();
finally {
inputStream.close();
} }
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2013 the original author or authors. * Copyright 2012-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -35,13 +35,9 @@ final class Bytes {
} }
public static byte[] get(RandomAccessData data) throws IOException { public static byte[] get(RandomAccessData data) throws IOException {
InputStream inputStream = data.getInputStream(ResourceAccess.ONCE); try (InputStream inputStream = data.getInputStream(ResourceAccess.ONCE)) {
try {
return get(inputStream, data.getSize()); return get(inputStream, data.getSize());
} }
finally {
inputStream.close();
}
} }
public static byte[] get(InputStream inputStream, long length) throws IOException { public static byte[] get(InputStream inputStream, long length) throws IOException {

@ -160,17 +160,13 @@ public class JarFile extends java.util.jar.JarFile {
manifest = new JarFile(this.getRootJarFile()).getManifest(); manifest = new JarFile(this.getRootJarFile()).getManifest();
} }
else { else {
InputStream inputStream = getInputStream(MANIFEST_NAME, try (InputStream inputStream = getInputStream(MANIFEST_NAME,
ResourceAccess.ONCE); ResourceAccess.ONCE)) {
if (inputStream == null) { if (inputStream == null) {
return null; return null;
} }
try {
manifest = new Manifest(inputStream); manifest = new Manifest(inputStream);
} }
finally {
inputStream.close();
}
} }
this.manifest = new SoftReference<>(manifest); this.manifest = new SoftReference<>(manifest);
} }
@ -335,9 +331,8 @@ public class JarFile extends java.util.jar.JarFile {
// Fallback to JarInputStream to obtain certificates, not fast but hopefully not // Fallback to JarInputStream to obtain certificates, not fast but hopefully not
// happening that often. // happening that often.
try { try {
JarInputStream inputStream = new JarInputStream( try (JarInputStream inputStream = new JarInputStream(
getData().getInputStream(ResourceAccess.ONCE)); getData().getInputStream(ResourceAccess.ONCE))) {
try {
java.util.jar.JarEntry certEntry = inputStream.getNextJarEntry(); java.util.jar.JarEntry certEntry = inputStream.getNextJarEntry();
while (certEntry != null) { while (certEntry != null) {
inputStream.closeEntry(); inputStream.closeEntry();
@ -348,9 +343,6 @@ public class JarFile extends java.util.jar.JarFile {
certEntry = inputStream.getNextJarEntry(); certEntry = inputStream.getNextJarEntry();
} }
} }
finally {
inputStream.close();
}
} }
catch (IOException ex) { catch (IOException ex) {
throw new IllegalStateException(ex); throw new IllegalStateException(ex);

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2013 the original author or authors. * Copyright 2012-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -40,8 +40,7 @@ public abstract class TestJarCreator {
public static void createTestJar(File file, boolean unpackNested) throws Exception { public static void createTestJar(File file, boolean unpackNested) throws Exception {
FileOutputStream fileOutputStream = new FileOutputStream(file); FileOutputStream fileOutputStream = new FileOutputStream(file);
JarOutputStream jarOutputStream = new JarOutputStream(fileOutputStream); try (JarOutputStream jarOutputStream = new JarOutputStream(fileOutputStream)) {
try {
writeManifest(jarOutputStream, "j1"); writeManifest(jarOutputStream, "j1");
writeEntry(jarOutputStream, "1.dat", 1); writeEntry(jarOutputStream, "1.dat", 1);
writeEntry(jarOutputStream, "2.dat", 2); writeEntry(jarOutputStream, "2.dat", 2);
@ -53,9 +52,6 @@ public abstract class TestJarCreator {
writeNestedEntry("nested.jar", unpackNested, jarOutputStream); writeNestedEntry("nested.jar", unpackNested, jarOutputStream);
writeNestedEntry("another-nested.jar", unpackNested, jarOutputStream); writeNestedEntry("another-nested.jar", unpackNested, jarOutputStream);
} }
finally {
jarOutputStream.close();
}
} }
private static void writeNestedEntry(String name, boolean unpackNested, private static void writeNestedEntry(String name, boolean unpackNested,

@ -205,21 +205,18 @@ public class StartMojo extends AbstractRunMojo {
throws IOException, MojoFailureException, MojoExecutionException { throws IOException, MojoFailureException, MojoExecutionException {
try { try {
getLog().debug("Connecting to local MBeanServer at port " + this.jmxPort); getLog().debug("Connecting to local MBeanServer at port " + this.jmxPort);
JMXConnector connector = execute(this.wait, this.maxAttempts, try (JMXConnector connector = execute(this.wait, this.maxAttempts,
new CreateJmxConnector(this.jmxPort)); new CreateJmxConnector(this.jmxPort))) {
if (connector == null) { if (connector == null) {
throw new MojoExecutionException( throw new MojoExecutionException(
"JMX MBean server was not reachable before the configured " "JMX MBean server was not reachable before the configured "
+ "timeout (" + (this.wait * this.maxAttempts) + "ms"); + "timeout (" + (this.wait * this.maxAttempts)
} + "ms");
getLog().debug("Connected to local MBeanServer at port " + this.jmxPort); }
try { getLog().debug("Connected to local MBeanServer at port " + this.jmxPort);
MBeanServerConnection connection = connector.getMBeanServerConnection(); MBeanServerConnection connection = connector.getMBeanServerConnection();
doWaitForSpringApplication(connection); doWaitForSpringApplication(connection);
} }
finally {
connector.close();
}
} }
catch (IOException ex) { catch (IOException ex) {
throw ex; throw ex;

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2016 the original author or authors. * Copyright 2012-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -110,14 +110,11 @@ public class StopMojo extends AbstractMojo {
private void stopForkedProcess() private void stopForkedProcess()
throws IOException, MojoFailureException, MojoExecutionException { throws IOException, MojoFailureException, MojoExecutionException {
JMXConnector connector = SpringApplicationAdminClient.connect(this.jmxPort); try (JMXConnector connector = SpringApplicationAdminClient
try { .connect(this.jmxPort)) {
MBeanServerConnection connection = connector.getMBeanServerConnection(); MBeanServerConnection connection = connector.getMBeanServerConnection();
doStop(connection); doStop(connection);
} }
finally {
connector.close();
}
} }
private void stop() throws IOException, MojoFailureException, MojoExecutionException { private void stop() throws IOException, MojoFailureException, MojoExecutionException {

@ -198,14 +198,10 @@ public final class Verify {
.startsWith(new String(new byte[] { 0x50, 0x4b, 0x03, 0x04 })); .startsWith(new String(new byte[] { 0x50, 0x4b, 0x03, 0x04 }));
} }
ZipFile zipFile = new ZipFile(this.file); try (ZipFile zipFile = new ZipFile(this.file)) {
try {
ArchiveVerifier verifier = new ArchiveVerifier(zipFile); ArchiveVerifier verifier = new ArchiveVerifier(zipFile);
verifyZipEntries(verifier); verifyZipEntries(verifier);
} }
finally {
zipFile.close();
}
} }
protected void verifyZipEntries(ArchiveVerifier verifier) throws Exception { protected void verifyZipEntries(ArchiveVerifier verifier) throws Exception {

@ -125,14 +125,10 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner {
} }
private String[] getClassPath(URL booterJar) throws Exception { private String[] getClassPath(URL booterJar) throws Exception {
JarFile jarFile = new JarFile(new File(booterJar.toURI())); try (JarFile jarFile = new JarFile(new File(booterJar.toURI()))) {
try {
return StringUtils.delimitedListToStringArray(jarFile.getManifest() return StringUtils.delimitedListToStringArray(jarFile.getManifest()
.getMainAttributes().getValue(Attributes.Name.CLASS_PATH), " "); .getMainAttributes().getValue(Attributes.Name.CLASS_PATH), " ");
} }
finally {
jarFile.close();
}
} }
private URL[] processUrls(URL[] urls, Class<?> testClass) throws Exception { private URL[] processUrls(URL[] urls, Class<?> testClass) throws Exception {

@ -36,6 +36,7 @@ import org.springframework.util.StringUtils;
* both Jar Files, Exploded Archives and directly running applications. * both Jar Files, Exploded Archives and directly running applications.
* *
* @author Phillip Webb * @author Phillip Webb
* @author Raja Kolli
* @since 1.2.0 * @since 1.2.0
*/ */
public class ApplicationHome { public class ApplicationHome {

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2015 the original author or authors. * Copyright 2012-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -81,13 +81,9 @@ public class ApplicationPid {
public void write(File file) throws IOException { public void write(File file) throws IOException {
Assert.state(this.pid != null, "No PID available"); Assert.state(this.pid != null, "No PID available");
createParentFolder(file); createParentFolder(file);
FileWriter writer = new FileWriter(file); try (FileWriter writer = new FileWriter(file)) {
try {
writer.append(this.pid); writer.append(this.pid);
} }
finally {
writer.close();
}
} }
private void createParentFolder(File file) { private void createParentFolder(File file) {

@ -44,6 +44,7 @@ import org.springframework.util.Assert;
* @author Craig Burke * @author Craig Burke
* @author Phillip Webb * @author Phillip Webb
* @author Madhura Bhave * @author Madhura Bhave
* @author Raja Kolli
* @since 1.4.0 * @since 1.4.0
*/ */
public class ImageBanner implements Banner { public class ImageBanner implements Banner {

@ -37,6 +37,7 @@ import org.springframework.core.ConfigurableObjectInputStream;
* *
* @author Phillip Webb * @author Phillip Webb
* @author Peter Leibiger * @author Peter Leibiger
* @author Raja Kolli
*/ */
class FileSessionPersistence implements SessionPersistenceManager { class FileSessionPersistence implements SessionPersistenceManager {
@ -59,13 +60,10 @@ class FileSessionPersistence implements SessionPersistenceManager {
private void save(Map<String, PersistentSession> sessionData, File file) private void save(Map<String, PersistentSession> sessionData, File file)
throws IOException { throws IOException {
ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(file)); try (ObjectOutputStream stream = new ObjectOutputStream(
try { new FileOutputStream(file))) {
save(sessionData, stream); save(sessionData, stream);
} }
finally {
stream.close();
}
} }
private void save(Map<String, PersistentSession> sessionData, private void save(Map<String, PersistentSession> sessionData,

@ -83,13 +83,9 @@ public class MustacheView extends AbstractTemplateView {
} }
private Template createTemplate(Resource resource) throws IOException { private Template createTemplate(Resource resource) throws IOException {
Reader reader = getReader(resource); try (Reader reader = getReader(resource)) {
try {
return this.compiler.compile(reader); return this.compiler.compile(reader);
} }
finally {
reader.close();
}
} }
private Reader getReader(Resource resource) throws IOException { private Reader getReader(Resource resource) throws IOException {

@ -112,18 +112,12 @@ public class ConfigurationWarningsApplicationContextInitializerTests {
} }
private void load(Class<?> configClass) { private void load(Class<?> configClass) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
new TestConfigurationWarningsApplicationContextInitializer().initialize(context); new TestConfigurationWarningsApplicationContextInitializer()
context.register(configClass); .initialize(context);
try { context.register(configClass);
context.refresh(); context.refresh();
} }
catch (Exception ex) {
ex.printStackTrace();
}
finally {
context.close();
}
} }
/** /**

@ -196,12 +196,8 @@ public class ConfigFileApplicationListenerTests {
try { try {
Properties properties = new Properties(); Properties properties = new Properties();
properties.put("the.property", "fromlocalfile"); properties.put("the.property", "fromlocalfile");
OutputStream out = new FileOutputStream(localFile); try (OutputStream outputStream = new FileOutputStream(localFile)) {
try { properties.store(outputStream, "");
properties.store(out, "");
}
finally {
out.close();
} }
this.initializer.postProcessEnvironment(this.environment, this.application); this.initializer.postProcessEnvironment(this.environment, this.application);
String property = this.environment.getProperty("the.property"); String property = this.environment.getProperty("the.property");

@ -44,15 +44,11 @@ public class LoggingApplicationListenerIntegrationTests {
@Test @Test
public void loggingSystemRegisteredInTheContext() { public void loggingSystemRegisteredInTheContext() {
ConfigurableApplicationContext context = new SpringApplicationBuilder( try (ConfigurableApplicationContext context = new SpringApplicationBuilder(
SampleService.class).web(WebApplicationType.NONE).run(); SampleService.class).web(WebApplicationType.NONE).run()) {
try {
SampleService service = context.getBean(SampleService.class); SampleService service = context.getBean(SampleService.class);
assertThat(service.loggingSystem).isNotNull(); assertThat(service.loggingSystem).isNotNull();
} }
finally {
context.close();
}
} }
@Test @Test

@ -33,7 +33,7 @@ import static org.junit.Assert.fail;
* *
* @author Stephane Nicoll * @author Stephane Nicoll
*/ */
public class BeanCreationFailureAnalyzerTest { public class BeanCreationFailureAnalyzerTests {
private final FailureAnalyzer analyzer = new BeanCreationFailureAnalyzer(); private final FailureAnalyzer analyzer = new BeanCreationFailureAnalyzer();
@ -55,20 +55,14 @@ public class BeanCreationFailureAnalyzerTest {
} }
private Exception createFailure(Class<?> configuration) { private Exception createFailure(Class<?> configuration) {
ConfigurableApplicationContext context = null; try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(
try { configuration)) {
context = new AnnotationConfigApplicationContext(configuration); fail("Expected failure did not occur");
return null;
} }
catch (Exception ex) { catch (Exception ex) {
return ex; return ex;
} }
finally {
if (context != null) {
context.close();
}
}
fail("Expected failure did not occur");
return null;
} }
@Configuration @Configuration

@ -118,9 +118,8 @@ public class BeanCurrentlyInCreationFailureAnalyzerTests {
private List<String> readDescriptionLines(FailureAnalysis analysis) private List<String> readDescriptionLines(FailureAnalysis analysis)
throws IOException { throws IOException {
BufferedReader lineReader = new BufferedReader( try (BufferedReader lineReader = new BufferedReader(
new StringReader(analysis.getDescription())); new StringReader(analysis.getDescription()))) {
try {
List<String> lines = new ArrayList<>(); List<String> lines = new ArrayList<>();
String line; String line;
while ((line = lineReader.readLine()) != null) { while ((line = lineReader.readLine()) != null) {
@ -128,9 +127,6 @@ public class BeanCurrentlyInCreationFailureAnalyzerTests {
} }
return lines; return lines;
} }
finally {
lineReader.close();
}
} }
private FailureAnalysis performAnalysis(Class<?> configuration) { private FailureAnalysis performAnalysis(Class<?> configuration) {
@ -140,21 +136,15 @@ public class BeanCurrentlyInCreationFailureAnalyzerTests {
} }
private Exception createFailure(Class<?> configuration) { private Exception createFailure(Class<?> configuration) {
ConfigurableApplicationContext context = null; try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(
try { configuration);) {
context = new AnnotationConfigApplicationContext(configuration); fail("Expected failure did not occur");
return null;
} }
catch (Exception ex) { catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
return ex; return ex;
} }
finally {
if (context != null) {
context.close();
}
}
fail("Expected failure did not occur");
return null;
} }
@org.springframework.context.annotation.Configuration @org.springframework.context.annotation.Configuration

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2016 the original author or authors. * Copyright 2012-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -57,20 +57,14 @@ public class BeanNotOfRequiredTypeFailureAnalyzerTests {
} }
private Exception createFailure(Class<?> configuration) { private Exception createFailure(Class<?> configuration) {
ConfigurableApplicationContext context = null; try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(
try { configuration)) {
context = new AnnotationConfigApplicationContext(configuration); fail("Expected failure did not occur");
return null;
} }
catch (Exception ex) { catch (Exception ex) {
return ex; return ex;
} }
finally {
if (context != null) {
context.close();
}
}
fail("Expected failure did not occur");
return null;
} }
@Configuration @Configuration

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2016 the original author or authors. * Copyright 2012-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -102,20 +102,19 @@ public class NoUniqueBeanDefinitionFailureAnalyzerTests {
} }
private BeanCreationException createFailure(Class<?> consumer) { private BeanCreationException createFailure(Class<?> consumer) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
context.register(DuplicateBeansProducer.class, consumer); context.register(DuplicateBeansProducer.class, consumer);
context.setParent(new AnnotationConfigApplicationContext(ParentProducer.class)); context.setParent(
try { new AnnotationConfigApplicationContext(ParentProducer.class));
context.refresh(); try {
context.refresh();
}
catch (BeanCreationException ex) {
this.analyzer.setBeanFactory(context.getBeanFactory());
return ex;
}
return null; return null;
} }
catch (BeanCreationException ex) {
this.analyzer.setBeanFactory(context.getBeanFactory());
return ex;
}
finally {
context.close();
}
} }
private FailureAnalysis analyzeFailure(BeanCreationException failure) { private FailureAnalysis analyzeFailure(BeanCreationException failure) {

@ -101,15 +101,11 @@ public class ServletWebServerMvcIntegrationTests {
ClientHttpRequest request = clientHttpRequestFactory.createRequest(new URI( ClientHttpRequest request = clientHttpRequestFactory.createRequest(new URI(
"http://localhost:" + context.getWebServer().getPort() + resourcePath), "http://localhost:" + context.getWebServer().getPort() + resourcePath),
HttpMethod.GET); HttpMethod.GET);
ClientHttpResponse response = request.execute(); try (ClientHttpResponse response = request.execute()) {
try {
String actual = StreamUtils.copyToString(response.getBody(), String actual = StreamUtils.copyToString(response.getBody(),
Charset.forName("UTF-8")); Charset.forName("UTF-8"));
assertThat(actual).isEqualTo("Hello World"); assertThat(actual).isEqualTo("Hello World");
} }
finally {
response.close();
}
} }
// Simple main method for testing in a browser // Simple main method for testing in a browser

@ -122,6 +122,7 @@ import static org.mockito.Mockito.verify;
* @author Phillip Webb * @author Phillip Webb
* @author Greg Turnquist * @author Greg Turnquist
* @author Andy Wilkinson * @author Andy Wilkinson
* @author Raja Kolli
*/ */
public abstract class AbstractServletWebServerFactoryTests { public abstract class AbstractServletWebServerFactoryTests {
@ -1058,13 +1059,9 @@ public abstract class AbstractServletWebServerFactoryTests {
protected String getResponse(String url, HttpMethod method, String... headers) protected String getResponse(String url, HttpMethod method, String... headers)
throws IOException, URISyntaxException { throws IOException, URISyntaxException {
ClientHttpResponse response = getClientResponse(url, method, headers); try (ClientHttpResponse response = getClientResponse(url, method, headers)) {
try {
return StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8")); return StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8"));
} }
finally {
response.close();
}
} }
protected String getResponse(String url, protected String getResponse(String url,
@ -1076,14 +1073,10 @@ public abstract class AbstractServletWebServerFactoryTests {
protected String getResponse(String url, HttpMethod method, protected String getResponse(String url, HttpMethod method,
HttpComponentsClientHttpRequestFactory requestFactory, String... headers) HttpComponentsClientHttpRequestFactory requestFactory, String... headers)
throws IOException, URISyntaxException { throws IOException, URISyntaxException {
ClientHttpResponse response = getClientResponse(url, method, requestFactory, try (ClientHttpResponse response = getClientResponse(url, method, requestFactory,
headers); headers)) {
try {
return StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8")); return StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8"));
} }
finally {
response.close();
}
} }
protected ClientHttpResponse getClientResponse(String url, String... headers) protected ClientHttpResponse getClientResponse(String url, String... headers)

@ -102,15 +102,11 @@ public class SpringBootServletInitializerTests {
@Override @Override
public void onStartup(ServletContext servletContext) public void onStartup(ServletContext servletContext)
throws ServletException { throws ServletException {
AbstractApplicationContext context = (AbstractApplicationContext) new WithErrorPageFilterNotRegistered() try (AbstractApplicationContext context = (AbstractApplicationContext) new WithErrorPageFilterNotRegistered()
.createRootApplicationContext(servletContext); .createRootApplicationContext(servletContext)) {
try {
assertThat(context.getBeansOfType(ErrorPageFilter.class)) assertThat(context.getBeansOfType(ErrorPageFilter.class))
.hasSize(0); .hasSize(0);
} }
finally {
context.close();
}
} }
}); });
try { try {
@ -124,14 +120,10 @@ public class SpringBootServletInitializerTests {
@Test @Test
public void executableWarThatUsesServletInitializerDoesNotHaveErrorPageFilterConfigured() public void executableWarThatUsesServletInitializerDoesNotHaveErrorPageFilterConfigured()
throws Exception { throws Exception {
ConfigurableApplicationContext context = new SpringApplication( try (ConfigurableApplicationContext context = new SpringApplication(
ExecutableWar.class).run(); ExecutableWar.class).run()) {
try {
assertThat(context.getBeansOfType(ErrorPageFilter.class)).hasSize(0); assertThat(context.getBeansOfType(ErrorPageFilter.class)).hasSize(0);
} }
finally {
context.close();
}
} }
@Test @Test

Loading…
Cancel
Save