From 8099fc8178d73375c709e795370ad1767f3f5b01 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Tue, 16 Jun 2020 22:57:45 +0200 Subject: [PATCH] Use try-with-resources language construct where feasible Closes gh-2063 Co-authored-by: igor-suhorukov --- .../javamail/ConfigurableMimeFileTypeMap.java | 8 +- .../jcache/config/JCacheJavaConfigTests.java | 10 +- .../scheduling/quartz/QuartzSupportTests.java | 50 +++------- .../support/AbstractValueAdaptingCache.java | 1 - .../factory/xml/XmlBeanFactoryTests.java | 8 +- .../jmx/export/MBeanExporterTests.java | 92 ++++++++----------- .../AnnotationLazyInitMBeanTests.java | 29 ++---- .../core/SpringProperties.java | 8 +- .../util/xml/XmlValidationModeDetector.java | 8 +- .../core/io/PathResourceTests.java | 20 +--- .../core/io/ResourceTests.java | 11 +-- .../core/io/buffer/DataBufferTests.java | 9 +- .../util/SocketUtilsTests.java | 16 +--- ...tLobCreatingPreparedStatementCallback.java | 8 +- .../config/JdbcNamespaceIntegrationTests.java | 64 +++++-------- ...tenerAnnotationBeanPostProcessorTests.java | 36 ++------ .../PersistenceUnitReader.java | 8 +- .../AbstractHttpInvokerRequestExecutor.java | 6 +- .../HttpInvokerServiceExporter.java | 16 +--- .../AbstractAsyncHttpRequestFactoryTests.java | 59 ++++-------- .../AbstractHttpRequestFactoryTests.java | 48 +++++----- ...ufferingClientHttpRequestFactoryTests.java | 12 +-- .../StompWebSocketIntegrationTests.java | 46 +++------- 23 files changed, 179 insertions(+), 394 deletions(-) diff --git a/spring-context-support/src/main/java/org/springframework/mail/javamail/ConfigurableMimeFileTypeMap.java b/spring-context-support/src/main/java/org/springframework/mail/javamail/ConfigurableMimeFileTypeMap.java index cc6933129d8..ff6921b3718 100644 --- a/spring-context-support/src/main/java/org/springframework/mail/javamail/ConfigurableMimeFileTypeMap.java +++ b/spring-context-support/src/main/java/org/springframework/mail/javamail/ConfigurableMimeFileTypeMap.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2020 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. @@ -146,13 +146,9 @@ public class ConfigurableMimeFileTypeMap extends FileTypeMap implements Initiali protected FileTypeMap createFileTypeMap(@Nullable Resource mappingLocation, @Nullable String[] mappings) throws IOException { MimetypesFileTypeMap fileTypeMap = null; if (mappingLocation != null) { - InputStream is = mappingLocation.getInputStream(); - try { + try (InputStream is = mappingLocation.getInputStream()) { fileTypeMap = new MimetypesFileTypeMap(is); } - finally { - is.close(); - } } else { fileTypeMap = new MimetypesFileTypeMap(); diff --git a/spring-context-support/src/test/java/org/springframework/cache/jcache/config/JCacheJavaConfigTests.java b/spring-context-support/src/test/java/org/springframework/cache/jcache/config/JCacheJavaConfigTests.java index 9288994fc6f..5c12aceac02 100644 --- a/spring-context-support/src/test/java/org/springframework/cache/jcache/config/JCacheJavaConfigTests.java +++ b/spring-context-support/src/test/java/org/springframework/cache/jcache/config/JCacheJavaConfigTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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. @@ -101,10 +101,7 @@ public class JCacheJavaConfigTests extends AbstractJCacheAnnotationTests { @Test public void exceptionCacheResolverLazilyRequired() { - ConfigurableApplicationContext context = - new AnnotationConfigApplicationContext(NoExceptionCacheResolverConfig.class); - - try { + try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(NoExceptionCacheResolverConfig.class)) { DefaultJCacheOperationSource cos = context.getBean(DefaultJCacheOperationSource.class); assertThat(cos.getCacheResolver()).isSameAs(context.getBean("cacheResolver")); @@ -115,9 +112,6 @@ public class JCacheJavaConfigTests extends AbstractJCacheAnnotationTests { assertThatIllegalStateException().isThrownBy(() -> service.cacheWithException("test", false)); } - finally { - context.close(); - } } diff --git a/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSupportTests.java b/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSupportTests.java index a30b1c29121..0278e53f91b 100644 --- a/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSupportTests.java +++ b/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSupportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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. @@ -295,40 +295,31 @@ public class QuartzSupportTests { @Test // SPR-772 public void multipleSchedulers() throws Exception { - ClassPathXmlApplicationContext ctx = context("multipleSchedulers.xml"); - try { + try (ClassPathXmlApplicationContext ctx = context("multipleSchedulers.xml")) { Scheduler scheduler1 = (Scheduler) ctx.getBean("scheduler1"); Scheduler scheduler2 = (Scheduler) ctx.getBean("scheduler2"); assertThat(scheduler2).isNotSameAs(scheduler1); assertThat(scheduler1.getSchedulerName()).isEqualTo("quartz1"); assertThat(scheduler2.getSchedulerName()).isEqualTo("quartz2"); } - finally { - ctx.close(); - } } @Test // SPR-16884 public void multipleSchedulersWithQuartzProperties() throws Exception { - ClassPathXmlApplicationContext ctx = context("multipleSchedulersWithQuartzProperties.xml"); - try { + try (ClassPathXmlApplicationContext ctx = context("multipleSchedulersWithQuartzProperties.xml")) { Scheduler scheduler1 = (Scheduler) ctx.getBean("scheduler1"); Scheduler scheduler2 = (Scheduler) ctx.getBean("scheduler2"); assertThat(scheduler2).isNotSameAs(scheduler1); assertThat(scheduler1.getSchedulerName()).isEqualTo("quartz1"); assertThat(scheduler2.getSchedulerName()).isEqualTo("quartz2"); } - finally { - ctx.close(); - } } @Test @EnabledForTestGroups(PERFORMANCE) public void twoAnonymousMethodInvokingJobDetailFactoryBeans() throws Exception { - ClassPathXmlApplicationContext ctx = context("multipleAnonymousMethodInvokingJobDetailFB.xml"); Thread.sleep(3000); - try { + try (ClassPathXmlApplicationContext ctx = context("multipleAnonymousMethodInvokingJobDetailFB.xml")) { QuartzTestBean exportService = (QuartzTestBean) ctx.getBean("exportService"); QuartzTestBean importService = (QuartzTestBean) ctx.getBean("importService"); @@ -337,17 +328,13 @@ public class QuartzSupportTests { assertThat(importService.getImportCount()).as("doImport not called on importService").isEqualTo(2); assertThat(importService.getExportCount()).as("doExport called on importService").isEqualTo(0); } - finally { - ctx.close(); - } } @Test @EnabledForTestGroups(PERFORMANCE) public void schedulerAccessorBean() throws Exception { - ClassPathXmlApplicationContext ctx = context("schedulerAccessorBean.xml"); Thread.sleep(3000); - try { + try (ClassPathXmlApplicationContext ctx = context("schedulerAccessorBean.xml")) { QuartzTestBean exportService = (QuartzTestBean) ctx.getBean("exportService"); QuartzTestBean importService = (QuartzTestBean) ctx.getBean("importService"); @@ -356,9 +343,6 @@ public class QuartzSupportTests { assertThat(importService.getImportCount()).as("doImport not called on importService").isEqualTo(2); assertThat(importService.getExportCount()).as("doExport called on importService").isEqualTo(0); } - finally { - ctx.close(); - } } @Test @@ -387,9 +371,9 @@ public class QuartzSupportTests { @Test public void schedulerRepositoryExposure() throws Exception { - ClassPathXmlApplicationContext ctx = context("schedulerRepositoryExposure.xml"); - assertThat(ctx.getBean("scheduler")).isSameAs(SchedulerRepository.getInstance().lookup("myScheduler")); - ctx.close(); + try (ClassPathXmlApplicationContext ctx = context("schedulerRepositoryExposure.xml")) { + assertThat(ctx.getBean("scheduler")).isSameAs(SchedulerRepository.getInstance().lookup("myScheduler")); + } } /** @@ -401,19 +385,15 @@ public class QuartzSupportTests { DummyJob.param = 0; DummyJob.count = 0; - ClassPathXmlApplicationContext ctx = context("databasePersistence.xml"); - JdbcTemplate jdbcTemplate = new JdbcTemplate(ctx.getBean(DataSource.class)); - assertThat(jdbcTemplate.queryForList("SELECT * FROM qrtz_triggers").isEmpty()).as("No triggers were persisted").isFalse(); + try (ClassPathXmlApplicationContext ctx = context("databasePersistence.xml")) { + JdbcTemplate jdbcTemplate = new JdbcTemplate(ctx.getBean(DataSource.class)); + assertThat(jdbcTemplate.queryForList("SELECT * FROM qrtz_triggers").isEmpty()).as("No triggers were persisted").isFalse(); - /* - Thread.sleep(3000); - try { - assertTrue("DummyJob should have been executed at least once.", DummyJob.count > 0); - } - finally { - ctx.close(); + /* + Thread.sleep(3000); + assertTrue("DummyJob should have been executed at least once.", DummyJob.count > 0); + */ } - */ } private ClassPathXmlApplicationContext context(String path) { diff --git a/spring-context/src/main/java/org/springframework/cache/support/AbstractValueAdaptingCache.java b/spring-context/src/main/java/org/springframework/cache/support/AbstractValueAdaptingCache.java index 96091db9c3c..2e1d67fea19 100644 --- a/spring-context/src/main/java/org/springframework/cache/support/AbstractValueAdaptingCache.java +++ b/spring-context/src/main/java/org/springframework/cache/support/AbstractValueAdaptingCache.java @@ -123,5 +123,4 @@ public abstract class AbstractValueAdaptingCache implements Cache { return (storeValue != null ? new SimpleValueWrapper(fromStoreValue(storeValue)) : null); } - } diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests.java b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests.java index 0fed592d03c..edf72fdcf2b 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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. @@ -173,13 +173,9 @@ class XmlBeanFactoryTests { XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE); - InputStream inputStream = getClass().getResourceAsStream(REFTYPES_CONTEXT.getPath()); - try { + try (InputStream inputStream = getClass().getResourceAsStream(REFTYPES_CONTEXT.getPath())) { reader.loadBeanDefinitions(new InputSource(inputStream)); } - finally { - inputStream.close(); - } // Let's create the outer bean named "innerBean", // to check whether it doesn't create any conflicts diff --git a/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java b/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java index 1cf666cbb61..adff3bb372d 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,7 +77,7 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { @Test - public void testRegisterNullNotificationListenerType() throws Exception { + void testRegisterNullNotificationListenerType() throws Exception { Map listeners = new HashMap<>(); // put null in as a value... listeners.put("*", null); @@ -88,7 +88,7 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { } @Test - public void testRegisterNotificationListenerForNonExistentMBean() throws Exception { + void testRegisterNotificationListenerForNonExistentMBean() throws Exception { Map listeners = new HashMap<>(); NotificationListener dummyListener = new NotificationListener() { @Override @@ -108,7 +108,7 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { } @Test - public void testWithSuppliedMBeanServer() throws Exception { + void testWithSuppliedMBeanServer() throws Exception { MBeanExporter exporter = new MBeanExporter(); exporter.setBeans(getBeanMap()); exporter.setServer(server); @@ -123,7 +123,7 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { } @Test - public void testUserCreatedMBeanRegWithDynamicMBean() throws Exception { + void testUserCreatedMBeanRegWithDynamicMBean() throws Exception { Map map = new HashMap<>(); map.put("spring:name=dynBean", new TestDynamicMBean()); @@ -146,9 +146,8 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { } @Test - public void testAutodetectMBeans() throws Exception { - ConfigurableApplicationContext ctx = load("autodetectMBeans.xml"); - try { + void testAutodetectMBeans() throws Exception { + try (ConfigurableApplicationContext ctx = load("autodetectMBeans.xml")) { ctx.getBean("exporter"); MBeanServer server = ctx.getBean("server", MBeanServer.class); ObjectInstance instance = server.getObjectInstance(ObjectNameManager.getInstance("spring:mbean=true")); @@ -158,15 +157,11 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { instance = server.getObjectInstance(ObjectNameManager.getInstance("spring:mbean3=true")); assertThat(instance).isNotNull(); } - finally { - ctx.close(); - } } @Test - public void testAutodetectWithExclude() throws Exception { - ConfigurableApplicationContext ctx = load("autodetectMBeans.xml"); - try { + void testAutodetectWithExclude() throws Exception { + try (ConfigurableApplicationContext ctx = load("autodetectMBeans.xml")) { ctx.getBean("exporter"); MBeanServer server = ctx.getBean("server", MBeanServer.class); ObjectInstance instance = server.getObjectInstance(ObjectNameManager.getInstance("spring:mbean=true")); @@ -175,15 +170,11 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { assertThatExceptionOfType(InstanceNotFoundException.class).isThrownBy(() -> server.getObjectInstance(ObjectNameManager.getInstance("spring:mbean=false"))); } - finally { - ctx.close(); - } } @Test - public void testAutodetectLazyMBeans() throws Exception { - ConfigurableApplicationContext ctx = load("autodetectLazyMBeans.xml"); - try { + void testAutodetectLazyMBeans() throws Exception { + try (ConfigurableApplicationContext ctx = load("autodetectLazyMBeans.xml")) { ctx.getBean("exporter"); MBeanServer server = ctx.getBean("server", MBeanServer.class); @@ -197,24 +188,17 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { name = (String) server.getAttribute(oname, "Name"); assertThat(name).as("Invalid name returned").isEqualTo("Juergen Hoeller"); } - finally { - ctx.close(); - } } @Test - public void testAutodetectNoMBeans() throws Exception { - ConfigurableApplicationContext ctx = load("autodetectNoMBeans.xml"); - try { + void testAutodetectNoMBeans() throws Exception { + try (ConfigurableApplicationContext ctx = load("autodetectNoMBeans.xml")) { ctx.getBean("exporter"); } - finally { - ctx.close(); - } } @Test - public void testWithMBeanExporterListeners() throws Exception { + void testWithMBeanExporterListeners() throws Exception { MockMBeanExporterListener listener1 = new MockMBeanExporterListener(); MockMBeanExporterListener listener2 = new MockMBeanExporterListener(); @@ -230,7 +214,7 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { } @Test - public void testExportJdkProxy() throws Exception { + void testExportJdkProxy() throws Exception { JmxTestBean bean = new JmxTestBean(); bean.setName("Rob Harrop"); @@ -256,7 +240,7 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { } @Test - public void testSelfNaming() throws Exception { + void testSelfNaming() throws Exception { ObjectName objectName = ObjectNameManager.getInstance(OBJECT_NAME); SelfNamingTestBean testBean = new SelfNamingTestBean(); testBean.setObjectName(objectName); @@ -275,7 +259,7 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { } @Test - public void testRegisterIgnoreExisting() throws Exception { + void testRegisterIgnoreExisting() throws Exception { ObjectName objectName = ObjectNameManager.getInstance(OBJECT_NAME); Person preRegistered = new Person(); @@ -309,7 +293,7 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { } @Test - public void testRegisterReplaceExisting() throws Exception { + void testRegisterReplaceExisting() throws Exception { ObjectName objectName = ObjectNameManager.getInstance(OBJECT_NAME); Person preRegistered = new Person(); @@ -338,7 +322,7 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { } @Test - public void testWithExposeClassLoader() throws Exception { + void testWithExposeClassLoader() throws Exception { String name = "Rob Harrop"; String otherName = "Juergen Hoeller"; @@ -368,7 +352,7 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { } @Test - public void testBonaFideMBeanIsNotExportedWhenAutodetectIsTotallyTurnedOff() throws Exception { + void testBonaFideMBeanIsNotExportedWhenAutodetectIsTotallyTurnedOff() throws Exception { BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(Person.class); DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); factory.registerBeanDefinition("^&_invalidObjectName_(*", builder.getBeanDefinition()); @@ -388,7 +372,7 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { } @Test - public void testOnlyBonaFideMBeanIsExportedWhenAutodetectIsMBeanOnly() throws Exception { + void testOnlyBonaFideMBeanIsExportedWhenAutodetectIsMBeanOnly() throws Exception { BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(Person.class); DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); factory.registerBeanDefinition(OBJECT_NAME, builder.getBeanDefinition()); @@ -409,7 +393,7 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { } @Test - public void testBonaFideMBeanAndRegularBeanExporterWithAutodetectAll() throws Exception { + void testBonaFideMBeanAndRegularBeanExporterWithAutodetectAll() throws Exception { BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(Person.class); DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); factory.registerBeanDefinition(OBJECT_NAME, builder.getBeanDefinition()); @@ -433,7 +417,7 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { } @Test - public void testBonaFideMBeanIsNotExportedWithAutodetectAssembler() throws Exception { + void testBonaFideMBeanIsNotExportedWithAutodetectAssembler() throws Exception { BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(Person.class); DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); factory.registerBeanDefinition(OBJECT_NAME, builder.getBeanDefinition()); @@ -456,7 +440,7 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { * Want to ensure that said MBean is not exported twice. */ @Test - public void testBonaFideMBeanExplicitlyExportedAndAutodetectionIsOn() throws Exception { + void testBonaFideMBeanExplicitlyExportedAndAutodetectionIsOn() throws Exception { BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(Person.class); DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); factory.registerBeanDefinition(OBJECT_NAME, builder.getBeanDefinition()); @@ -475,42 +459,42 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { } @Test - public void testSetAutodetectModeToOutOfRangeNegativeValue() { + void testSetAutodetectModeToOutOfRangeNegativeValue() { MBeanExporter exporter = new MBeanExporter(); assertThatIllegalArgumentException().isThrownBy(() -> exporter.setAutodetectMode(-1)); } @Test - public void testSetAutodetectModeToOutOfRangePositiveValue() { + void testSetAutodetectModeToOutOfRangePositiveValue() { MBeanExporter exporter = new MBeanExporter(); assertThatIllegalArgumentException().isThrownBy(() -> exporter.setAutodetectMode(5)); } @Test - public void testSetAutodetectModeNameToAnEmptyString() { + void testSetAutodetectModeNameToAnEmptyString() { MBeanExporter exporter = new MBeanExporter(); assertThatIllegalArgumentException().isThrownBy(() -> exporter.setAutodetectModeName("")); } @Test - public void testSetAutodetectModeNameToAWhitespacedString() { + void testSetAutodetectModeNameToAWhitespacedString() { MBeanExporter exporter = new MBeanExporter(); assertThatIllegalArgumentException().isThrownBy(() -> exporter.setAutodetectModeName(" \t")); } @Test - public void testSetAutodetectModeNameToARubbishValue() { + void testSetAutodetectModeNameToARubbishValue() { MBeanExporter exporter = new MBeanExporter(); assertThatIllegalArgumentException().isThrownBy(() -> exporter.setAutodetectModeName("That Hansel is... *sssooo* hot right now!")); } @Test - public void testNotRunningInBeanFactoryAndPassedBeanNameToExport() throws Exception { + void testNotRunningInBeanFactoryAndPassedBeanNameToExport() throws Exception { MBeanExporter exporter = new MBeanExporter(); Map beans = new HashMap<>(); beans.put(OBJECT_NAME, "beanName"); @@ -520,7 +504,7 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { } @Test - public void testNotRunningInBeanFactoryAndAutodetectionIsOn() throws Exception { + void testNotRunningInBeanFactoryAndAutodetectionIsOn() throws Exception { MBeanExporter exporter = new MBeanExporter(); exporter.setAutodetectMode(MBeanExporter.AUTODETECT_ALL); assertThatExceptionOfType(MBeanExportException.class).isThrownBy(() -> @@ -528,7 +512,7 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { } @Test // SPR-2158 - public void testMBeanIsNotUnregisteredSpuriouslyIfSomeExternalProcessHasUnregisteredMBean() throws Exception { + void testMBeanIsNotUnregisteredSpuriouslyIfSomeExternalProcessHasUnregisteredMBean() throws Exception { MBeanExporter exporter = new MBeanExporter(); exporter.setBeans(getBeanMap()); exporter.setServer(this.server); @@ -544,7 +528,7 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { } @Test // SPR-3302 - public void testBeanNameCanBeUsedInNotificationListenersMap() throws Exception { + void testBeanNameCanBeUsedInNotificationListenersMap() throws Exception { String beanName = "charlesDexterWard"; BeanDefinitionBuilder testBean = BeanDefinitionBuilder.rootBeanDefinition(JmxTestBean.class); @@ -566,7 +550,7 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { } @Test - public void testWildcardCanBeUsedInNotificationListenersMap() throws Exception { + void testWildcardCanBeUsedInNotificationListenersMap() throws Exception { String beanName = "charlesDexterWard"; BeanDefinitionBuilder testBean = BeanDefinitionBuilder.rootBeanDefinition(JmxTestBean.class); @@ -588,7 +572,7 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { } @Test // SPR-3625 - public void testMBeanIsUnregisteredForRuntimeExceptionDuringInitialization() throws Exception { + void testMBeanIsUnregisteredForRuntimeExceptionDuringInitialization() throws Exception { BeanDefinitionBuilder builder1 = BeanDefinitionBuilder.rootBeanDefinition(Person.class); BeanDefinitionBuilder builder2 = BeanDefinitionBuilder .rootBeanDefinition(RuntimeExceptionThrowingConstructorBean.class); @@ -618,7 +602,7 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { } @Test - public void testIgnoreBeanName() throws MalformedObjectNameException { + void testIgnoreBeanName() throws MalformedObjectNameException { DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); String firstBeanName = "spring:type=TestBean"; factory.registerSingleton(firstBeanName, new TestBean("test")); @@ -640,7 +624,7 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { } @Test - public void testRegisterFactoryBean() throws MalformedObjectNameException { + void testRegisterFactoryBean() throws MalformedObjectNameException { DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); factory.registerBeanDefinition("spring:type=FactoryBean", new RootBeanDefinition(ProperSomethingFactoryBean.class)); @@ -655,7 +639,7 @@ public class MBeanExporterTests extends AbstractMBeanServerTests { } @Test - public void testIgnoreNullObjectFromFactoryBean() throws MalformedObjectNameException { + void testIgnoreNullObjectFromFactoryBean() throws MalformedObjectNameException { DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); factory.registerBeanDefinition("spring:type=FactoryBean", new RootBeanDefinition(NullSomethingFactoryBean.class)); diff --git a/spring-context/src/test/java/org/springframework/jmx/export/annotation/AnnotationLazyInitMBeanTests.java b/spring-context/src/test/java/org/springframework/jmx/export/annotation/AnnotationLazyInitMBeanTests.java index 04e5134b21b..46b8d5ec3d7 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/annotation/AnnotationLazyInitMBeanTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/annotation/AnnotationLazyInitMBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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,30 +31,23 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Rob Harrop * @author Juergen Hoeller */ -public class AnnotationLazyInitMBeanTests { +class AnnotationLazyInitMBeanTests { @Test - public void lazyNaming() throws Exception { - ConfigurableApplicationContext ctx = - new ClassPathXmlApplicationContext("org/springframework/jmx/export/annotation/lazyNaming.xml"); - try { + void lazyNaming() throws Exception { + try (ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("org/springframework/jmx/export/annotation/lazyNaming.xml")) { MBeanServer server = (MBeanServer) ctx.getBean("server"); ObjectName oname = ObjectNameManager.getInstance("bean:name=testBean4"); assertThat(server.getObjectInstance(oname)).isNotNull(); String name = (String) server.getAttribute(oname, "Name"); assertThat(name).as("Invalid name returned").isEqualTo("TEST"); } - finally { - ctx.close(); - } } @Test - public void lazyAssembling() throws Exception { + void lazyAssembling() throws Exception { System.setProperty("domain", "bean"); - ConfigurableApplicationContext ctx = - new ClassPathXmlApplicationContext("org/springframework/jmx/export/annotation/lazyAssembling.xml"); - try { + try (ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("org/springframework/jmx/export/annotation/lazyAssembling.xml")) { MBeanServer server = (MBeanServer) ctx.getBean("server"); ObjectName oname = ObjectNameManager.getInstance("bean:name=testBean4"); @@ -79,24 +72,18 @@ public class AnnotationLazyInitMBeanTests { } finally { System.clearProperty("domain"); - ctx.close(); } } @Test - public void componentScan() throws Exception { - ConfigurableApplicationContext ctx = - new ClassPathXmlApplicationContext("org/springframework/jmx/export/annotation/componentScan.xml"); - try { + void componentScan() throws Exception { + try (ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("org/springframework/jmx/export/annotation/componentScan.xml")) { MBeanServer server = (MBeanServer) ctx.getBean("server"); ObjectName oname = ObjectNameManager.getInstance("bean:name=testBean4"); assertThat(server.getObjectInstance(oname)).isNotNull(); String name = (String) server.getAttribute(oname, "Name"); assertThat(name).isNull(); } - finally { - ctx.close(); - } } } diff --git a/spring-core/src/main/java/org/springframework/core/SpringProperties.java b/spring-core/src/main/java/org/springframework/core/SpringProperties.java index 50ef4e75f13..4026ade5cdc 100644 --- a/spring-core/src/main/java/org/springframework/core/SpringProperties.java +++ b/spring-core/src/main/java/org/springframework/core/SpringProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2020 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,13 +62,9 @@ public final class SpringProperties { ClassLoader.getSystemResource(PROPERTIES_RESOURCE_LOCATION)); if (url != null) { logger.debug("Found 'spring.properties' file in local classpath"); - InputStream is = url.openStream(); - try { + try (InputStream is = url.openStream()) { localProperties.load(is); } - finally { - is.close(); - } } } catch (IOException ex) { diff --git a/spring-core/src/main/java/org/springframework/util/xml/XmlValidationModeDetector.java b/spring-core/src/main/java/org/springframework/util/xml/XmlValidationModeDetector.java index 305619e1fb0..19814c2b83f 100644 --- a/spring-core/src/main/java/org/springframework/util/xml/XmlValidationModeDetector.java +++ b/spring-core/src/main/java/org/springframework/util/xml/XmlValidationModeDetector.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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. @@ -90,8 +90,7 @@ public class XmlValidationModeDetector { */ public int detectValidationMode(InputStream inputStream) throws IOException { // Peek into the file to look for DOCTYPE. - BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); - try { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { boolean isDtdValidated = false; String content; while ((content = reader.readLine()) != null) { @@ -115,9 +114,6 @@ public class XmlValidationModeDetector { // Leave the decision up to the caller. return VALIDATION_AUTO; } - finally { - reader.close(); - } } diff --git a/spring-core/src/test/java/org/springframework/core/io/PathResourceTests.java b/spring-core/src/test/java/org/springframework/core/io/PathResourceTests.java index 7ef32706ee2..59761c1d628 100644 --- a/spring-core/src/test/java/org/springframework/core/io/PathResourceTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/PathResourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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. @@ -291,19 +291,12 @@ class PathResourceTests { @Test void getReadableByteChannel() throws IOException { PathResource resource = new PathResource(TEST_FILE); - ReadableByteChannel channel = null; - try { - channel = resource.readableChannel(); + try (ReadableByteChannel channel = resource.readableChannel()) { ByteBuffer buffer = ByteBuffer.allocate((int) resource.contentLength()); channel.read(buffer); buffer.rewind(); assertThat(buffer.limit()).isGreaterThan(0); } - finally { - if (channel != null) { - channel.close(); - } - } } @Test @@ -330,16 +323,9 @@ class PathResourceTests { Files.createFile(testPath); PathResource resource = new PathResource(testPath); ByteBuffer buffer = ByteBuffer.wrap("test".getBytes(StandardCharsets.UTF_8)); - WritableByteChannel channel = null; - try { - channel = resource.writableChannel(); + try (WritableByteChannel channel = resource.writableChannel()) { channel.write(buffer); } - finally { - if (channel != null) { - channel.close(); - } - } assertThat(resource.contentLength()).isEqualTo(4L); } diff --git a/spring-core/src/test/java/org/springframework/core/io/ResourceTests.java b/spring-core/src/test/java/org/springframework/core/io/ResourceTests.java index 83865675759..5a9c8e5d6d9 100644 --- a/spring-core/src/test/java/org/springframework/core/io/ResourceTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/ResourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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. @@ -298,19 +298,12 @@ class ResourceTests { @Test void readableChannel() throws IOException { Resource resource = new FileSystemResource(getClass().getResource("Resource.class").getFile()); - ReadableByteChannel channel = null; - try { - channel = resource.readableChannel(); + try (ReadableByteChannel channel = resource.readableChannel()) { ByteBuffer buffer = ByteBuffer.allocate((int) resource.contentLength()); channel.read(buffer); buffer.rewind(); assertThat(buffer.limit() > 0).isTrue(); } - finally { - if (channel != null) { - channel.close(); - } - } } @Test diff --git a/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferTests.java b/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferTests.java index cd0932e6257..619b9ce037f 100644 --- a/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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. @@ -346,17 +346,12 @@ class DataBufferTests extends AbstractDataBufferAllocatingTests { byte[] bytes = {'a', 'b', 'c'}; buffer.write(bytes); - InputStream inputStream = buffer.asInputStream(true); - - try { + try (InputStream inputStream = buffer.asInputStream(true)) { byte[] result = new byte[3]; int len = inputStream.read(result); assertThat(len).isEqualTo(3); assertThat(result).isEqualTo(bytes); } - finally { - inputStream.close(); - } // AbstractDataBufferAllocatingTests.leakDetector will verify the buffer's release } diff --git a/spring-core/src/test/java/org/springframework/util/SocketUtilsTests.java b/spring-core/src/test/java/org/springframework/util/SocketUtilsTests.java index 2e249eb0fa5..0f62fedb539 100644 --- a/spring-core/src/test/java/org/springframework/util/SocketUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/SocketUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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. @@ -75,19 +75,16 @@ class SocketUtilsTests { } @Test + @SuppressWarnings("try") void findAvailableTcpPortWhenPortOnLoopbackInterfaceIsNotAvailable() throws Exception { int port = SocketUtils.findAvailableTcpPort(); - ServerSocket socket = ServerSocketFactory.getDefault().createServerSocket(port, 1, InetAddress.getByName("localhost")); - try { + try (ServerSocket socket = ServerSocketFactory.getDefault().createServerSocket(port, 1, InetAddress.getByName("localhost"))) { // will only look for the exact port assertThatIllegalStateException().isThrownBy(() -> SocketUtils.findAvailableTcpPort(port, port)) .withMessageStartingWith("Could not find an available TCP port") .withMessageEndingWith("after 1 attempts"); } - finally { - socket.close(); - } } @Test @@ -152,19 +149,16 @@ class SocketUtilsTests { } @Test + @SuppressWarnings("try") void findAvailableUdpPortWhenPortOnLoopbackInterfaceIsNotAvailable() throws Exception { int port = SocketUtils.findAvailableUdpPort(); - DatagramSocket socket = new DatagramSocket(port, InetAddress.getByName("localhost")); - try { + try (DatagramSocket socket = new DatagramSocket(port, InetAddress.getByName("localhost"))) { // will only look for the exact port assertThatIllegalStateException().isThrownBy(() -> SocketUtils.findAvailableUdpPort(port, port)) .withMessageStartingWith("Could not find an available UDP port") .withMessageEndingWith("after 1 attempts"); } - finally { - socket.close(); - } } @Test diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/core/support/AbstractLobCreatingPreparedStatementCallback.java b/spring-jdbc/src/main/java/org/springframework/jdbc/core/support/AbstractLobCreatingPreparedStatementCallback.java index a74a5283fa2..42f415cba55 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/core/support/AbstractLobCreatingPreparedStatementCallback.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/core/support/AbstractLobCreatingPreparedStatementCallback.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2020 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. @@ -70,14 +70,10 @@ public abstract class AbstractLobCreatingPreparedStatementCallback implements Pr @Override public final Integer doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException { - LobCreator lobCreator = this.lobHandler.getLobCreator(); - try { + try (LobCreator lobCreator = this.lobHandler.getLobCreator()) { setValues(ps, lobCreator); return ps.executeUpdate(); } - finally { - lobCreator.close(); - } } /** diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/config/JdbcNamespaceIntegrationTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/config/JdbcNamespaceIntegrationTests.java index cf3d4b8a9f4..ec9c5fc1b19 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/config/JdbcNamespaceIntegrationTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/config/JdbcNamespaceIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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,44 +48,44 @@ import static org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFacto * @author Sam Brannen * @author Stephane Nicoll */ -public class JdbcNamespaceIntegrationTests { +class JdbcNamespaceIntegrationTests { @Test @EnabledForTestGroups(LONG_RUNNING) - public void createEmbeddedDatabase() throws Exception { + void createEmbeddedDatabase() throws Exception { assertCorrectSetup("jdbc-config.xml", "dataSource", "h2DataSource", "derbyDataSource"); } @Test @EnabledForTestGroups(LONG_RUNNING) - public void createEmbeddedDatabaseAgain() throws Exception { + void createEmbeddedDatabaseAgain() throws Exception { // If Derby isn't cleaned up properly this will fail... assertCorrectSetup("jdbc-config.xml", "derbyDataSource"); } @Test - public void createWithResourcePattern() throws Exception { + void createWithResourcePattern() throws Exception { assertCorrectSetup("jdbc-config-pattern.xml", "dataSource"); } @Test - public void createWithAnonymousDataSourceAndDefaultDatabaseName() throws Exception { + void createWithAnonymousDataSourceAndDefaultDatabaseName() throws Exception { assertCorrectSetupForSingleDataSource("jdbc-config-db-name-default-and-anonymous-datasource.xml", url -> url.endsWith(DEFAULT_DATABASE_NAME)); } @Test - public void createWithImplicitDatabaseName() throws Exception { + void createWithImplicitDatabaseName() throws Exception { assertCorrectSetupForSingleDataSource("jdbc-config-db-name-implicit.xml", url -> url.endsWith("dataSource")); } @Test - public void createWithExplicitDatabaseName() throws Exception { + void createWithExplicitDatabaseName() throws Exception { assertCorrectSetupForSingleDataSource("jdbc-config-db-name-explicit.xml", url -> url.endsWith("customDbName")); } @Test - public void createWithGeneratedDatabaseName() throws Exception { + void createWithGeneratedDatabaseName() throws Exception { Predicate urlPredicate = url -> url.startsWith("jdbc:hsqldb:mem:"); urlPredicate.and(url -> !url.endsWith("dataSource")); urlPredicate.and(url -> !url.endsWith("shouldBeOverriddenByGeneratedName")); @@ -93,19 +93,18 @@ public class JdbcNamespaceIntegrationTests { } @Test - public void createWithEndings() throws Exception { + void createWithEndings() throws Exception { assertCorrectSetupAndCloseContext("jdbc-initialize-endings-config.xml", 2, "dataSource"); } @Test - public void createWithEndingsNested() throws Exception { + void createWithEndingsNested() throws Exception { assertCorrectSetupAndCloseContext("jdbc-initialize-endings-nested-config.xml", 2, "dataSource"); } @Test - public void createAndDestroy() throws Exception { - ClassPathXmlApplicationContext context = context("jdbc-destroy-config.xml"); - try { + void createAndDestroy() throws Exception { + try (ClassPathXmlApplicationContext context = context("jdbc-destroy-config.xml")) { DataSource dataSource = context.getBean(DataSource.class); JdbcTemplate template = new JdbcTemplate(dataSource); assertNumRowsInTestTable(template, 1); @@ -114,15 +113,11 @@ public class JdbcNamespaceIntegrationTests { assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(() -> assertNumRowsInTestTable(template, 1)); } - finally { - context.close(); - } } @Test - public void createAndDestroyNestedWithHsql() throws Exception { - ClassPathXmlApplicationContext context = context("jdbc-destroy-nested-config.xml"); - try { + void createAndDestroyNestedWithHsql() throws Exception { + try (ClassPathXmlApplicationContext context = context("jdbc-destroy-nested-config.xml")) { DataSource dataSource = context.getBean(DataSource.class); JdbcTemplate template = new JdbcTemplate(dataSource); assertNumRowsInTestTable(template, 1); @@ -131,15 +126,11 @@ public class JdbcNamespaceIntegrationTests { assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(() -> assertNumRowsInTestTable(template, 1)); } - finally { - context.close(); - } } @Test - public void createAndDestroyNestedWithH2() throws Exception { - ClassPathXmlApplicationContext context = context("jdbc-destroy-nested-config-h2.xml"); - try { + void createAndDestroyNestedWithH2() throws Exception { + try (ClassPathXmlApplicationContext context = context("jdbc-destroy-nested-config-h2.xml")) { DataSource dataSource = context.getBean(DataSource.class); JdbcTemplate template = new JdbcTemplate(dataSource); assertNumRowsInTestTable(template, 1); @@ -148,13 +139,10 @@ public class JdbcNamespaceIntegrationTests { assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy(() -> assertNumRowsInTestTable(template, 1)); } - finally { - context.close(); - } } @Test - public void multipleDataSourcesHaveDifferentDatabaseNames() throws Exception { + void multipleDataSourcesHaveDifferentDatabaseNames() throws Exception { DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(factory).loadBeanDefinitions(new ClassPathResource( "jdbc-config-multiple-datasources.xml", getClass())); @@ -163,12 +151,12 @@ public class JdbcNamespaceIntegrationTests { } @Test - public void initializeWithCustomSeparator() throws Exception { + void initializeWithCustomSeparator() throws Exception { assertCorrectSetupAndCloseContext("jdbc-initialize-custom-separator.xml", 2, "dataSource"); } @Test - public void embeddedWithCustomSeparator() throws Exception { + void embeddedWithCustomSeparator() throws Exception { assertCorrectSetupAndCloseContext("jdbc-config-custom-separator.xml", 2, "dataSource"); } @@ -192,8 +180,7 @@ public class JdbcNamespaceIntegrationTests { } private void assertCorrectSetupAndCloseContext(String file, int count, String... dataSources) { - ConfigurableApplicationContext context = context(file); - try { + try (ConfigurableApplicationContext context = context(file)) { for (String dataSourceName : dataSources) { DataSource dataSource = context.getBean(dataSourceName, DataSource.class); assertNumRowsInTestTable(new JdbcTemplate(dataSource), count); @@ -202,23 +189,16 @@ public class JdbcNamespaceIntegrationTests { assertThat(adbDataSource.getUrl()).contains(dataSourceName); } } - finally { - context.close(); - } } private void assertCorrectSetupForSingleDataSource(String file, Predicate urlPredicate) { - ConfigurableApplicationContext context = context(file); - try { + try (ConfigurableApplicationContext context = context(file)) { DataSource dataSource = context.getBean(DataSource.class); assertNumRowsInTestTable(new JdbcTemplate(dataSource), 1); assertThat(dataSource instanceof AbstractDriverBasedDataSource).isTrue(); AbstractDriverBasedDataSource adbDataSource = (AbstractDriverBasedDataSource) dataSource; assertThat(urlPredicate.test(adbDataSource.getUrl())).isTrue(); } - finally { - context.close(); - } } } diff --git a/spring-jms/src/test/java/org/springframework/jms/annotation/JmsListenerAnnotationBeanPostProcessorTests.java b/spring-jms/src/test/java/org/springframework/jms/annotation/JmsListenerAnnotationBeanPostProcessorTests.java index 54ecb8ee281..2c893899c79 100644 --- a/spring-jms/src/test/java/org/springframework/jms/annotation/JmsListenerAnnotationBeanPostProcessorTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/annotation/JmsListenerAnnotationBeanPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,10 +53,10 @@ import static org.mockito.Mockito.mock; * @author Stephane Nicoll * @author Juergen Hoeller */ -public class JmsListenerAnnotationBeanPostProcessorTests { +class JmsListenerAnnotationBeanPostProcessorTests { @Test - public void simpleMessageListener() throws Exception { + void simpleMessageListener() throws Exception { ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( Config.class, SimpleMessageListenerTestBean.class); @@ -81,11 +81,8 @@ public class JmsListenerAnnotationBeanPostProcessorTests { } @Test - public void metaAnnotationIsDiscovered() throws Exception { - ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( - Config.class, MetaAnnotationTestBean.class); - - try { + void metaAnnotationIsDiscovered() throws Exception { + try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(Config.class, MetaAnnotationTestBean.class)) { JmsListenerContainerTestFactory factory = context.getBean(JmsListenerContainerTestFactory.class); assertThat(factory.getListenerContainers().size()).as("one container should have been registered").isEqualTo(1); @@ -97,16 +94,11 @@ public class JmsListenerAnnotationBeanPostProcessorTests { assertThat(methodEndpoint.getMostSpecificMethod()).isEqualTo(MetaAnnotationTestBean.class.getMethod("handleIt", String.class)); assertThat(((AbstractJmsListenerEndpoint) endpoint).getDestination()).isEqualTo("metaTestQueue"); } - finally { - context.close(); - } } @Test - public void sendToAnnotationFoundOnInterfaceProxy() throws Exception { - ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( - Config.class, ProxyConfig.class, InterfaceProxyTestBean.class); - try { + void sendToAnnotationFoundOnInterfaceProxy() throws Exception { + try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(Config.class, ProxyConfig.class, InterfaceProxyTestBean.class)) { JmsListenerContainerTestFactory factory = context.getBean(JmsListenerContainerTestFactory.class); assertThat(factory.getListenerContainers().size()).as("one container should have been registered").isEqualTo(1); @@ -124,16 +116,11 @@ public class JmsListenerAnnotationBeanPostProcessorTests { Object destination = ReflectionUtils.invokeMethod(method, endpoint); assertThat(destination).as("SendTo annotation not found on proxy").isEqualTo("foobar"); } - finally { - context.close(); - } } @Test - public void sendToAnnotationFoundOnCglibProxy() throws Exception { - ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( - Config.class, ProxyConfig.class, ClassProxyTestBean.class); - try { + void sendToAnnotationFoundOnCglibProxy() throws Exception { + try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(Config.class, ProxyConfig.class, ClassProxyTestBean.class)) { JmsListenerContainerTestFactory factory = context.getBean(JmsListenerContainerTestFactory.class); assertThat(factory.getListenerContainers().size()).as("one container should have been registered").isEqualTo(1); @@ -151,14 +138,11 @@ public class JmsListenerAnnotationBeanPostProcessorTests { Object destination = ReflectionUtils.invokeMethod(method, endpoint); assertThat(destination).as("SendTo annotation not found on proxy").isEqualTo("foobar"); } - finally { - context.close(); - } } @Test @SuppressWarnings("resource") - public void invalidProxy() { + void invalidProxy() { assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> new AnnotationConfigApplicationContext(Config.class, ProxyConfig.class, InvalidProxyTestBean.class)) .withCauseInstanceOf(IllegalStateException.class) diff --git a/spring-orm/src/main/java/org/springframework/orm/jpa/persistenceunit/PersistenceUnitReader.java b/spring-orm/src/main/java/org/springframework/orm/jpa/persistenceunit/PersistenceUnitReader.java index 88d1894f39a..5a7083ab452 100644 --- a/spring-orm/src/main/java/org/springframework/orm/jpa/persistenceunit/PersistenceUnitReader.java +++ b/spring-orm/src/main/java/org/springframework/orm/jpa/persistenceunit/PersistenceUnitReader.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -130,14 +130,10 @@ final class PersistenceUnitReader { Resource[] resources = this.resourcePatternResolver.getResources(location); for (Resource resource : resources) { resourceLocation = resource.toString(); - InputStream stream = resource.getInputStream(); - try { + try (InputStream stream = resource.getInputStream()) { Document document = buildDocument(handler, stream); parseDocument(resource, document, infos); } - finally { - stream.close(); - } } } } diff --git a/spring-web/src/main/java/org/springframework/remoting/httpinvoker/AbstractHttpInvokerRequestExecutor.java b/spring-web/src/main/java/org/springframework/remoting/httpinvoker/AbstractHttpInvokerRequestExecutor.java index 39404c01eae..790d63ea899 100644 --- a/spring-web/src/main/java/org/springframework/remoting/httpinvoker/AbstractHttpInvokerRequestExecutor.java +++ b/spring-web/src/main/java/org/springframework/remoting/httpinvoker/AbstractHttpInvokerRequestExecutor.java @@ -166,13 +166,9 @@ public abstract class AbstractHttpInvokerRequestExecutor implements HttpInvokerR * @see #doWriteRemoteInvocation */ protected void writeRemoteInvocation(RemoteInvocation invocation, OutputStream os) throws IOException { - ObjectOutputStream oos = new ObjectOutputStream(decorateOutputStream(os)); - try { + try (ObjectOutputStream oos = new ObjectOutputStream(decorateOutputStream(os))) { doWriteRemoteInvocation(invocation, oos); } - finally { - oos.close(); - } } /** diff --git a/spring-web/src/main/java/org/springframework/remoting/httpinvoker/HttpInvokerServiceExporter.java b/spring-web/src/main/java/org/springframework/remoting/httpinvoker/HttpInvokerServiceExporter.java index 22ddb8fd045..3c863d67d7d 100644 --- a/spring-web/src/main/java/org/springframework/remoting/httpinvoker/HttpInvokerServiceExporter.java +++ b/spring-web/src/main/java/org/springframework/remoting/httpinvoker/HttpInvokerServiceExporter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2020 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. @@ -113,13 +113,9 @@ public class HttpInvokerServiceExporter extends RemoteInvocationSerializingExpor protected RemoteInvocation readRemoteInvocation(HttpServletRequest request, InputStream is) throws IOException, ClassNotFoundException { - ObjectInputStream ois = createObjectInputStream(decorateInputStream(request, is)); - try { + try (ObjectInputStream ois = createObjectInputStream(decorateInputStream(request, is))) { return doReadRemoteInvocation(ois); } - finally { - ois.close(); - } } /** @@ -170,14 +166,10 @@ public class HttpInvokerServiceExporter extends RemoteInvocationSerializingExpor HttpServletRequest request, HttpServletResponse response, RemoteInvocationResult result, OutputStream os) throws IOException { - ObjectOutputStream oos = - createObjectOutputStream(new FlushGuardedOutputStream(decorateOutputStream(request, response, os))); - try { + try (ObjectOutputStream oos = + createObjectOutputStream(new FlushGuardedOutputStream(decorateOutputStream(request, response, os)))) { doWriteRemoteInvocationResult(result, oos); } - finally { - oos.close(); - } } /** diff --git a/spring-web/src/test/java/org/springframework/http/client/AbstractAsyncHttpRequestFactoryTests.java b/spring-web/src/test/java/org/springframework/http/client/AbstractAsyncHttpRequestFactoryTests.java index 980fe77c0bf..c9e87892970 100644 --- a/spring-web/src/test/java/org/springframework/http/client/AbstractAsyncHttpRequestFactoryTests.java +++ b/spring-web/src/test/java/org/springframework/http/client/AbstractAsyncHttpRequestFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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. @@ -71,13 +71,9 @@ public abstract class AbstractAsyncHttpRequestFactoryTests extends AbstractMockW assertThat(request.getMethod()).as("Invalid HTTP method").isEqualTo(HttpMethod.GET); assertThat(request.getURI()).as("Invalid HTTP URI").isEqualTo(uri); Future futureResponse = request.executeAsync(); - ClientHttpResponse response = futureResponse.get(); - try { + try (ClientHttpResponse response = futureResponse.get()) { assertThat(response.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.NOT_FOUND); } - finally { - response.close(); - } } @Test @@ -102,13 +98,9 @@ public abstract class AbstractAsyncHttpRequestFactoryTests extends AbstractMockW throw new AssertionError(ex.getMessage(), ex); } }); - ClientHttpResponse response = listenableFuture.get(); - try { + try (ClientHttpResponse response = listenableFuture.get()) { assertThat(response.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.NOT_FOUND); } - finally { - response.close(); - } } @Test @@ -132,20 +124,17 @@ public abstract class AbstractAsyncHttpRequestFactoryTests extends AbstractMockW } Future futureResponse = request.executeAsync(); - ClientHttpResponse response = futureResponse.get(); - try { + try ( ClientHttpResponse response = futureResponse.get()) { assertThat(response.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK); assertThat(response.getHeaders().containsKey(headerName)).as("Header not found").isTrue(); assertThat(response.getHeaders().get(headerName)).as("Header value not found").isEqualTo(Arrays.asList(headerValue1, headerValue2)); byte[] result = FileCopyUtils.copyToByteArray(response.getBody()); assertThat(Arrays.equals(body, result)).as("Invalid body").isTrue(); } - finally { - response.close(); - } } @Test + @SuppressWarnings("try") public void multipleWrites() throws Exception { AsyncClientHttpRequest request = this.factory.createAsyncRequest(new URI(baseUrl + "/echo"), HttpMethod.POST); final byte[] body = "Hello World".getBytes("UTF-8"); @@ -159,17 +148,13 @@ public abstract class AbstractAsyncHttpRequestFactoryTests extends AbstractMockW } Future futureResponse = request.executeAsync(); - ClientHttpResponse response = futureResponse.get(); - try { - assertThatIllegalStateException().isThrownBy(() -> - FileCopyUtils.copy(body, request.getBody())); - } - finally { - response.close(); + try (ClientHttpResponse response = futureResponse.get()) { + assertThatIllegalStateException().isThrownBy(() -> FileCopyUtils.copy(body, request.getBody())); } } @Test + @SuppressWarnings("try") public void headersAfterExecute() throws Exception { AsyncClientHttpRequest request = this.factory.createAsyncRequest(new URI(baseUrl + "/echo"), HttpMethod.POST); request.getHeaders().add("MyHeader", "value"); @@ -177,14 +162,10 @@ public abstract class AbstractAsyncHttpRequestFactoryTests extends AbstractMockW FileCopyUtils.copy(body, request.getBody()); Future futureResponse = request.executeAsync(); - ClientHttpResponse response = futureResponse.get(); - try { + try (ClientHttpResponse response = futureResponse.get()) { assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> request.getHeaders().add("MyHeader", "value")); } - finally { - response.close(); - } } @Test @@ -198,23 +179,16 @@ public abstract class AbstractAsyncHttpRequestFactoryTests extends AbstractMockW } protected void assertHttpMethod(String path, HttpMethod method) throws Exception { - ClientHttpResponse response = null; - try { - AsyncClientHttpRequest request = this.factory.createAsyncRequest(new URI(baseUrl + "/methods/" + path), method); - if (method == HttpMethod.POST || method == HttpMethod.PUT || method == HttpMethod.PATCH) { - // requires a body - request.getBody().write(32); - } - Future futureResponse = request.executeAsync(); - response = futureResponse.get(); + AsyncClientHttpRequest request = this.factory.createAsyncRequest(new URI(baseUrl + "/methods/" + path), method); + if (method == HttpMethod.POST || method == HttpMethod.PUT || method == HttpMethod.PATCH) { + // requires a body + request.getBody().write(32); + } + Future futureResponse = request.executeAsync(); + try (ClientHttpResponse response = futureResponse.get()) { assertThat(response.getStatusCode()).as("Invalid response status").isEqualTo(HttpStatus.OK); assertThat(request.getMethod().name()).as("Invalid method").isEqualTo(path.toUpperCase(Locale.ENGLISH)); } - finally { - if (response != null) { - response.close(); - } - } } @Test @@ -226,5 +200,4 @@ public abstract class AbstractAsyncHttpRequestFactoryTests extends AbstractMockW assertThat(futureResponse.isCancelled()).isTrue(); } - } diff --git a/spring-web/src/test/java/org/springframework/http/client/AbstractHttpRequestFactoryTests.java b/spring-web/src/test/java/org/springframework/http/client/AbstractHttpRequestFactoryTests.java index 7538e2e6eb2..58a0a9cc697 100644 --- a/spring-web/src/test/java/org/springframework/http/client/AbstractHttpRequestFactoryTests.java +++ b/spring-web/src/test/java/org/springframework/http/client/AbstractHttpRequestFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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,13 +40,13 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * @author Arjen Poutsma */ -public abstract class AbstractHttpRequestFactoryTests extends AbstractMockWebServerTests { +abstract class AbstractHttpRequestFactoryTests extends AbstractMockWebServerTests { protected ClientHttpRequestFactory factory; @BeforeEach - public final void createFactory() throws Exception { + final void createFactory() throws Exception { factory = createRequestFactory(); if (factory instanceof InitializingBean) { ((InitializingBean) factory).afterPropertiesSet(); @@ -54,7 +54,7 @@ public abstract class AbstractHttpRequestFactoryTests extends AbstractMockWebSer } @AfterEach - public final void destroyFactory() throws Exception { + final void destroyFactory() throws Exception { if (factory instanceof DisposableBean) { ((DisposableBean) factory).destroy(); } @@ -65,7 +65,7 @@ public abstract class AbstractHttpRequestFactoryTests extends AbstractMockWebSer @Test - public void status() throws Exception { + void status() throws Exception { URI uri = new URI(baseUrl + "/status/notfound"); ClientHttpRequest request = factory.createRequest(uri, HttpMethod.GET); assertThat(request.getMethod()).as("Invalid HTTP method").isEqualTo(HttpMethod.GET); @@ -77,7 +77,7 @@ public abstract class AbstractHttpRequestFactoryTests extends AbstractMockWebSer } @Test - public void echo() throws Exception { + void echo() throws Exception { ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.PUT); assertThat(request.getMethod()).as("Invalid HTTP method").isEqualTo(HttpMethod.PUT); @@ -107,7 +107,7 @@ public abstract class AbstractHttpRequestFactoryTests extends AbstractMockWebSer } @Test - public void multipleWrites() throws Exception { + void multipleWrites() throws Exception { ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.POST); final byte[] body = "Hello World".getBytes(StandardCharsets.UTF_8); @@ -130,7 +130,7 @@ public abstract class AbstractHttpRequestFactoryTests extends AbstractMockWebSer @Test @SuppressWarnings("try") - public void headersAfterExecute() throws Exception { + void headersAfterExecute() throws Exception { ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/status/ok"), HttpMethod.POST); request.getHeaders().add("MyHeader", "value"); @@ -144,7 +144,7 @@ public abstract class AbstractHttpRequestFactoryTests extends AbstractMockWebSer } @Test - public void httpMethods() throws Exception { + void httpMethods() throws Exception { assertHttpMethod("get", HttpMethod.GET); assertHttpMethod("head", HttpMethod.HEAD); assertHttpMethod("post", HttpMethod.POST); @@ -154,31 +154,25 @@ public abstract class AbstractHttpRequestFactoryTests extends AbstractMockWebSer } protected void assertHttpMethod(String path, HttpMethod method) throws Exception { - ClientHttpResponse response = null; - try { - ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/methods/" + path), method); - if (method == HttpMethod.POST || method == HttpMethod.PUT || method == HttpMethod.PATCH) { - // requires a body - try { - request.getBody().write(32); - } - catch (UnsupportedOperationException ex) { - // probably a streaming request - let's simply ignore it - } + ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/methods/" + path), method); + if (method == HttpMethod.POST || method == HttpMethod.PUT || method == HttpMethod.PATCH) { + // requires a body + try { + request.getBody().write(32); } - response = request.execute(); + catch (UnsupportedOperationException ex) { + // probably a streaming request - let's simply ignore it + } + } + + try (ClientHttpResponse response = request.execute()) { assertThat(response.getStatusCode()).as("Invalid response status").isEqualTo(HttpStatus.OK); assertThat(request.getMethod().name()).as("Invalid method").isEqualTo(path.toUpperCase(Locale.ENGLISH)); } - finally { - if (response != null) { - response.close(); - } - } } @Test - public void queryParameters() throws Exception { + void queryParameters() throws Exception { URI uri = new URI(baseUrl + "/params?param1=value¶m2=value1¶m2=value2"); ClientHttpRequest request = factory.createRequest(uri, HttpMethod.GET); diff --git a/spring-web/src/test/java/org/springframework/http/client/BufferingClientHttpRequestFactoryTests.java b/spring-web/src/test/java/org/springframework/http/client/BufferingClientHttpRequestFactoryTests.java index b3c272324b4..131a923b55a 100644 --- a/spring-web/src/test/java/org/springframework/http/client/BufferingClientHttpRequestFactoryTests.java +++ b/spring-web/src/test/java/org/springframework/http/client/BufferingClientHttpRequestFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,7 @@ import org.springframework.util.FileCopyUtils; import static org.assertj.core.api.Assertions.assertThat; -public class BufferingClientHttpRequestFactoryTests extends AbstractHttpRequestFactoryTests { +class BufferingClientHttpRequestFactoryTests extends AbstractHttpRequestFactoryTests { @Override protected ClientHttpRequestFactory createRequestFactory() { @@ -35,7 +35,7 @@ public class BufferingClientHttpRequestFactoryTests extends AbstractHttpRequestF } @Test - public void repeatableRead() throws Exception { + void repeatableRead() throws Exception { ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.PUT); assertThat(request.getMethod()).as("Invalid HTTP method").isEqualTo(HttpMethod.PUT); String headerName = "MyHeader"; @@ -46,8 +46,7 @@ public class BufferingClientHttpRequestFactoryTests extends AbstractHttpRequestF byte[] body = "Hello World".getBytes("UTF-8"); request.getHeaders().setContentLength(body.length); FileCopyUtils.copy(body, request.getBody()); - ClientHttpResponse response = request.execute(); - try { + try (ClientHttpResponse response = request.execute()) { assertThat(response.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK); assertThat(response.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatus.OK); @@ -62,9 +61,6 @@ public class BufferingClientHttpRequestFactoryTests extends AbstractHttpRequestF FileCopyUtils.copyToByteArray(response.getBody()); assertThat(Arrays.equals(body, result)).as("Invalid body").isTrue(); } - finally { - response.close(); - } } } diff --git a/spring-websocket/src/test/java/org/springframework/web/socket/messaging/StompWebSocketIntegrationTests.java b/spring-websocket/src/test/java/org/springframework/web/socket/messaging/StompWebSocketIntegrationTests.java index f2e0eec1224..8c2cab0ec6d 100644 --- a/spring-websocket/src/test/java/org/springframework/web/socket/messaging/StompWebSocketIntegrationTests.java +++ b/spring-websocket/src/test/java/org/springframework/web/socket/messaging/StompWebSocketIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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. @@ -72,22 +72,20 @@ class StompWebSocketIntegrationTests extends AbstractWebSocketIntegrationTests { @ParameterizedWebSocketTest + @SuppressWarnings("try") void sendMessageToController(WebSocketTestServer server, WebSocketClient webSocketClient, TestInfo testInfo) throws Exception { super.setup(server, webSocketClient, testInfo); TextMessage message = create(StompCommand.SEND).headers("destination:/app/simple").build(); - WebSocketSession session = doHandshake(new TestClientWebSocketHandler(0, message), "/ws").get(); - SimpleController controller = this.wac.getBean(SimpleController.class); - try { + try (@SuppressWarnings("unused")WebSocketSession session = doHandshake(new TestClientWebSocketHandler(0, message), "/ws").get()) { + SimpleController controller = this.wac.getBean(SimpleController.class); assertThat(controller.latch.await(TIMEOUT, TimeUnit.SECONDS)).isTrue(); } - finally { - session.close(); - } } @ParameterizedWebSocketTest + @SuppressWarnings("try") void sendMessageToControllerAndReceiveReplyViaTopic(WebSocketTestServer server, WebSocketClient webSocketClient, TestInfo testInfo) throws Exception { super.setup(server, webSocketClient, testInfo); @@ -98,17 +96,14 @@ class StompWebSocketIntegrationTests extends AbstractWebSocketIntegrationTests { .headers("destination:/app/increment").body("5").build(); TestClientWebSocketHandler clientHandler = new TestClientWebSocketHandler(2, m0, m1, m2); - WebSocketSession session = doHandshake(clientHandler, "/ws").get(); - try { + try (WebSocketSession session = doHandshake(clientHandler, "/ws").get()) { assertThat(clientHandler.latch.await(TIMEOUT, TimeUnit.SECONDS)).isTrue(); } - finally { - session.close(); - } } @ParameterizedWebSocketTest // SPR-10930 + @SuppressWarnings("try") void sendMessageToBrokerAndReceiveReplyViaTopic(WebSocketTestServer server, WebSocketClient webSocketClient, TestInfo testInfo) throws Exception { super.setup(server, webSocketClient, testInfo); @@ -117,20 +112,17 @@ class StompWebSocketIntegrationTests extends AbstractWebSocketIntegrationTests { TextMessage m2 = create(StompCommand.SEND).headers("destination:/topic/foo").body("5").build(); TestClientWebSocketHandler clientHandler = new TestClientWebSocketHandler(2, m0, m1, m2); - WebSocketSession session = doHandshake(clientHandler, "/ws").get(); - try { + try (WebSocketSession session = doHandshake(clientHandler, "/ws").get()) { assertThat(clientHandler.latch.await(TIMEOUT, TimeUnit.SECONDS)).isTrue(); String payload = clientHandler.actual.get(1).getPayload(); assertThat(payload.startsWith("MESSAGE\n")).as("Expected STOMP MESSAGE, got " + payload).isTrue(); } - finally { - session.close(); - } } @ParameterizedWebSocketTest // SPR-11648 + @SuppressWarnings("try") void sendSubscribeToControllerAndReceiveReply(WebSocketTestServer server, WebSocketClient webSocketClient, TestInfo testInfo) throws Exception { super.setup(server, webSocketClient, testInfo); @@ -139,20 +131,17 @@ class StompWebSocketIntegrationTests extends AbstractWebSocketIntegrationTests { TextMessage m1 = create(StompCommand.SUBSCRIBE).headers("id:subs1", destHeader).build(); TestClientWebSocketHandler clientHandler = new TestClientWebSocketHandler(2, m0, m1); - WebSocketSession session = doHandshake(clientHandler, "/ws").get(); - try { + try (WebSocketSession session = doHandshake(clientHandler, "/ws").get()) { assertThat(clientHandler.latch.await(TIMEOUT, TimeUnit.SECONDS)).isTrue(); String payload = clientHandler.actual.get(1).getPayload(); assertThat(payload.contains(destHeader)).as("Expected STOMP destination=/app/number, got " + payload).isTrue(); assertThat(payload.contains("42")).as("Expected STOMP Payload=42, got " + payload).isTrue(); } - finally { - session.close(); - } } @ParameterizedWebSocketTest + @SuppressWarnings("try") void handleExceptionAndSendToUser(WebSocketTestServer server, WebSocketClient webSocketClient, TestInfo testInfo) throws Exception { super.setup(server, webSocketClient, testInfo); @@ -162,21 +151,18 @@ class StompWebSocketIntegrationTests extends AbstractWebSocketIntegrationTests { TextMessage m2 = create(StompCommand.SEND).headers("destination:/app/exception").build(); TestClientWebSocketHandler clientHandler = new TestClientWebSocketHandler(2, m0, m1, m2); - WebSocketSession session = doHandshake(clientHandler, "/ws").get(); - try { + try (WebSocketSession session = doHandshake(clientHandler, "/ws").get()) { assertThat(clientHandler.latch.await(TIMEOUT, TimeUnit.SECONDS)).isTrue(); String payload = clientHandler.actual.get(1).getPayload(); assertThat(payload.startsWith("MESSAGE\n")).isTrue(); assertThat(payload.contains("destination:/user/queue/error\n")).isTrue(); assertThat(payload.endsWith("Got error: Bad input\0")).isTrue(); } - finally { - session.close(); - } } @ParameterizedWebSocketTest + @SuppressWarnings("try") void webSocketScope(WebSocketTestServer server, WebSocketClient webSocketClient, TestInfo testInfo) throws Exception { super.setup(server, webSocketClient, testInfo); @@ -187,18 +173,14 @@ class StompWebSocketIntegrationTests extends AbstractWebSocketIntegrationTests { .headers("destination:/app/scopedBeanValue").build(); TestClientWebSocketHandler clientHandler = new TestClientWebSocketHandler(2, m0, m1, m2); - WebSocketSession session = doHandshake(clientHandler, "/ws").get(); - try { + try (WebSocketSession session = doHandshake(clientHandler, "/ws").get()) { assertThat(clientHandler.latch.await(TIMEOUT, TimeUnit.SECONDS)).isTrue(); String payload = clientHandler.actual.get(1).getPayload(); assertThat(payload.startsWith("MESSAGE\n")).isTrue(); assertThat(payload.contains("destination:/topic/scopedBeanValue\n")).isTrue(); assertThat(payload.endsWith("55\0")).isTrue(); } - finally { - session.close(); - } }