From d5438c299c39fa249874847a96f1d80cef032ab0 Mon Sep 17 00:00:00 2001 From: Andy Wilkinson Date: Tue, 23 May 2017 17:24:01 +0100 Subject: [PATCH] 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 --- .../hypermedia/EndpointDocumentation.java | 9 ++-- .../endpoint/mvc/HeapdumpMvcEndpoint.java | 8 +-- .../actuate/health/JmsHealthIndicator.java | 8 +-- ...CacheStatisticsAutoConfigurationTests.java | 1 + .../EndpointWebMvcAutoConfigurationTests.java | 28 ++++------ .../endpoint/TomcatPublicMetricsTests.java | 8 +-- .../export/MetricCopyExporterTests.java | 14 ++--- .../cache/InfinispanCacheConfiguration.java | 1 + .../EmbeddedLdapAutoConfiguration.java | 1 + ...icationAdminJmxAutoConfigurationTests.java | 21 +++----- .../ConditionalOnSingleCandidateTests.java | 12 ++--- .../MessageSourceAutoConfigurationTests.java | 8 +-- ...DataAutoConfigurationIntegrationTests.java | 6 +-- ...uchBeanDefinitionFailureAnalyzerTests.java | 12 ++--- .../FreeMarkerAutoConfigurationTests.java | 12 ++--- .../EmbeddedDataSourceConfigurationTests.java | 16 ++---- .../ArtemisAutoConfigurationTests.java | 21 +++----- .../EmbeddedMongoAutoConfigurationTests.java | 8 +-- .../SecurityAutoConfigurationTests.java | 16 +++--- ...ConfigurationEarlyInitializationTests.java | 7 +-- .../SecurityFilterAutoConfigurationTests.java | 9 +--- ...hymeleafServletAutoConfigurationTests.java | 13 ++--- .../infrastructure/CommandLineInvoker.java | 12 +---- .../cli/command/archive/ArchiveCommand.java | 6 +-- .../cli/command/init/ProjectGenerator.java | 11 ++-- .../install/GroovyGrabDependencyResolver.java | 9 +--- .../boot/cli/command/install/Installer.java | 9 +--- .../compiler/ExtendedGroovyClassLoader.java | 8 +-- .../cli/command/init/InitCommandTests.java | 10 ++-- .../init/InitializrServiceMetadataTests.java | 6 +-- .../devtools/livereload/LiveReloadServer.java | 14 ++--- .../devtools/tunnel/client/TunnelClient.java | 8 +-- .../src/test/java/sample/layout/Verify.java | 8 +-- .../SampleIntegrationApplicationTests.java | 6 +-- .../jetty/SampleJettyApplicationTests.java | 11 +--- .../tomcat/SampleTomcatApplicationTests.java | 8 +-- .../SampleUndertowApplicationTests.java | 9 ++-- .../TestDatabaseAutoConfigurationTests.java | 8 +-- .../restdocs/ContentContainingCondition.java | 16 +----- .../AutoConfigureAnnotationProcessor.java | 6 +-- ...tConditionMetadataAnnotationProcessor.java | 6 +-- ...ionMetadataRepositoryJsonBuilderTests.java | 54 ++++--------------- .../configurationprocessor/MetadataStore.java | 7 +-- ...ationMetadataAnnotationProcessorTests.java | 6 +-- .../plugin/ApplicationPluginAction.java | 19 ++----- .../loader/tools/BuildPropertiesWriter.java | 13 +---- .../boot/loader/tools/FileUtils.java | 10 ++-- .../boot/loader/tools/JarWriter.java | 26 ++++----- .../boot/loader/tools/MainClassFinder.java | 14 ++--- .../boot/loader/tools/Repackager.java | 29 ++-------- .../boot/loader/tools/FileUtilsTests.java | 6 +-- .../boot/loader/tools/RepackagerTests.java | 44 ++++----------- .../boot/loader/tools/TestJarFile.java | 18 ++----- .../boot/loader/PropertiesLauncher.java | 51 +++++++++--------- .../boot/loader/archive/ExplodedArchive.java | 6 +-- .../boot/loader/archive/JarFileArchive.java | 24 +++------ .../boot/loader/jar/Bytes.java | 8 +-- .../boot/loader/jar/JarFile.java | 22 +++----- .../boot/loader/TestJarCreator.java | 8 +-- .../springframework/boot/maven/StartMojo.java | 21 ++++---- .../springframework/boot/maven/StopMojo.java | 9 ++-- .../springframework/boot/maven/Verify.java | 6 +-- .../classpath/ModifiedClassPathRunner.java | 6 +-- .../springframework/boot/ApplicationHome.java | 1 + .../springframework/boot/ApplicationPid.java | 8 +-- .../org/springframework/boot/ImageBanner.java | 1 + .../undertow/FileSessionPersistence.java | 8 ++- .../boot/web/servlet/view/MustacheView.java | 6 +-- ...ngsApplicationContextInitializerTests.java | 14 ++--- .../ConfigFileApplicationListenerTests.java | 8 +-- ...ngApplicationListenerIntegrationTests.java | 8 +-- ... => BeanCreationFailureAnalyzerTests.java} | 16 ++---- ...rrentlyInCreationFailureAnalyzerTests.java | 22 +++----- ...NotOfRequiredTypeFailureAnalyzerTests.java | 16 ++---- ...queBeanDefinitionFailureAnalyzerTests.java | 25 +++++---- .../ServletWebServerMvcIntegrationTests.java | 6 +-- .../AbstractServletWebServerFactoryTests.java | 15 ++---- .../SpringBootServletInitializerTests.java | 16 ++---- 78 files changed, 284 insertions(+), 703 deletions(-) rename spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/{BeanCreationFailureAnalyzerTest.java => BeanCreationFailureAnalyzerTests.java} (88%) diff --git a/spring-boot-actuator-docs/src/restdoc/java/org/springframework/boot/actuate/hypermedia/EndpointDocumentation.java b/spring-boot-actuator-docs/src/restdoc/java/org/springframework/boot/actuate/hypermedia/EndpointDocumentation.java index 01a4048bf96..bd452e2cca2 100644 --- a/spring-boot-actuator-docs/src/restdoc/java/org/springframework/boot/actuate/hypermedia/EndpointDocumentation.java +++ b/spring-boot-actuator-docs/src/restdoc/java/org/springframework/boot/actuate/hypermedia/EndpointDocumentation.java @@ -132,7 +132,8 @@ public class EndpointDocumentation { @Test public void auditEvents() throws Exception { 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)) .andExpect(status().isOk()).andDo(document("auditevents")); } @@ -188,15 +189,11 @@ public class EndpointDocumentation { } File file = new File(RESTDOCS_OUTPUT_DIR + "/endpoints.adoc"); file.getParentFile().mkdirs(); - PrintWriter writer = new PrintWriter(file, "UTF-8"); - try { + try (PrintWriter writer = new PrintWriter(file, "UTF-8")) { Template template = this.templates.createTemplate( new File("src/restdoc/resources/templates/endpoints.adoc.tpl")); template.make(model).writeTo(writer); } - finally { - writer.close(); - } } private Collection getEndpoints() { diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/HeapdumpMvcEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/HeapdumpMvcEndpoint.java index dbd168368d3..a89e8152074 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/HeapdumpMvcEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/HeapdumpMvcEndpoint.java @@ -51,7 +51,7 @@ import org.springframework.web.bind.annotation.ResponseStatus; * * @author Lari Hotari * @author Phillip Webb - * @author rajakolli + * @author Raja Kolli * @since 1.4.0 */ @ConfigurationProperties(prefix = "endpoints.heapdump") @@ -146,9 +146,9 @@ public class HeapdumpMvcEndpoint extends AbstractNamedMvcEndpoint { response.setHeader("Content-Disposition", "attachment; filename=\"" + (heapDumpFile.getName() + ".gz") + "\""); try (InputStream in = new FileInputStream(heapDumpFile); - GZIPOutputStream out = new GZIPOutputStream(response.getOutputStream())) { - StreamUtils.copy(in, out); - out.finish(); + GZIPOutputStream out = new GZIPOutputStream(response.getOutputStream())) { + StreamUtils.copy(in, out); + out.finish(); } catch (NullPointerException | FileNotFoundException ex) { } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/JmsHealthIndicator.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/JmsHealthIndicator.java index 401ccf4e5c4..a83435076d7 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/JmsHealthIndicator.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/JmsHealthIndicator.java @@ -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"); * you may not use this file except in compliance with the License. @@ -35,15 +35,11 @@ public class JmsHealthIndicator extends AbstractHealthIndicator { @Override protected void doHealthCheck(Health.Builder builder) throws Exception { - Connection connection = this.connectionFactory.createConnection(); - try { + try (Connection connection = this.connectionFactory.createConnection()) { connection.start(); builder.up().withDetail("provider", connection.getMetaData().getJMSProviderName()); } - finally { - connection.close(); - } } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/CacheStatisticsAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/CacheStatisticsAutoConfigurationTests.java index 18856a10d11..32434a5f552 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/CacheStatisticsAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/CacheStatisticsAutoConfigurationTests.java @@ -61,6 +61,7 @@ import static org.assertj.core.api.Assertions.offset; * * @author Stephane Nicoll * @author Eddú Meléndez + * @author Raja Kolli */ @SuppressWarnings({ "rawtypes", "unchecked" }) public class CacheStatisticsAutoConfigurationTests { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfigurationTests.java index e8c4734539a..f78301974f7 100755 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfigurationTests.java @@ -338,9 +338,8 @@ public class EndpointWebMvcAutoConfigurationTests { @Test public void specificPortsViaPropertiesWithClash() throws Exception { int managementPort = ports.get().management; - ServerSocket serverSocket = new ServerSocket(); - serverSocket.bind(new InetSocketAddress(managementPort)); - try { + try (ServerSocket serverSocket = new ServerSocket()) { + serverSocket.bind(new InetSocketAddress(managementPort)); EnvironmentTestUtils.addEnvironment(this.applicationContext, "server.port:" + ports.get().server, "management.port:" + ports.get().management); @@ -350,9 +349,6 @@ public class EndpointWebMvcAutoConfigurationTests { this.thrown.expect(WebServerException.class); this.applicationContext.refresh(); } - finally { - serverSocket.close(); - } } @Test @@ -683,23 +679,17 @@ public class EndpointWebMvcAutoConfigurationTests { httpClient); ClientHttpRequest request = requestFactory.createRequest( new URI(scheme + "://localhost:" + port + url), HttpMethod.GET); - try { - ClientHttpResponse response = request.execute(); + try (ClientHttpResponse response = request.execute()) { if (HttpStatus.NOT_FOUND.equals(response.getStatusCode())) { throw new FileNotFoundException(); } - try { - String actual = StreamUtils.copyToString(response.getBody(), - Charset.forName("UTF-8")); - if (expected instanceof Matcher) { - assertThat(actual).is(Matched.by((Matcher) expected)); - } - else { - assertThat(actual).isEqualTo(expected); - } + String actual = StreamUtils.copyToString(response.getBody(), + Charset.forName("UTF-8")); + if (expected instanceof Matcher) { + assertThat(actual).is(Matched.by((Matcher) expected)); } - finally { - response.close(); + else { + assertThat(actual).isEqualTo(expected); } } catch (Exception ex) { diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/TomcatPublicMetricsTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/TomcatPublicMetricsTests.java index e5e23bf48b5..3a073929fce 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/TomcatPublicMetricsTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/TomcatPublicMetricsTests.java @@ -39,9 +39,8 @@ public class TomcatPublicMetricsTests { @Test public void tomcatMetrics() throws Exception { - AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext( - Config.class); - try { + try (AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext( + Config.class)) { TomcatPublicMetrics tomcatMetrics = context .getBean(TomcatPublicMetrics.class); Iterator> metrics = tomcatMetrics.metrics().iterator(); @@ -49,9 +48,6 @@ public class TomcatPublicMetricsTests { assertThat(metrics.next().getName()).isEqualTo("httpsessions.active"); assertThat(metrics.hasNext()).isFalse(); } - finally { - context.close(); - } } @Configuration diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/MetricCopyExporterTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/MetricCopyExporterTests.java index 2bdc160b522..e02485950cd 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/MetricCopyExporterTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/MetricCopyExporterTests.java @@ -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"); * you may not use this file except in compliance with the License. @@ -62,18 +62,14 @@ public class MetricCopyExporterTests { @Test public void counterWithGaugeWriter() throws Exception { SimpleGaugeWriter writer = new SimpleGaugeWriter(); - MetricCopyExporter exporter = new MetricCopyExporter(this.reader, writer); - try { + try (MetricCopyExporter customExporter = new MetricCopyExporter(this.reader, writer)) { this.reader.increment(new Delta("counter.foo", 2)); - exporter.export(); + customExporter.export(); this.reader.increment(new Delta("counter.foo", 3)); - exporter.export(); - exporter.flush(); + customExporter.export(); + customExporter.flush(); assertThat(writer.getValue().getValue()).isEqualTo(5L); } - finally { - exporter.close(); - } } @Test diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/InfinispanCacheConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/InfinispanCacheConfiguration.java index 6392ab5cfde..440627d2672 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/InfinispanCacheConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/InfinispanCacheConfiguration.java @@ -40,6 +40,7 @@ import org.springframework.util.CollectionUtils; * * @author Eddú Meléndez * @author Stephane Nicoll + * @author Raja Kolli * @since 1.3.0 */ @Configuration diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfiguration.java index 4d0f9920ece..e43fd0bf921 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfiguration.java @@ -57,6 +57,7 @@ import org.springframework.util.StringUtils; * * @author Eddú Meléndez * @author Mathieu Ouellet + * @author Raja Kolli * @since 1.5.0 */ @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java index f37a70795e6..a51fd8e9740 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java @@ -127,8 +127,8 @@ public class SpringApplicationAdminJmxAutoConfigurationTests { assertThat(this.context).isInstanceOf(ServletWebServerApplicationContext.class); assertThat(this.mBeanServer.getAttribute(createDefaultObjectName(), "EmbeddedWebApplication")).isEqualTo(Boolean.TRUE); - int expected = ((ServletWebServerApplicationContext) this.context) - .getWebServer().getPort(); + int expected = ((ServletWebServerApplicationContext) this.context).getWebServer() + .getPort(); String actual = getProperty(createDefaultObjectName(), "local.server.port"); assertThat(actual).isEqualTo(String.valueOf(expected)); } @@ -142,26 +142,17 @@ public class SpringApplicationAdminJmxAutoConfigurationTests { .child(JmxAutoConfiguration.class, SpringApplicationAdminJmxAutoConfiguration.class) .web(WebApplicationType.NONE); - ConfigurableApplicationContext parent = null; - ConfigurableApplicationContext child = null; - try { - parent = parentBuilder.run("--" + ENABLE_ADMIN_PROP); - child = childBuilder.run("--" + ENABLE_ADMIN_PROP); + try (ConfigurableApplicationContext parent = parentBuilder + .run("--" + ENABLE_ADMIN_PROP); + ConfigurableApplicationContext child = childBuilder + .run("--" + ENABLE_ADMIN_PROP)) { BeanFactoryUtils.beanOfType(parent.getBeanFactory(), SpringApplicationAdminMXBeanRegistrar.class); this.thrown.expect(NoSuchBeanDefinitionException.class); BeanFactoryUtils.beanOfType(child.getBeanFactory(), SpringApplicationAdminMXBeanRegistrar.class); } - finally { - if (parent != null) { - parent.close(); - } - if (child != null) { - child.close(); - } - } } private ObjectName createDefaultObjectName() { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java index dbc6a297715..cb4099d467e 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java @@ -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"); * you may not use this file except in compliance with the License. @@ -145,17 +145,13 @@ public class ConditionalOnSingleCandidateTests { @Test public void singleCandidateMultipleCandidatesInContextHierarchy() { load(FooPrimaryConfiguration.class, BarConfiguration.class); - AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext(); - child.setParent(this.context); - child.register(OnBeanSingleCandidateConfiguration.class); - try { + try (AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext()) { + child.setParent(this.context); + child.register(OnBeanSingleCandidateConfiguration.class); child.refresh(); assertThat(child.containsBean("baz")).isTrue(); assertThat(child.getBean("baz")).isEqualTo("foo"); } - finally { - child.close(); - } } private void load(Class... classes) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java index 30a70e27503..46f76d8e70e 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java @@ -143,9 +143,8 @@ public class MessageSourceAutoConfigurationTests { @Test public void existingMessageSourceInParentIsIgnored() { - ConfigurableApplicationContext parent = new AnnotationConfigApplicationContext(); - parent.refresh(); - try { + try (ConfigurableApplicationContext parent = new AnnotationConfigApplicationContext()) { + parent.refresh(); this.context = new AnnotationConfigApplicationContext(); this.context.setParent(parent); EnvironmentTestUtils.addEnvironment(this.context, @@ -156,9 +155,6 @@ public class MessageSourceAutoConfigurationTests { assertThat(this.context.getMessage("foo", null, "Foo message", Locale.UK)) .isEqualTo("bar"); } - finally { - parent.close(); - } } private void load(String... environment) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationIntegrationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationIntegrationTests.java index 4173cab2b74..2951bdc44ca 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationIntegrationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationIntegrationTests.java @@ -83,14 +83,10 @@ public class CassandraDataAutoConfigurationIntegrationTests { } private void createTestKeyspaceIfNotExists() { - Session session = this.cassandra.getCluster().connect(); - try { + try (Session session = this.cassandra.getCluster().connect()) { session.execute("CREATE KEYSPACE IF NOT EXISTS boot_test" + " WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };"); } - finally { - session.close(); - } } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzerTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzerTests.java index 2d3c093fc81..bbd11963068 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzerTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzerTests.java @@ -235,20 +235,16 @@ public class NoSuchBeanDefinitionFailureAnalyzerTests { } private FatalBeanException createFailure(Class config, String... environment) { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - this.analyzer.setBeanFactory(context.getBeanFactory()); - EnvironmentTestUtils.addEnvironment(context, environment); - context.register(config); - try { + try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) { + this.analyzer.setBeanFactory(context.getBeanFactory()); + EnvironmentTestUtils.addEnvironment(context, environment); + context.register(config); context.refresh(); return null; } catch (FatalBeanException ex) { return ex; } - finally { - context.close(); - } } private FailureAnalysis analyzeFailure(Exception failure) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java index 951b66307b9..b9103518ae0 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java @@ -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"); * you may not use this file except in compliance with the License. @@ -177,18 +177,14 @@ public class FreeMarkerAutoConfigurationTests { @Test public void renderNonWebAppTemplate() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - FreeMarkerAutoConfiguration.class); - try { - freemarker.template.Configuration freemarker = context + try (AnnotationConfigApplicationContext customContext = new AnnotationConfigApplicationContext( + FreeMarkerAutoConfiguration.class)) { + freemarker.template.Configuration freemarker = customContext .getBean(freemarker.template.Configuration.class); StringWriter writer = new StringWriter(); freemarker.getTemplate("message.ftl").process(this, writer); assertThat(writer.toString()).contains("Hello World"); } - finally { - context.close(); - } } @Test diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfigurationTests.java index b5c141e8bb4..8cc7c0702ca 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfigurationTests.java @@ -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"); * you may not use this file except in compliance with the License. @@ -56,22 +56,17 @@ public class EmbeddedDataSourceConfigurationTests { @Test public void generateUniqueName() throws Exception { this.context = load("spring.datasource.generate-unique-name=true"); - AnnotationConfigApplicationContext context2 = load( - "spring.datasource.generate-unique-name=true"); - try { + try (AnnotationConfigApplicationContext context2 = load( + "spring.datasource.generate-unique-name=true")) { DataSource dataSource = this.context.getBean(DataSource.class); DataSource dataSource2 = context2.getBean(DataSource.class); assertThat(getDatabaseName(dataSource)) .isNotEqualTo(getDatabaseName(dataSource2)); } - finally { - context2.close(); - } } private String getDatabaseName(DataSource dataSource) throws SQLException { - Connection connection = dataSource.getConnection(); - try { + try (Connection connection = dataSource.getConnection()) { ResultSet catalogs = connection.getMetaData().getCatalogs(); if (catalogs.next()) { return catalogs.getString(1); @@ -80,9 +75,6 @@ public class EmbeddedDataSourceConfigurationTests { throw new IllegalStateException("Unable to get database name"); } } - finally { - connection.close(); - } } private AnnotationConfigApplicationContext load(String... environment) { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java index 0398a035d4a..76f440bcc64 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java @@ -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"); * you may not use this file except in compliance with the License. @@ -234,9 +234,8 @@ public class ArtemisAutoConfigurationTests { @Test public void severalEmbeddedBrokers() { load(EmptyConfiguration.class, "spring.artemis.embedded.queues=Queue1"); - AnnotationConfigApplicationContext anotherContext = doLoad( - EmptyConfiguration.class, "spring.artemis.embedded.queues=Queue2"); - try { + try (AnnotationConfigApplicationContext anotherContext = doLoad( + EmptyConfiguration.class, "spring.artemis.embedded.queues=Queue2")) { ArtemisProperties properties = this.context.getBean(ArtemisProperties.class); ArtemisProperties anotherProperties = anotherContext .getBean(ArtemisProperties.class); @@ -249,29 +248,23 @@ public class ArtemisAutoConfigurationTests { anotherChecker.checkQueue("Queue2", true); anotherChecker.checkQueue("Queue1", true); } - finally { - anotherContext.close(); - } } @Test public void connectToASpecificEmbeddedBroker() { load(EmptyConfiguration.class, "spring.artemis.embedded.serverId=93", "spring.artemis.embedded.queues=Queue1"); - AnnotationConfigApplicationContext anotherContext = doLoad( + + try (AnnotationConfigApplicationContext anotherContext = doLoad( EmptyConfiguration.class, "spring.artemis.mode=embedded", - "spring.artemis.embedded.serverId=93", // Connect to the "main" broker - "spring.artemis.embedded.enabled=false"); // do not start a specific one - try { + "spring.artemis.embedded.serverId=93", /* Connect to the "main" broker */ + "spring.artemis.embedded.enabled=false" /* do not start a specific one */)) { DestinationChecker checker = new DestinationChecker(this.context); checker.checkQueue("Queue1", true); DestinationChecker anotherChecker = new DestinationChecker(anotherContext); anotherChecker.checkQueue("Queue1", true); } - finally { - anotherContext.close(); - } } private TransportConfiguration assertInVmConnectionFactory( diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfigurationTests.java index 6ebd3114e9b..c3acc343d6c 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfigurationTests.java @@ -108,9 +108,8 @@ public class EmbeddedMongoAutoConfigurationTests { @Test public void portIsAvailableInParentContext() { - ConfigurableApplicationContext parent = new AnnotationConfigApplicationContext(); - parent.refresh(); - try { + try (ConfigurableApplicationContext parent = new AnnotationConfigApplicationContext()) { + parent.refresh(); this.context = new AnnotationConfigApplicationContext(); this.context.setParent(parent); this.context.register(EmbeddedMongoAutoConfiguration.class, @@ -119,9 +118,6 @@ public class EmbeddedMongoAutoConfigurationTests { assertThat(parent.getEnvironment().getProperty("local.mongo.port")) .isNotNull(); } - finally { - parent.close(); - } } @Test diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityAutoConfigurationTests.java index 2d8a63315a1..f4acddf5005 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityAutoConfigurationTests.java @@ -108,16 +108,12 @@ public class SecurityAutoConfigurationTests { @Test public void testFilterIsNotRegisteredInNonWeb() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - context.register(SecurityAutoConfiguration.class, - SecurityFilterAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); - try { - context.refresh(); - assertThat(context.containsBean("securityFilterChainRegistration")).isFalse(); - } - finally { - context.close(); + try (AnnotationConfigApplicationContext customContext = new AnnotationConfigApplicationContext()) { + customContext.register(SecurityAutoConfiguration.class, + SecurityFilterAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class); + customContext.refresh(); + assertThat(customContext.containsBean("securityFilterChainRegistration")).isFalse(); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityFilterAutoConfigurationEarlyInitializationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityFilterAutoConfigurationEarlyInitializationTests.java index c64cbcb2a8a..2057120908c 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityFilterAutoConfigurationEarlyInitializationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityFilterAutoConfigurationEarlyInitializationTests.java @@ -58,8 +58,7 @@ public class SecurityFilterAutoConfigurationEarlyInitializationTests { @Test public void testSecurityFilterDoesNotCauseEarlyInitialization() throws Exception { - AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext(); - try { + try (AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext()) { EnvironmentTestUtils.addEnvironment(context, "server.port:0", "security.user.password:password"); context.register(Config.class); @@ -70,10 +69,6 @@ public class SecurityFilterAutoConfigurationEarlyInitializationTests { // If early initialization occurred a ConverterNotFoundException is thrown } - finally { - context.close(); - } - } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityFilterAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityFilterAutoConfigurationTests.java index f650cfa4056..d26d1a1cecc 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityFilterAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/SecurityFilterAutoConfigurationTests.java @@ -44,16 +44,11 @@ public class SecurityFilterAutoConfigurationTests { @Test public void filterAutoConfigurationWorksWithoutSecurityAutoConfiguration() throws Exception { - AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); - context.setServletContext(new MockServletContext()); - try { + try (AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext()) { + context.setServletContext(new MockServletContext()); context.register(Config.class); context.refresh(); } - finally { - context.close(); - } - } @Configuration diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafServletAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafServletAutoConfigurationTests.java index fcde8b85154..b6787a89b29 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafServletAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafServletAutoConfigurationTests.java @@ -173,20 +173,17 @@ public class ThymeleafServletAutoConfigurationTests { @Test public void renderNonWebAppTemplate() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( + try (AnnotationConfigApplicationContext customContext = new AnnotationConfigApplicationContext( ThymeleafAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class); - assertThat(context.getBeanNamesForType(ViewResolver.class).length).isEqualTo(0); - try { - TemplateEngine engine = context.getBean(TemplateEngine.class); + PropertyPlaceholderAutoConfiguration.class)) { + assertThat(customContext.getBeanNamesForType(ViewResolver.class).length) + .isEqualTo(0); + TemplateEngine engine = customContext.getBean(TemplateEngine.class); Context attrs = new Context(Locale.UK, Collections.singletonMap("greeting", "Hello World")); String result = engine.process("message", attrs); assertThat(result).contains("Hello World"); } - finally { - context.close(); - } } @Test diff --git a/spring-boot-cli/src/it/java/org/springframework/boot/cli/infrastructure/CommandLineInvoker.java b/spring-boot-cli/src/it/java/org/springframework/boot/cli/infrastructure/CommandLineInvoker.java index 9adb7c9bf8d..3d1dc546ae9 100644 --- a/spring-boot-cli/src/it/java/org/springframework/boot/cli/infrastructure/CommandLineInvoker.java +++ b/spring-boot-cli/src/it/java/org/springframework/boot/cli/infrastructure/CommandLineInvoker.java @@ -79,8 +79,7 @@ public final class CommandLineInvoker { } })[0]; - ZipInputStream input = new ZipInputStream(new FileInputStream(zip)); - try { + try (ZipInputStream input = new ZipInputStream(new FileInputStream(zip))) { ZipEntry entry; while ((entry = input.getNextEntry()) != null) { File file = new File(unpacked, entry.getName()); @@ -89,22 +88,15 @@ public final class CommandLineInvoker { } else { file.getParentFile().mkdirs(); - FileOutputStream output = new FileOutputStream(file); - try { + try (FileOutputStream output = new FileOutputStream(file)) { StreamUtils.copy(input, output); if (entry.getName().endsWith("/bin/spring")) { file.setExecutable(true); } } - finally { - output.close(); - } } } } - finally { - input.close(); - } } File bin = new File(unpacked.listFiles()[0], "bin"); File launchScript = new File(bin, isWindows() ? "spring.bat" : "spring"); diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/ArchiveCommand.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/ArchiveCommand.java index 4e47c6f162a..c37709e6c1c 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/ArchiveCommand.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/ArchiveCommand.java @@ -187,8 +187,7 @@ abstract class ArchiveCommand extends OptionParsingCommand { List classpathEntries, List dependencies) throws FileNotFoundException, IOException, URISyntaxException { final List libraries; - JarWriter writer = new JarWriter(file); - try { + try (JarWriter writer = new JarWriter(file)) { addManifest(writer, compiledClasses); addCliClasses(writer); for (Class compiledClass : compiledClasses) { @@ -196,9 +195,6 @@ abstract class ArchiveCommand extends OptionParsingCommand { } libraries = addClasspathEntries(writer, classpathEntries); } - finally { - writer.close(); - } libraries.addAll(createLibraries(dependencies)); Repackager repackager = new Repackager(file); repackager.setMainClass(PackagedSpringApplicationLauncher.class.getName()); diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectGenerator.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectGenerator.java index 9e04f501104..0c9725182a0 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectGenerator.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectGenerator.java @@ -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"); * 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. * * @author Stephane Nicoll - * @since 1.2.0 */ class ProjectGenerator { @@ -106,17 +105,13 @@ class ProjectGenerator { if (!outputFolder.exists()) { outputFolder.mkdirs(); } - ZipInputStream zipStream = new ZipInputStream( - new ByteArrayInputStream(entity.getContent())); - try { + try (ZipInputStream zipStream = new ZipInputStream( + new ByteArrayInputStream(entity.getContent()))) { extractFromStream(zipStream, overwrite, outputFolder); fixExecutableFlag(outputFolder, "mvnw"); fixExecutableFlag(outputFolder, "gradlew"); Log.info("Project extracted to '" + outputFolder.getAbsolutePath() + "'"); } - finally { - zipStream.close(); - } } private void extractFromStream(ZipInputStream zipStream, boolean overwrite, diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolver.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolver.java index 087692bbf20..561ae16b00f 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolver.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/GroovyGrabDependencyResolver.java @@ -36,7 +36,6 @@ import org.springframework.boot.cli.compiler.GroovyCompilerConfiguration; * * @author Dave Syer * @author Andy Wilkinson - * @since 1.2.0 */ class GroovyGrabDependencyResolver implements DependencyResolver { @@ -70,18 +69,14 @@ class GroovyGrabDependencyResolver implements DependencyResolver { private String createSources(List artifactIdentifiers) throws IOException { File file = File.createTempFile("SpringCLIDependency", ".groovy"); file.deleteOnExit(); - OutputStreamWriter stream = new OutputStreamWriter(new FileOutputStream(file), - "UTF-8"); - try { + try (OutputStreamWriter stream = new OutputStreamWriter( + new FileOutputStream(file), "UTF-8")) { for (String artifactIdentifier : artifactIdentifiers) { stream.write("@Grab('" + artifactIdentifier + "')"); } // Dummy class to force compiler to do grab stream.write("class Installer {}"); } - finally { - stream.close(); - } // Windows paths get tricky unless you work with URI return file.getAbsoluteFile().toURI().toString(); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/Installer.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/Installer.java index cd1fef04915..ff5f3925703 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/Installer.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/install/Installer.java @@ -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"); * 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}. * * @author Andy Wilkinson - * @since 1.2.0 */ class Installer { @@ -82,13 +81,9 @@ class Installer { } private void saveInstallCounts() throws IOException { - FileWriter writer = new FileWriter(getInstalled()); - try { + try (FileWriter writer = new FileWriter(getInstalled())) { this.installCounts.store(writer, null); } - finally { - writer.close(); - } } public void install(List artifactIdentifiers) throws Exception { diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoader.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoader.java index a3bee740eab..b1e5be1daba 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoader.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoader.java @@ -98,14 +98,10 @@ public class ExtendedGroovyClassLoader extends GroovyClassLoader { private Class findSharedClass(String name) { try { String path = name.replace('.', '/').concat(".class"); - InputStream inputStream = getParent().getResourceAsStream(path); - if (inputStream != null) { - try { + try (InputStream inputStream = getParent().getResourceAsStream(path)) { + if (inputStream != null) { return defineClass(name, FileCopyUtils.copyToByteArray(inputStream)); } - finally { - inputStream.close(); - } } return null; } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitCommandTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitCommandTests.java index 4f150678913..9a0611e61f6 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitCommandTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitCommandTests.java @@ -365,18 +365,14 @@ public class InitCommandTests extends AbstractHttpClientMockTests { private byte[] createFakeZipArchive(String fileName, String content) throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ZipOutputStream zos = new ZipOutputStream(bos); - try { + try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ZipOutputStream zos = new ZipOutputStream(bos)) { ZipEntry entry = new ZipEntry(fileName); zos.putNextEntry(entry); zos.write(content.getBytes()); zos.closeEntry(); + return bos.toByteArray(); } - finally { - bos.close(); - } - return bos.toByteArray(); } private static class TestableInitCommandOptionHandler diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceMetadataTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceMetadataTests.java index 5edae7312bb..8f496abee02 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceMetadataTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceMetadataTests.java @@ -92,14 +92,10 @@ public class InitializrServiceMetadataTests { private static JSONObject readJson(String version) throws IOException, JSONException { Resource resource = new ClassPathResource( "metadata/service-metadata-" + version + ".json"); - InputStream stream = resource.getInputStream(); - try { + try (InputStream stream = resource.getInputStream()) { return new JSONObject( StreamUtils.copyToString(stream, Charset.forName("UTF-8"))); } - finally { - stream.close(); - } } } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/LiveReloadServer.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/LiveReloadServer.java index 69a8d2eef77..9a5e81449f7 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/LiveReloadServer.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/LiveReloadServer.java @@ -282,16 +282,10 @@ public class LiveReloadServer { private void handle() throws Exception { try { - try { - OutputStream outputStream = this.socket.getOutputStream(); - try { - Connection connection = createConnection(this.socket, - this.inputStream, outputStream); - runConnection(connection); - } - finally { - outputStream.close(); - } + try (OutputStream outputStream = this.socket.getOutputStream()) { + Connection connection = createConnection(this.socket, + this.inputStream, outputStream); + runConnection(connection); } finally { this.inputStream.close(); diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/TunnelClient.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/TunnelClient.java index 9d0a0620c19..00edb905e48 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/TunnelClient.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/TunnelClient.java @@ -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"); * you may not use this file except in compliance with the License. @@ -152,16 +152,12 @@ public class TunnelClient implements SmartInitializingSingleton { public void run() { try { while (this.acceptConnections) { - SocketChannel socket = this.serverSocketChannel.accept(); - try { + try (SocketChannel socket = this.serverSocketChannel.accept()) { handleConnection(socket); } catch (AsynchronousCloseException ex) { // Connection has been closed. Keep the server running } - finally { - socket.close(); - } } } catch (Exception ex) { diff --git a/spring-boot-samples/spring-boot-sample-custom-layout/src/test/java/sample/layout/Verify.java b/spring-boot-samples/spring-boot-sample-custom-layout/src/test/java/sample/layout/Verify.java index 1d7cd3868ce..2310f191d54 100644 --- a/spring-boot-samples/spring-boot-sample-custom-layout/src/test/java/sample/layout/Verify.java +++ b/spring-boot-samples/spring-boot-sample-custom-layout/src/test/java/sample/layout/Verify.java @@ -27,8 +27,7 @@ public final class Verify { } public static void verify(File file, String entry) throws Exception { - ZipFile zipFile = new ZipFile(file); - try { + try (ZipFile zipFile = new ZipFile(file)) { Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { if (entries.nextElement().getName().equals(entry)) { @@ -37,9 +36,6 @@ public final class Verify { } throw new AssertionError("No entry " + entry); } - finally { - zipFile.close(); - } } -} \ No newline at end of file +} diff --git a/spring-boot-samples/spring-boot-sample-integration/src/test/java/sample/integration/consumer/SampleIntegrationApplicationTests.java b/spring-boot-samples/spring-boot-sample-integration/src/test/java/sample/integration/consumer/SampleIntegrationApplicationTests.java index 76ace128a3a..b9ff96f52d4 100644 --- a/spring-boot-samples/spring-boot-sample-integration/src/test/java/sample/integration/consumer/SampleIntegrationApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-integration/src/test/java/sample/integration/consumer/SampleIntegrationApplicationTests.java @@ -97,14 +97,10 @@ public class SampleIntegrationApplicationTests { } StringBuilder builder = new StringBuilder(); for (Resource resource : resources) { - InputStream inputStream = resource.getInputStream(); - try { + try (InputStream inputStream = resource.getInputStream()) { builder.append(new String( StreamUtils.copyToByteArray(inputStream))); } - finally { - inputStream.close(); - } } return builder.toString(); } diff --git a/spring-boot-samples/spring-boot-sample-jetty/src/test/java/sample/jetty/SampleJettyApplicationTests.java b/spring-boot-samples/spring-boot-sample-jetty/src/test/java/sample/jetty/SampleJettyApplicationTests.java index 91912ccce32..d3ea7a18fd3 100644 --- a/spring-boot-samples/spring-boot-sample-jetty/src/test/java/sample/jetty/SampleJettyApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jetty/src/test/java/sample/jetty/SampleJettyApplicationTests.java @@ -64,21 +64,14 @@ public class SampleJettyApplicationTests { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("Accept-Encoding", "gzip"); HttpEntity requestEntity = new HttpEntity<>(requestHeaders); - ResponseEntity entity = this.restTemplate.exchange("/", HttpMethod.GET, requestEntity, byte[].class); - assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - - GZIPInputStream inflater = new GZIPInputStream( - new ByteArrayInputStream(entity.getBody())); - try { + try (GZIPInputStream inflater = new GZIPInputStream( + new ByteArrayInputStream(entity.getBody()))) { assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))) .isEqualTo("Hello World"); } - finally { - inflater.close(); - } } } diff --git a/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/SampleTomcatApplicationTests.java b/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/SampleTomcatApplicationTests.java index c4b43aa29df..42520d13286 100644 --- a/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/SampleTomcatApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/SampleTomcatApplicationTests.java @@ -75,15 +75,11 @@ public class SampleTomcatApplicationTests { ResponseEntity entity = this.restTemplate.exchange("/", HttpMethod.GET, requestEntity, byte[].class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - GZIPInputStream inflater = new GZIPInputStream( - new ByteArrayInputStream(entity.getBody())); - try { + try (GZIPInputStream inflater = new GZIPInputStream( + new ByteArrayInputStream(entity.getBody()))) { assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))) .isEqualTo("Hello World"); } - finally { - inflater.close(); - } } @Test diff --git a/spring-boot-samples/spring-boot-sample-undertow/src/test/java/sample/undertow/SampleUndertowApplicationTests.java b/spring-boot-samples/spring-boot-sample-undertow/src/test/java/sample/undertow/SampleUndertowApplicationTests.java index 3b964e191fe..35704151a38 100644 --- a/spring-boot-samples/spring-boot-sample-undertow/src/test/java/sample/undertow/SampleUndertowApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-undertow/src/test/java/sample/undertow/SampleUndertowApplicationTests.java @@ -70,15 +70,12 @@ public class SampleUndertowApplicationTests { ResponseEntity entity = this.restTemplate.exchange("/", HttpMethod.GET, requestEntity, byte[].class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); - GZIPInputStream inflater = new GZIPInputStream( - new ByteArrayInputStream(entity.getBody())); - try { + + try (GZIPInputStream inflater = new GZIPInputStream( + new ByteArrayInputStream(entity.getBody()))) { assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))) .isEqualTo("Hello World"); } - finally { - inflater.close(); - } } private void assertOkResponse(String path, String body) { diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java index f5ad54e4a59..85d2c58efe6 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java @@ -60,16 +60,12 @@ public class TestDatabaseAutoConfigurationTests { DataSource datasource = this.context.getBean(DataSource.class); JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource); jdbcTemplate.execute("create table example (id int, name varchar);"); - ConfigurableApplicationContext anotherContext = doLoad( - ExistingDataSourceConfiguration.class); - try { + try (ConfigurableApplicationContext anotherContext = doLoad( + ExistingDataSourceConfiguration.class)) { DataSource anotherDatasource = anotherContext.getBean(DataSource.class); JdbcTemplate anotherJdbcTemplate = new JdbcTemplate(anotherDatasource); anotherJdbcTemplate.execute("create table example (id int, name varchar);"); } - finally { - anotherContext.close(); - } } private void load(Class config, String... environment) { diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/ContentContainingCondition.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/ContentContainingCondition.java index 9c8411f09da..2ca90ac0547 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/ContentContainingCondition.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/ContentContainingCondition.java @@ -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"); * you may not use this file except in compliance with the License. @@ -42,25 +42,13 @@ class ContentContainingCondition extends Condition { @Override public boolean matches(File value) { - Reader reader = null; - try { - reader = new FileReader(value); + try (Reader reader = new FileReader(value)) { String content = FileCopyUtils.copyToString(reader); return content.contains(this.toContain); } catch (IOException ex) { throw new IllegalStateException(ex); } - finally { - if (reader != null) { - try { - reader.close(); - } - catch (IOException ex) { - // Ignore - } - } - } } } diff --git a/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessor.java b/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessor.java index 71a26c85582..7a981e5bc4c 100644 --- a/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessor.java +++ b/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessor.java @@ -201,13 +201,9 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor { if (!this.properties.isEmpty()) { FileObject file = this.processingEnv.getFiler() .createResource(StandardLocation.CLASS_OUTPUT, "", PROPERTIES_PATH); - OutputStream outputStream = file.openOutputStream(); - try { + try (OutputStream outputStream = file.openOutputStream()) { this.properties.store(outputStream, null); } - finally { - outputStream.close(); - } } } diff --git a/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestConditionMetadataAnnotationProcessor.java b/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestConditionMetadataAnnotationProcessor.java index 9d7830ceed8..56471007965 100644 --- a/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestConditionMetadataAnnotationProcessor.java +++ b/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestConditionMetadataAnnotationProcessor.java @@ -62,15 +62,11 @@ public class TestConditionMetadataAnnotationProcessor if (!file.exists()) { return null; } - FileInputStream inputStream = new FileInputStream(file); - try { + try (FileInputStream inputStream = new FileInputStream(file)) { Properties properties = new Properties(); properties.load(inputStream); return properties; } - finally { - inputStream.close(); - } } } diff --git a/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java b/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java index 94277ebf174..d168280f347 100644 --- a/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java +++ b/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java @@ -40,8 +40,7 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests @Test public void simpleRepository() throws IOException { - InputStream foo = getInputStreamFor("foo"); - try { + try (InputStream foo = getInputStreamFor("foo")) { ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder .create(foo).build(); validateFoo(repo); @@ -50,15 +49,11 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests "spring.foo.counter"); assertThat(repo.getAllProperties()).hasSize(3); } - finally { - foo.close(); - } } @Test public void hintsOnMaps() throws IOException { - InputStream map = getInputStreamFor("map"); - try { + try (InputStream map = getInputStreamFor("map")) { ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder .create(map).build(); validateMap(repo); @@ -67,16 +62,12 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests "spring.map.keys", "spring.map.values"); assertThat(repo.getAllProperties()).hasSize(4); } - finally { - map.close(); - } } @Test public void severalRepositoriesNoConflict() throws IOException { - InputStream foo = getInputStreamFor("foo"); - InputStream bar = getInputStreamFor("bar"); - try { + try (InputStream foo = getInputStreamFor("foo"); + InputStream bar = getInputStreamFor("bar")) { ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder .create(foo, bar).build(); validateFoo(repo); @@ -87,17 +78,12 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests "spring.bar.counter"); assertThat(repo.getAllProperties()).hasSize(6); } - finally { - foo.close(); - bar.close(); - } } @Test public void repositoryWithRoot() throws IOException { - InputStream foo = getInputStreamFor("foo"); - InputStream root = getInputStreamFor("root"); - try { + try (InputStream foo = getInputStreamFor("foo"); + InputStream root = getInputStreamFor("root")) { ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder .create(foo, root).build(); validateFoo(repo); @@ -107,17 +93,12 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests "spring.foo.counter", "spring.root.name", "spring.root2.name"); assertThat(repo.getAllProperties()).hasSize(5); } - finally { - foo.close(); - root.close(); - } } @Test public void severalRepositoriesIdenticalGroups() throws IOException { - InputStream foo = getInputStreamFor("foo"); - InputStream foo2 = getInputStreamFor("foo2"); - try { + try (InputStream foo = getInputStreamFor("foo"); + InputStream foo2 = getInputStreamFor("foo2")) { ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder .create(foo, foo2).build(); assertThat(repo.getAllGroups()).hasSize(1); @@ -132,16 +113,11 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests "spring.foo.counter", "spring.foo.enabled", "spring.foo.type"); assertThat(repo.getAllProperties()).hasSize(5); } - finally { - foo.close(); - foo2.close(); - } } @Test public void emptyGroups() throws IOException { - InputStream in = getInputStreamFor("empty-groups"); - try { + try (InputStream in = getInputStreamFor("empty-groups")) { ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder .create(in).build(); validateEmptyGroup(repo); @@ -149,16 +125,12 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests contains(repo.getAllProperties(), "name", "title"); assertThat(repo.getAllProperties()).hasSize(2); } - finally { - in.close(); - } } @Test public void builderInstancesAreIsolated() throws IOException { - InputStream foo = getInputStreamFor("foo"); - InputStream bar = getInputStreamFor("bar"); - try { + try (InputStream foo = getInputStreamFor("foo"); + InputStream bar = getInputStreamFor("bar")) { ConfigurationMetadataRepositoryJsonBuilder builder = ConfigurationMetadataRepositoryJsonBuilder .create(); ConfigurationMetadataRepository firstRepo = builder.withJsonResource(foo) @@ -175,10 +147,6 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests assertThat(secondRepo.getAllGroups()).hasSize(2); assertThat(secondRepo.getAllProperties()).hasSize(6); } - finally { - foo.close(); - bar.close(); - } } private void validateFoo(ConfigurationMetadataRepository repo) { diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataStore.java b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataStore.java index f26ca1b6d08..0ab5ed2bb4e 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataStore.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataStore.java @@ -64,13 +64,10 @@ public class MetadataStore { public void writeMetadata(ConfigurationMetadata metadata) throws IOException { if (!metadata.getItems().isEmpty()) { - OutputStream outputStream = createMetadataResource().openOutputStream(); - try { + try (OutputStream outputStream = createMetadataResource() + .openOutputStream()) { new JsonMarshaller().write(metadata, outputStream); } - finally { - outputStream.close(); - } } } diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java index 5115a1f7034..5b11f5b1afb 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java @@ -815,13 +815,9 @@ public class ConfigurationMetadataAnnotationProcessorTests { } private void writeMetadata(File metadataFile, JSONObject metadata) throws Exception { - FileWriter writer = new FileWriter(metadataFile); - try { + try (FileWriter writer = new FileWriter(metadataFile)) { writer.append(metadata.toString(2)); } - finally { - writer.close(); - } } private static class AdditionalMetadata { diff --git a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ApplicationPluginAction.java b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ApplicationPluginAction.java index d012f9919f5..547eb516173 100644 --- a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ApplicationPluginAction.java +++ b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ApplicationPluginAction.java @@ -83,12 +83,11 @@ final class ApplicationPluginAction implements PluginApplicationAction { } private String loadResource(String name) { - InputStreamReader reader = new InputStreamReader( - getClass().getResourceAsStream(name)); - char[] buffer = new char[4096]; - int read = 0; - StringWriter writer = new StringWriter(); - try { + try (InputStreamReader reader = new InputStreamReader( + getClass().getResourceAsStream(name));) { + char[] buffer = new char[4096]; + int read = 0; + StringWriter writer = new StringWriter(); while ((read = reader.read(buffer)) > 0) { writer.write(buffer, 0, read); } @@ -97,14 +96,6 @@ final class ApplicationPluginAction implements PluginApplicationAction { catch (IOException ex) { throw new GradleException("Failed to read '" + name + "'", ex); } - finally { - try { - reader.close(); - } - catch (IOException ex) { - // Continue - } - } } } diff --git a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/BuildPropertiesWriter.java b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/BuildPropertiesWriter.java index 2f95a3b6391..c3367fdc3d1 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/BuildPropertiesWriter.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/BuildPropertiesWriter.java @@ -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"); * 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 { Properties properties = createBuildInfo(projectDetails); createFileIfNecessary(this.outputFile); - FileOutputStream outputStream = new FileOutputStream(this.outputFile); - try { + try (FileOutputStream outputStream = new FileOutputStream(this.outputFile)) { properties.store(outputStream, "Properties"); } - finally { - try { - outputStream.close(); - } - catch (IOException ex) { - // Continue - } - } } private void createFileIfNecessary(File file) throws IOException { diff --git a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/FileUtils.java b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/FileUtils.java index 0b71779a180..bb6778b0b18 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/FileUtils.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/FileUtils.java @@ -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"); * 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 { try { - DigestInputStream inputStream = new DigestInputStream( - new FileInputStream(file), MessageDigest.getInstance("SHA-1")); - try { + try (DigestInputStream inputStream = new DigestInputStream( + new FileInputStream(file), MessageDigest.getInstance("SHA-1"))) { byte[] buffer = new byte[4098]; while (inputStream.read(buffer) != -1) { // Read the entire stream } return bytesToHex(inputStream.getMessageDigest().digest()); } - finally { - inputStream.close(); - } } catch (NoSuchAlgorithmException ex) { throw new IllegalStateException(ex); diff --git a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JarWriter.java b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JarWriter.java index c60b595418f..7ab71cf74f6 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JarWriter.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JarWriter.java @@ -49,7 +49,7 @@ import java.util.zip.ZipEntry; * @author Phillip Webb * @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"; @@ -128,23 +128,24 @@ public class JarWriter implements LoaderClassesWriter { Enumeration entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); - ZipHeaderPeekInputStream inputStream = new ZipHeaderPeekInputStream( - jarFile.getInputStream(entry)); - try { - if (inputStream.hasZipHeader() && entry.getMethod() != ZipEntry.STORED) { - new CrcAndSize(inputStream).setupStoredEntry(entry); - inputStream.close(); - inputStream = new ZipHeaderPeekInputStream( - jarFile.getInputStream(entry)); - } + setUpStoredEntryIfNecessary(jarFile, entry); + try (ZipHeaderPeekInputStream inputStream = new ZipHeaderPeekInputStream( + jarFile.getInputStream(entry))) { EntryWriter entryWriter = new InputStreamEntryWriter(inputStream, true); JarEntry transformedEntry = entryTransformer.transform(entry); if (transformedEntry != null) { 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. * @throws IOException if the file cannot be closed */ + @Override public void close() throws IOException { this.jarOutput.close(); } diff --git a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/MainClassFinder.java b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/MainClassFinder.java index e9835a3468a..e02525e6917 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/MainClassFinder.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/MainClassFinder.java @@ -141,8 +141,7 @@ public abstract class MainClassFinder { while (!stack.isEmpty()) { File file = stack.pop(); if (file.isFile()) { - InputStream inputStream = new FileInputStream(file); - try { + try (InputStream inputStream = new FileInputStream(file)) { ClassDescriptor classDescriptor = createClassDescriptor(inputStream); if (classDescriptor != null && classDescriptor.isMainMethodFound()) { String className = convertToClassName(file.getAbsolutePath(), @@ -154,9 +153,6 @@ public abstract class MainClassFinder { } } } - finally { - inputStream.close(); - } } if (file.isDirectory()) { pushAllSorted(stack, file.listFiles(PACKAGE_FOLDER_FILTER)); @@ -240,9 +236,8 @@ public abstract class MainClassFinder { List classEntries = getClassEntries(jarFile, classesLocation); Collections.sort(classEntries, new ClassEntryComparator()); for (JarEntry entry : classEntries) { - InputStream inputStream = new BufferedInputStream( - jarFile.getInputStream(entry)); - try { + try (InputStream inputStream = new BufferedInputStream( + jarFile.getInputStream(entry))) { ClassDescriptor classDescriptor = createClassDescriptor(inputStream); if (classDescriptor != null && classDescriptor.isMainMethodFound()) { String className = convertToClassName(entry.getName(), @@ -254,9 +249,6 @@ public abstract class MainClassFinder { } } } - finally { - inputStream.close(); - } } return null; } diff --git a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Repackager.java b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Repackager.java index 1bfee27d333..d011dd90ba1 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Repackager.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Repackager.java @@ -184,13 +184,9 @@ public class Repackager { } destination.delete(); try { - JarFile jarFileSource = new JarFile(workingSource); - try { + try (JarFile jarFileSource = new JarFile(workingSource)) { repackage(jarFileSource, destination, libraries, launchScript); } - finally { - jarFileSource.close(); - } } finally { if (!this.backupSource && !this.source.equals(workingSource)) { @@ -221,21 +217,16 @@ public class Repackager { } private boolean alreadyRepackaged() throws IOException { - JarFile jarFile = new JarFile(this.source); - try { + try (JarFile jarFile = new JarFile(this.source)) { Manifest manifest = jarFile.getManifest(); return (manifest != null && manifest.getMainAttributes() .getValue(BOOT_VERSION_ATTRIBUTE) != null); } - finally { - jarFile.close(); - } } private void repackage(JarFile sourceJar, File destination, Libraries libraries, LaunchScript launchScript) throws IOException { - JarWriter writer = new JarWriter(destination, launchScript); - try { + try (JarWriter writer = new JarWriter(destination, launchScript)) { final List unpackLibraries = new ArrayList<>(); final List standardLibraries = new ArrayList<>(); libraries.doWithLibraries(new LibraryCallback() { @@ -256,14 +247,6 @@ public class Repackager { }); repackage(sourceJar, writer, unpackLibraries, standardLibraries); } - finally { - try { - writer.close(); - } - catch (Exception ex) { - // Ignore - } - } } private void repackage(JarFile sourceJar, JarWriter writer, @@ -309,13 +292,9 @@ public class Repackager { private boolean isZip(File file) { try { - FileInputStream fileInputStream = new FileInputStream(file); - try { + try (FileInputStream fileInputStream = new FileInputStream(file)) { return isZip(fileInputStream); } - finally { - fileInputStream.close(); - } } catch (IOException ex) { return false; diff --git a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/FileUtilsTests.java b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/FileUtilsTests.java index 80b47f6c3ce..04433f52337 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/FileUtilsTests.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/FileUtilsTests.java @@ -102,13 +102,9 @@ public class FileUtilsTests { @Test public void hash() throws Exception { File file = this.temporaryFolder.newFile(); - OutputStream outputStream = new FileOutputStream(file); - try { + try (OutputStream outputStream = new FileOutputStream(file)) { outputStream.write(new byte[] { 1, 2, 3 }); } - finally { - outputStream.close(); - } assertThat(FileUtils.sha1Hash(file)) .isEqualTo("7037807198c22a7d2b0807371d763779a84fdfcf"); } diff --git a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java index 8aa3c89811d..67346e445be 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java @@ -455,17 +455,14 @@ public class RepackagerTests { callback.library(new Library(nestedFile, LibraryScope.COMPILE)); } }); - JarFile jarFile = new JarFile(file); - try { + + try (JarFile jarFile = new JarFile(file)) { assertThat( jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getMethod()) .isEqualTo(ZipEntry.STORED); assertThat(jarFile.getEntry("BOOT-INF/classes/test/nested.jar").getMethod()) .isEqualTo(ZipEntry.STORED); } - finally { - jarFile.close(); - } } @Test @@ -508,15 +505,12 @@ public class RepackagerTests { } }); - JarFile jarFile = new JarFile(file); - try { + + try (JarFile jarFile = new JarFile(file)) { assertThat( jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getComment()) .startsWith("UNPACK:"); } - finally { - jarFile.close(); - } } @Test @@ -542,14 +536,10 @@ public class RepackagerTests { } }); - JarFile jarFile = new JarFile(file); - try { + try (JarFile jarFile = new JarFile(file)) { assertThat(jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getSize()) .isEqualTo(sourceLength); } - finally { - jarFile.close(); - } } @Test @@ -561,13 +551,9 @@ public class RepackagerTests { File dest = this.temporaryFolder.newFile("dest.jar"); Repackager repackager = new Repackager(source); repackager.repackage(dest, NO_LIBRARIES); - JarFile jarFile = new JarFile(dest); - try { + try (JarFile jarFile = new JarFile(dest)) { assertThat(jarFile.getEntry("META-INF/INDEX.LIST")).isNull(); } - finally { - jarFile.close(); - } } @Test @@ -603,14 +589,10 @@ public class RepackagerTests { File dest = this.temporaryFolder.newFile("dest.jar"); Repackager repackager = new Repackager(source); repackager.repackage(dest, NO_LIBRARIES); - JarFile jarFile = new JarFile(dest); - try { + try (JarFile jarFile = new JarFile(dest)) { assertThat(jarFile.getEntry("META-INF/aop.xml")).isNull(); assertThat(jarFile.getEntry("BOOT-INF/classes/META-INF/aop.xml")).isNotNull(); } - finally { - jarFile.close(); - } } private boolean hasLauncherClasses(File file) throws IOException { @@ -623,23 +605,15 @@ public class RepackagerTests { } private JarEntry getEntry(File file, String name) throws IOException { - JarFile jarFile = new JarFile(file); - try { + try (JarFile jarFile = new JarFile(file)) { return jarFile.getJarEntry(name); } - finally { - jarFile.close(); - } } private Manifest getManifest(File file) throws IOException { - JarFile jarFile = new JarFile(file); - try { + try (JarFile jarFile = new JarFile(file)) { return jarFile.getManifest(); } - finally { - jarFile.close(); - } } private static class MockLauncherScript implements LaunchScript { diff --git a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/TestJarFile.java b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/TestJarFile.java index 22d148d5e64..32540ae2cfa 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/TestJarFile.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/TestJarFile.java @@ -65,25 +65,17 @@ public class TestJarFile { public void addFile(String filename, File fileToCopy) throws IOException { File file = getFilePath(filename); file.getParentFile().mkdirs(); - InputStream inputStream = new FileInputStream(fileToCopy); - try { + try (InputStream inputStream = new FileInputStream(fileToCopy)) { copyToFile(inputStream, file); } - finally { - inputStream.close(); - } } public void addManifest(Manifest manifest) throws IOException { File manifestFile = new File(this.jarSource, "META-INF/MANIFEST.MF"); manifestFile.getParentFile().mkdirs(); - OutputStream outputStream = new FileOutputStream(manifestFile); - try { + try (OutputStream outputStream = new FileOutputStream(manifestFile)) { manifest.write(outputStream); } - finally { - outputStream.close(); - } } private File getFilePath(String filename) { @@ -97,13 +89,9 @@ public class TestJarFile { private void copyToFile(InputStream inputStream, File file) throws FileNotFoundException, IOException { - OutputStream outputStream = new FileOutputStream(file); - try { + try (OutputStream outputStream = new FileOutputStream(file)) { copy(inputStream, outputStream); } - finally { - outputStream.close(); - } } private void copy(InputStream in, OutputStream out) throws IOException { diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/PropertiesLauncher.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/PropertiesLauncher.java index 3aaefebe242..b361c7ee526 100755 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/PropertiesLauncher.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/PropertiesLauncher.java @@ -164,35 +164,34 @@ public class PropertiesLauncher extends Launcher { } } for (String config : configs) { - InputStream resource = getResource(config); - if (resource != null) { - debug("Found: " + config); - try { - this.properties.load(resource); + try (InputStream resource = getResource(config)) { + if (resource != null) { + debug("Found: " + config); + loadResource(resource); + // Load the first one we find + return; } - finally { - resource.close(); + else { + 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); } } } diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/archive/ExplodedArchive.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/archive/ExplodedArchive.java index 3f2b435ddd7..3d21e46c0b8 100644 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/archive/ExplodedArchive.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/archive/ExplodedArchive.java @@ -91,13 +91,9 @@ public class ExplodedArchive implements Archive { @Override public Manifest getManifest() throws IOException { if (this.manifest == null && this.manifestFile.exists()) { - FileInputStream inputStream = new FileInputStream(this.manifestFile); - try { + try (FileInputStream inputStream = new FileInputStream(this.manifestFile)) { this.manifest = new Manifest(inputStream); } - finally { - inputStream.close(); - } } return this.manifest; } diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/archive/JarFileArchive.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/archive/JarFileArchive.java index fb72737695d..6408467c5a1 100755 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/archive/JarFileArchive.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/archive/JarFileArchive.java @@ -145,23 +145,15 @@ public class JarFileArchive implements Archive { } private void unpack(JarEntry entry, File file) throws IOException { - InputStream inputStream = this.jarFile.getInputStream(entry, ResourceAccess.ONCE); - try { - OutputStream outputStream = new FileOutputStream(file); - try { - byte[] buffer = new byte[BUFFER_SIZE]; - int bytesRead = -1; - while ((bytesRead = inputStream.read(buffer)) != -1) { - outputStream.write(buffer, 0, bytesRead); - } - outputStream.flush(); + try (InputStream inputStream = this.jarFile.getInputStream(entry, + ResourceAccess.ONCE); + OutputStream outputStream = new FileOutputStream(file)) { + byte[] buffer = new byte[BUFFER_SIZE]; + int bytesRead = -1; + while ((bytesRead = inputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, bytesRead); } - finally { - outputStream.close(); - } - } - finally { - inputStream.close(); + outputStream.flush(); } } diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/Bytes.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/Bytes.java index fb4baffe39b..946211d74bd 100644 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/Bytes.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/Bytes.java @@ -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"); * 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 { - InputStream inputStream = data.getInputStream(ResourceAccess.ONCE); - try { + try (InputStream inputStream = data.getInputStream(ResourceAccess.ONCE)) { return get(inputStream, data.getSize()); } - finally { - inputStream.close(); - } } public static byte[] get(InputStream inputStream, long length) throws IOException { diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFile.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFile.java index ce89b2ec80c..b0fe5f090e7 100644 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFile.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFile.java @@ -160,17 +160,13 @@ public class JarFile extends java.util.jar.JarFile { manifest = new JarFile(this.getRootJarFile()).getManifest(); } else { - InputStream inputStream = getInputStream(MANIFEST_NAME, - ResourceAccess.ONCE); - if (inputStream == null) { - return null; - } - try { + try (InputStream inputStream = getInputStream(MANIFEST_NAME, + ResourceAccess.ONCE)) { + if (inputStream == null) { + return null; + } manifest = new Manifest(inputStream); } - finally { - inputStream.close(); - } } 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 // happening that often. try { - JarInputStream inputStream = new JarInputStream( - getData().getInputStream(ResourceAccess.ONCE)); - try { + try (JarInputStream inputStream = new JarInputStream( + getData().getInputStream(ResourceAccess.ONCE))) { java.util.jar.JarEntry certEntry = inputStream.getNextJarEntry(); while (certEntry != null) { inputStream.closeEntry(); @@ -348,9 +343,6 @@ public class JarFile extends java.util.jar.JarFile { certEntry = inputStream.getNextJarEntry(); } } - finally { - inputStream.close(); - } } catch (IOException ex) { throw new IllegalStateException(ex); diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/TestJarCreator.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/TestJarCreator.java index a67fcb57958..217c5f09094 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/TestJarCreator.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/TestJarCreator.java @@ -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"); * 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 { FileOutputStream fileOutputStream = new FileOutputStream(file); - JarOutputStream jarOutputStream = new JarOutputStream(fileOutputStream); - try { + try (JarOutputStream jarOutputStream = new JarOutputStream(fileOutputStream)) { writeManifest(jarOutputStream, "j1"); writeEntry(jarOutputStream, "1.dat", 1); writeEntry(jarOutputStream, "2.dat", 2); @@ -53,9 +52,6 @@ public abstract class TestJarCreator { writeNestedEntry("nested.jar", unpackNested, jarOutputStream); writeNestedEntry("another-nested.jar", unpackNested, jarOutputStream); } - finally { - jarOutputStream.close(); - } } private static void writeNestedEntry(String name, boolean unpackNested, diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/StartMojo.java b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/StartMojo.java index 1c157acbf5b..7661cbaf2f4 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/StartMojo.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/StartMojo.java @@ -205,21 +205,18 @@ public class StartMojo extends AbstractRunMojo { throws IOException, MojoFailureException, MojoExecutionException { try { getLog().debug("Connecting to local MBeanServer at port " + this.jmxPort); - JMXConnector connector = execute(this.wait, this.maxAttempts, - new CreateJmxConnector(this.jmxPort)); - if (connector == null) { - throw new MojoExecutionException( - "JMX MBean server was not reachable before the configured " - + "timeout (" + (this.wait * this.maxAttempts) + "ms"); - } - getLog().debug("Connected to local MBeanServer at port " + this.jmxPort); - try { + try (JMXConnector connector = execute(this.wait, this.maxAttempts, + new CreateJmxConnector(this.jmxPort))) { + if (connector == null) { + throw new MojoExecutionException( + "JMX MBean server was not reachable before the configured " + + "timeout (" + (this.wait * this.maxAttempts) + + "ms"); + } + getLog().debug("Connected to local MBeanServer at port " + this.jmxPort); MBeanServerConnection connection = connector.getMBeanServerConnection(); doWaitForSpringApplication(connection); } - finally { - connector.close(); - } } catch (IOException ex) { throw ex; diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/StopMojo.java b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/StopMojo.java index 87309eb8569..d36bc7bd422 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/StopMojo.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/StopMojo.java @@ -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"); * you may not use this file except in compliance with the License. @@ -110,14 +110,11 @@ public class StopMojo extends AbstractMojo { private void stopForkedProcess() throws IOException, MojoFailureException, MojoExecutionException { - JMXConnector connector = SpringApplicationAdminClient.connect(this.jmxPort); - try { + try (JMXConnector connector = SpringApplicationAdminClient + .connect(this.jmxPort)) { MBeanServerConnection connection = connector.getMBeanServerConnection(); doStop(connection); } - finally { - connector.close(); - } } private void stop() throws IOException, MojoFailureException, MojoExecutionException { diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/Verify.java b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/Verify.java index 55beb4d1aa1..84af1060f89 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/Verify.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/Verify.java @@ -198,14 +198,10 @@ public final class Verify { .startsWith(new String(new byte[] { 0x50, 0x4b, 0x03, 0x04 })); } - ZipFile zipFile = new ZipFile(this.file); - try { + try (ZipFile zipFile = new ZipFile(this.file)) { ArchiveVerifier verifier = new ArchiveVerifier(zipFile); verifyZipEntries(verifier); } - finally { - zipFile.close(); - } } protected void verifyZipEntries(ArchiveVerifier verifier) throws Exception { diff --git a/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/junit/runner/classpath/ModifiedClassPathRunner.java b/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/junit/runner/classpath/ModifiedClassPathRunner.java index 39d6dff98db..87ef49ece59 100644 --- a/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/junit/runner/classpath/ModifiedClassPathRunner.java +++ b/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/junit/runner/classpath/ModifiedClassPathRunner.java @@ -125,14 +125,10 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { } private String[] getClassPath(URL booterJar) throws Exception { - JarFile jarFile = new JarFile(new File(booterJar.toURI())); - try { + try (JarFile jarFile = new JarFile(new File(booterJar.toURI()))) { return StringUtils.delimitedListToStringArray(jarFile.getManifest() .getMainAttributes().getValue(Attributes.Name.CLASS_PATH), " "); } - finally { - jarFile.close(); - } } private URL[] processUrls(URL[] urls, Class testClass) throws Exception { diff --git a/spring-boot/src/main/java/org/springframework/boot/ApplicationHome.java b/spring-boot/src/main/java/org/springframework/boot/ApplicationHome.java index 33c029f98a9..91d62616de9 100644 --- a/spring-boot/src/main/java/org/springframework/boot/ApplicationHome.java +++ b/spring-boot/src/main/java/org/springframework/boot/ApplicationHome.java @@ -36,6 +36,7 @@ import org.springframework.util.StringUtils; * both Jar Files, Exploded Archives and directly running applications. * * @author Phillip Webb + * @author Raja Kolli * @since 1.2.0 */ public class ApplicationHome { diff --git a/spring-boot/src/main/java/org/springframework/boot/ApplicationPid.java b/spring-boot/src/main/java/org/springframework/boot/ApplicationPid.java index f35d5f0541c..7115118f893 100644 --- a/spring-boot/src/main/java/org/springframework/boot/ApplicationPid.java +++ b/spring-boot/src/main/java/org/springframework/boot/ApplicationPid.java @@ -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"); * 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 { Assert.state(this.pid != null, "No PID available"); createParentFolder(file); - FileWriter writer = new FileWriter(file); - try { + try (FileWriter writer = new FileWriter(file)) { writer.append(this.pid); } - finally { - writer.close(); - } } private void createParentFolder(File file) { diff --git a/spring-boot/src/main/java/org/springframework/boot/ImageBanner.java b/spring-boot/src/main/java/org/springframework/boot/ImageBanner.java index ee512f548df..1dc0aaf2484 100644 --- a/spring-boot/src/main/java/org/springframework/boot/ImageBanner.java +++ b/spring-boot/src/main/java/org/springframework/boot/ImageBanner.java @@ -44,6 +44,7 @@ import org.springframework.util.Assert; * @author Craig Burke * @author Phillip Webb * @author Madhura Bhave + * @author Raja Kolli * @since 1.4.0 */ public class ImageBanner implements Banner { diff --git a/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/FileSessionPersistence.java b/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/FileSessionPersistence.java index 85cd0e2ba94..0b02f734110 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/FileSessionPersistence.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/FileSessionPersistence.java @@ -37,6 +37,7 @@ import org.springframework.core.ConfigurableObjectInputStream; * * @author Phillip Webb * @author Peter Leibiger + * @author Raja Kolli */ class FileSessionPersistence implements SessionPersistenceManager { @@ -59,13 +60,10 @@ class FileSessionPersistence implements SessionPersistenceManager { private void save(Map sessionData, File file) throws IOException { - ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(file)); - try { + try (ObjectOutputStream stream = new ObjectOutputStream( + new FileOutputStream(file))) { save(sessionData, stream); } - finally { - stream.close(); - } } private void save(Map sessionData, diff --git a/spring-boot/src/main/java/org/springframework/boot/web/servlet/view/MustacheView.java b/spring-boot/src/main/java/org/springframework/boot/web/servlet/view/MustacheView.java index b82db8825d2..d898ff460e7 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/servlet/view/MustacheView.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/servlet/view/MustacheView.java @@ -83,13 +83,9 @@ public class MustacheView extends AbstractTemplateView { } private Template createTemplate(Resource resource) throws IOException { - Reader reader = getReader(resource); - try { + try (Reader reader = getReader(resource)) { return this.compiler.compile(reader); } - finally { - reader.close(); - } } private Reader getReader(Resource resource) throws IOException { diff --git a/spring-boot/src/test/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializerTests.java b/spring-boot/src/test/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializerTests.java index 5d6e3374446..af8ec74fc76 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializerTests.java @@ -112,18 +112,12 @@ public class ConfigurationWarningsApplicationContextInitializerTests { } private void load(Class configClass) { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - new TestConfigurationWarningsApplicationContextInitializer().initialize(context); - context.register(configClass); - try { + try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) { + new TestConfigurationWarningsApplicationContextInitializer() + .initialize(context); + context.register(configClass); context.refresh(); } - catch (Exception ex) { - ex.printStackTrace(); - } - finally { - context.close(); - } } /** diff --git a/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java b/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java index 413bbb03e97..ef0a1cc62b8 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java @@ -196,12 +196,8 @@ public class ConfigFileApplicationListenerTests { try { Properties properties = new Properties(); properties.put("the.property", "fromlocalfile"); - OutputStream out = new FileOutputStream(localFile); - try { - properties.store(out, ""); - } - finally { - out.close(); + try (OutputStream outputStream = new FileOutputStream(localFile)) { + properties.store(outputStream, ""); } this.initializer.postProcessEnvironment(this.environment, this.application); String property = this.environment.getProperty("the.property"); diff --git a/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerIntegrationTests.java b/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerIntegrationTests.java index f33e22876cd..039fba6b3a7 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerIntegrationTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerIntegrationTests.java @@ -44,15 +44,11 @@ public class LoggingApplicationListenerIntegrationTests { @Test public void loggingSystemRegisteredInTheContext() { - ConfigurableApplicationContext context = new SpringApplicationBuilder( - SampleService.class).web(WebApplicationType.NONE).run(); - try { + try (ConfigurableApplicationContext context = new SpringApplicationBuilder( + SampleService.class).web(WebApplicationType.NONE).run()) { SampleService service = context.getBean(SampleService.class); assertThat(service.loggingSystem).isNotNull(); } - finally { - context.close(); - } } @Test diff --git a/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCreationFailureAnalyzerTest.java b/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCreationFailureAnalyzerTests.java similarity index 88% rename from spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCreationFailureAnalyzerTest.java rename to spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCreationFailureAnalyzerTests.java index 4a0bfd312e7..5550a2058b3 100644 --- a/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCreationFailureAnalyzerTest.java +++ b/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCreationFailureAnalyzerTests.java @@ -33,7 +33,7 @@ import static org.junit.Assert.fail; * * @author Stephane Nicoll */ -public class BeanCreationFailureAnalyzerTest { +public class BeanCreationFailureAnalyzerTests { private final FailureAnalyzer analyzer = new BeanCreationFailureAnalyzer(); @@ -55,20 +55,14 @@ public class BeanCreationFailureAnalyzerTest { } private Exception createFailure(Class configuration) { - ConfigurableApplicationContext context = null; - try { - context = new AnnotationConfigApplicationContext(configuration); + try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( + configuration)) { + fail("Expected failure did not occur"); + return null; } catch (Exception ex) { return ex; } - finally { - if (context != null) { - context.close(); - } - } - fail("Expected failure did not occur"); - return null; } @Configuration diff --git a/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzerTests.java b/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzerTests.java index 4b7fca55641..92cd12260e5 100644 --- a/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzerTests.java @@ -118,9 +118,8 @@ public class BeanCurrentlyInCreationFailureAnalyzerTests { private List readDescriptionLines(FailureAnalysis analysis) throws IOException { - BufferedReader lineReader = new BufferedReader( - new StringReader(analysis.getDescription())); - try { + try (BufferedReader lineReader = new BufferedReader( + new StringReader(analysis.getDescription()))) { List lines = new ArrayList<>(); String line; while ((line = lineReader.readLine()) != null) { @@ -128,9 +127,6 @@ public class BeanCurrentlyInCreationFailureAnalyzerTests { } return lines; } - finally { - lineReader.close(); - } } private FailureAnalysis performAnalysis(Class configuration) { @@ -140,21 +136,15 @@ public class BeanCurrentlyInCreationFailureAnalyzerTests { } private Exception createFailure(Class configuration) { - ConfigurableApplicationContext context = null; - try { - context = new AnnotationConfigApplicationContext(configuration); + try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( + configuration);) { + fail("Expected failure did not occur"); + return null; } catch (Exception ex) { ex.printStackTrace(); return ex; } - finally { - if (context != null) { - context.close(); - } - } - fail("Expected failure did not occur"); - return null; } @org.springframework.context.annotation.Configuration diff --git a/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzerTests.java b/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzerTests.java index 7975125075c..dbc9fc7fd50 100644 --- a/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzerTests.java @@ -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"); * you may not use this file except in compliance with the License. @@ -57,20 +57,14 @@ public class BeanNotOfRequiredTypeFailureAnalyzerTests { } private Exception createFailure(Class configuration) { - ConfigurableApplicationContext context = null; - try { - context = new AnnotationConfigApplicationContext(configuration); + try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( + configuration)) { + fail("Expected failure did not occur"); + return null; } catch (Exception ex) { return ex; } - finally { - if (context != null) { - context.close(); - } - } - fail("Expected failure did not occur"); - return null; } @Configuration diff --git a/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzerTests.java b/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzerTests.java index 036189f6339..7c79be29257 100644 --- a/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzerTests.java @@ -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"); * you may not use this file except in compliance with the License. @@ -102,20 +102,19 @@ public class NoUniqueBeanDefinitionFailureAnalyzerTests { } private BeanCreationException createFailure(Class consumer) { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - context.register(DuplicateBeansProducer.class, consumer); - context.setParent(new AnnotationConfigApplicationContext(ParentProducer.class)); - try { - context.refresh(); + try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) { + context.register(DuplicateBeansProducer.class, consumer); + context.setParent( + new AnnotationConfigApplicationContext(ParentProducer.class)); + try { + context.refresh(); + } + catch (BeanCreationException ex) { + this.analyzer.setBeanFactory(context.getBeanFactory()); + return ex; + } return null; } - catch (BeanCreationException ex) { - this.analyzer.setBeanFactory(context.getBeanFactory()); - return ex; - } - finally { - context.close(); - } } private FailureAnalysis analyzeFailure(BeanCreationException failure) { diff --git a/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerMvcIntegrationTests.java b/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerMvcIntegrationTests.java index abd44b8471e..c4a0f03d155 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerMvcIntegrationTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerMvcIntegrationTests.java @@ -101,15 +101,11 @@ public class ServletWebServerMvcIntegrationTests { ClientHttpRequest request = clientHttpRequestFactory.createRequest(new URI( "http://localhost:" + context.getWebServer().getPort() + resourcePath), HttpMethod.GET); - ClientHttpResponse response = request.execute(); - try { + try (ClientHttpResponse response = request.execute()) { String actual = StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8")); assertThat(actual).isEqualTo("Hello World"); } - finally { - response.close(); - } } // Simple main method for testing in a browser diff --git a/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactoryTests.java b/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactoryTests.java index 97c034dc2e5..25d820a15d2 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactoryTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactoryTests.java @@ -122,6 +122,7 @@ import static org.mockito.Mockito.verify; * @author Phillip Webb * @author Greg Turnquist * @author Andy Wilkinson + * @author Raja Kolli */ public abstract class AbstractServletWebServerFactoryTests { @@ -1058,13 +1059,9 @@ public abstract class AbstractServletWebServerFactoryTests { protected String getResponse(String url, HttpMethod method, String... headers) throws IOException, URISyntaxException { - ClientHttpResponse response = getClientResponse(url, method, headers); - try { + try (ClientHttpResponse response = getClientResponse(url, method, headers)) { return StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8")); } - finally { - response.close(); - } } protected String getResponse(String url, @@ -1076,14 +1073,10 @@ public abstract class AbstractServletWebServerFactoryTests { protected String getResponse(String url, HttpMethod method, HttpComponentsClientHttpRequestFactory requestFactory, String... headers) throws IOException, URISyntaxException { - ClientHttpResponse response = getClientResponse(url, method, requestFactory, - headers); - try { + try (ClientHttpResponse response = getClientResponse(url, method, requestFactory, + headers)) { return StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8")); } - finally { - response.close(); - } } protected ClientHttpResponse getClientResponse(String url, String... headers) diff --git a/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializerTests.java b/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializerTests.java index 016a12d8294..8094a143460 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializerTests.java @@ -102,15 +102,11 @@ public class SpringBootServletInitializerTests { @Override public void onStartup(ServletContext servletContext) throws ServletException { - AbstractApplicationContext context = (AbstractApplicationContext) new WithErrorPageFilterNotRegistered() - .createRootApplicationContext(servletContext); - try { + try (AbstractApplicationContext context = (AbstractApplicationContext) new WithErrorPageFilterNotRegistered() + .createRootApplicationContext(servletContext)) { assertThat(context.getBeansOfType(ErrorPageFilter.class)) .hasSize(0); } - finally { - context.close(); - } } }); try { @@ -124,14 +120,10 @@ public class SpringBootServletInitializerTests { @Test public void executableWarThatUsesServletInitializerDoesNotHaveErrorPageFilterConfigured() throws Exception { - ConfigurableApplicationContext context = new SpringApplication( - ExecutableWar.class).run(); - try { + try (ConfigurableApplicationContext context = new SpringApplication( + ExecutableWar.class).run()) { assertThat(context.getBeansOfType(ErrorPageFilter.class)).hasSize(0); } - finally { - context.close(); - } } @Test