From 04fdec6f8be7ce57362ad3e465fccf9ef1604fae Mon Sep 17 00:00:00 2001 From: Emanuel Campolo Date: Tue, 18 Jul 2017 11:50:10 -0300 Subject: [PATCH 1/6] Replace explicit generics with diamond operator Where possible, explicit generic declarations to use the Java 8 diamond operator. See gh-9781 --- .../autoconfigure/ManagementServerProperties.java | 2 +- .../boot/actuate/endpoint/EnvironmentEndpoint.java | 2 +- .../actuate/health/CompositeHealthIndicator.java | 2 +- .../boot/actuate/trace/WebRequestTraceFilter.java | 2 +- .../actuate/endpoint/CachePublicMetricsTests.java | 4 ++-- ...nPropertiesReportEndpointSerializationTests.java | 4 ++-- .../actuate/endpoint/EnvironmentEndpointTests.java | 2 +- .../endpoint/mvc/EnvironmentMvcEndpointTests.java | 6 +++--- .../metrics/statsd/StatsdMetricWriterTests.java | 4 ++-- .../ImportAutoConfigurationImportSelector.java | 2 +- .../elasticsearch/jest/JestProperties.java | 2 +- .../boot/autoconfigure/flyway/FlywayProperties.java | 2 +- .../FreeMarkerTemplateAvailabilityProvider.java | 2 +- .../GroovyTemplateAvailabilityProvider.java | 2 +- .../embedded/EmbeddedLdapAutoConfiguration.java | 3 +-- .../embedded/EmbeddedMongoAutoConfiguration.java | 3 +-- .../oauth2/resource/UserInfoTokenServicesTests.java | 2 +- .../autoconfigure/web/ServerPropertiesTests.java | 4 ++-- ...faultServletWebServerFactoryCustomizerTests.java | 6 +++--- .../DevToolsDataSourceAutoConfiguration.java | 3 +-- ...actEmbeddedServletContainerIntegrationTests.java | 2 +- .../embedded/BootRunApplicationLauncher.java | 2 +- .../context/embedded/IdeApplicationLauncher.java | 2 +- .../properties/AnnotationsPropertySource.java | 2 +- .../context/SpringBootTestContextBootstrapper.java | 2 +- ...DuplicateJsonObjectContextCustomizerFactory.java | 2 +- .../boot/test/json/JacksonTester.java | 2 +- .../gradle/tasks/bundling/BootArchiveSupport.java | 4 ++-- .../gradle/tasks/bundling/BootZipCopyAction.java | 2 +- .../tasks/bundling/LaunchScriptConfiguration.java | 2 +- .../boot/gradle/tasks/bundling/PomCondition.java | 2 +- .../boot/gradle/testkit/GradleBuild.java | 2 +- .../boot/loader/PropertiesLauncher.java | 4 ++-- .../boot/loader/util/SystemPropertyUtils.java | 4 ++-- .../boot/loader/PropertiesLauncherTests.java | 2 +- .../runner/classpath/ModifiedClassPathRunner.java | 13 ++++++------- .../springframework/boot/EnvironmentConverter.java | 4 ++-- .../source/ConfigurationPropertyName.java | 4 ++-- .../boot/env/OriginTrackedYamlLoader.java | 2 +- .../boot/jta/narayana/NarayanaProperties.java | 6 +++--- ...ServerPortInfoApplicationContextInitializer.java | 2 +- .../undertow/UndertowServletWebServerFactory.java | 2 +- ...gurationPropertiesBindingPostProcessorTests.java | 2 +- ...rverFactoryCustomizerBeanPostProcessorTests.java | 2 +- 44 files changed, 64 insertions(+), 68 deletions(-) diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ManagementServerProperties.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ManagementServerProperties.java index b8b1016974..2ec0b4910c 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ManagementServerProperties.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ManagementServerProperties.java @@ -169,7 +169,7 @@ public class ManagementServerProperties implements SecurityPrerequisite { /** * Comma-separated list of roles that can access the management endpoint. */ - private List roles = new ArrayList( + private List roles = new ArrayList<>( Collections.singletonList("ACTUATOR")); /** diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/EnvironmentEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/EnvironmentEndpoint.java index 3a8c4cac00..d34455cf52 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/EnvironmentEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/EnvironmentEndpoint.java @@ -89,7 +89,7 @@ public class EnvironmentEndpoint extends AbstractEndpoint> { } private Map> getPropertySourcesAsMap() { - Map> map = new LinkedHashMap>(); + Map> map = new LinkedHashMap<>(); for (PropertySource source : getPropertySources()) { extract("", map, source); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CompositeHealthIndicator.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CompositeHealthIndicator.java index 7018ad18cf..5e5f4c2cbb 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CompositeHealthIndicator.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CompositeHealthIndicator.java @@ -40,7 +40,7 @@ public class CompositeHealthIndicator implements HealthIndicator { * @param healthAggregator the health aggregator */ public CompositeHealthIndicator(HealthAggregator healthAggregator) { - this(healthAggregator, new LinkedHashMap()); + this(healthAggregator, new LinkedHashMap<>()); } /** diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/WebRequestTraceFilter.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/WebRequestTraceFilter.java index 78cf2b5630..f8066711a7 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/WebRequestTraceFilter.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/WebRequestTraceFilter.java @@ -191,7 +191,7 @@ public class WebRequestTraceFilter extends OncePerRequestFilter implements Order } private Map getParameterMapCopy(HttpServletRequest request) { - return new LinkedHashMap(request.getParameterMap()); + return new LinkedHashMap<>(request.getParameterMap()); } /** diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/CachePublicMetricsTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/CachePublicMetricsTests.java index 9986fbbe4f..fbeaac45d1 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/CachePublicMetricsTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/CachePublicMetricsTests.java @@ -45,7 +45,7 @@ import static org.assertj.core.api.Assertions.entry; */ public class CachePublicMetricsTests { - private Map cacheManagers = new HashMap(); + private Map cacheManagers = new HashMap<>(); @Before public void setup() { @@ -98,7 +98,7 @@ public class CachePublicMetricsTests { private Map metrics(CachePublicMetrics cpm) { Collection> metrics = cpm.metrics(); assertThat(metrics).isNotNull(); - Map result = new HashMap(); + Map result = new HashMap<>(); for (Metric metric : metrics) { result.put(metric.getName(), metric.getValue()); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointSerializationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointSerializationTests.java index b4a8bdae6a..37f8da43b5 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointSerializationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ConfigurationPropertiesReportEndpointSerializationTests.java @@ -435,9 +435,9 @@ public class ConfigurationPropertiesReportEndpointSerializationTests { public static class InitializedMapAndListProperties extends Foo { - private Map map = new HashMap(); + private Map map = new HashMap<>(); - private List list = new ArrayList(); + private List list = new ArrayList<>(); public Map getMap() { return this.map; diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EnvironmentEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EnvironmentEndpointTests.java index 72ec5333fc..9577dadc26 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EnvironmentEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EnvironmentEndpointTests.java @@ -268,7 +268,7 @@ public class EnvironmentEndpointTests extends AbstractEndpointTests source = new HashMap(); + Map source = new HashMap<>(); source.put("foo", Collections.singletonMap("bar", "baz")); propertySources.addFirst(new MapPropertySource("test", source)); this.context.register(Config.class); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/EnvironmentMvcEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/EnvironmentMvcEndpointTests.java index fe22fdbc6a..12572e9f77 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/EnvironmentMvcEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/EnvironmentMvcEndpointTests.java @@ -142,7 +142,7 @@ public class EnvironmentMvcEndpointTests { @Test public void nestedPathWhenPlaceholderCannotBeResolvedShouldReturnUnresolvedProperty() throws Exception { - Map map = new HashMap(); + Map map = new HashMap<>(); map.put("my.foo", "${my.bar}"); ((ConfigurableEnvironment) this.context.getEnvironment()).getPropertySources() .addFirst(new MapPropertySource("unresolved-placeholder", map)); @@ -152,7 +152,7 @@ public class EnvironmentMvcEndpointTests { @Test public void nestedPathWithSensitivePlaceholderShouldSanitize() throws Exception { - Map map = new HashMap(); + Map map = new HashMap<>(); map.put("my.foo", "${my.password}"); map.put("my.password", "hello"); ((ConfigurableEnvironment) this.context.getEnvironment()).getPropertySources() @@ -165,7 +165,7 @@ public class EnvironmentMvcEndpointTests { public void propertyWithTypeOtherThanStringShouldNotFail() throws Exception { MutablePropertySources propertySources = ((ConfigurableEnvironment) this.context .getEnvironment()).getPropertySources(); - Map source = new HashMap(); + Map source = new HashMap<>(); source.put("foo", Collections.singletonMap("bar", "baz")); propertySources.addFirst(new MapPropertySource("test", source)); this.mvc.perform(get("/application/env/foo.*")).andExpect(status().isOk()) diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/statsd/StatsdMetricWriterTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/statsd/StatsdMetricWriterTests.java index 4bd5295825..936d4586f8 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/statsd/StatsdMetricWriterTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/statsd/StatsdMetricWriterTests.java @@ -97,7 +97,7 @@ public class StatsdMetricWriterTests { @Test public void incrementMetricWithInvalidCharsInName() throws Exception { - this.writer.increment(new Delta("counter.fo:o", 3L)); + this.writer.increment(new Delta<>("counter.fo:o", 3L)); this.server.waitForMessage(); assertThat(this.server.messagesReceived().get(0)) .isEqualTo("me.counter.fo-o:3|c"); @@ -105,7 +105,7 @@ public class StatsdMetricWriterTests { @Test public void setMetricWithInvalidCharsInName() throws Exception { - this.writer.set(new Metric("gauge.f:o:o", 3L)); + this.writer.set(new Metric<>("gauge.f:o:o", 3L)); this.server.waitForMessage(); assertThat(this.server.messagesReceived().get(0)).isEqualTo("me.gauge.f-o-o:3|g"); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelector.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelector.java index 539a7df929..c3d3ce0675 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelector.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelector.java @@ -134,7 +134,7 @@ class ImportAutoConfigurationImportSelector extends AutoConfigurationImportSelec AnnotationMetadata metadata) { MultiValueMap, Annotation> annotations = new LinkedMultiValueMap<>(); Class source = ClassUtils.resolveClassName(metadata.getClassName(), null); - collectAnnotations(source, annotations, new HashSet>()); + collectAnnotations(source, annotations, new HashSet<>()); return Collections.unmodifiableMap(annotations); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestProperties.java index f4797969c7..2fe572e3d9 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestProperties.java @@ -34,7 +34,7 @@ public class JestProperties { /** * Comma-separated list of the Elasticsearch instances to use. */ - private List uris = new ArrayList( + private List uris = new ArrayList<>( Collections.singletonList("http://localhost:9200")); /** diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayProperties.java index 5423847ba0..407dac29ed 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayProperties.java @@ -73,7 +73,7 @@ public class FlywayProperties { * SQL statements to execute to initialize a connection immediately after obtaining * it. */ - private List initSqls = new ArrayList(); + private List initSqls = new ArrayList<>(); public void setLocations(List locations) { this.locations = locations; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProvider.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProvider.java index 55849cf9ce..c917f8633f 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProvider.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProvider.java @@ -41,7 +41,7 @@ public class FreeMarkerTemplateAvailabilityProvider static final class FreeMarkerTemplateAvailabilityProperties extends TemplateAvailabilityProperties { - private List templateLoaderPath = new ArrayList( + private List templateLoaderPath = new ArrayList<>( Arrays.asList(FreeMarkerProperties.DEFAULT_TEMPLATE_LOADER_PATH)); FreeMarkerTemplateAvailabilityProperties() { diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProvider.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProvider.java index fbc55fe7f5..90d39ccea7 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProvider.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProvider.java @@ -41,7 +41,7 @@ public class GroovyTemplateAvailabilityProvider static final class GroovyTemplateAvailabilityProperties extends TemplateAvailabilityProperties { - private List resourceLoaderPath = new ArrayList( + private List resourceLoaderPath = new ArrayList<>( Arrays.asList(GroovyTemplateProperties.DEFAULT_RESOURCE_LOADER_PATH)); GroovyTemplateAvailabilityProperties() { 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 e43fd0bf92..c4605e9c10 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 @@ -181,8 +181,7 @@ public class EmbeddedLdapAutoConfiguration { private Map getLdapPorts(MutablePropertySources sources) { PropertySource propertySource = sources.get(PROPERTY_SOURCE_NAME); if (propertySource == null) { - propertySource = new MapPropertySource(PROPERTY_SOURCE_NAME, - new HashMap()); + propertySource = new MapPropertySource(PROPERTY_SOURCE_NAME, new HashMap<>()); sources.addFirst(propertySource); } return (Map) propertySource.getSource(); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfiguration.java index 77d1eef674..725be1bd52 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfiguration.java @@ -179,8 +179,7 @@ public class EmbeddedMongoAutoConfiguration { private Map getMongoPorts(MutablePropertySources sources) { PropertySource propertySource = sources.get("mongo.ports"); if (propertySource == null) { - propertySource = new MapPropertySource("mongo.ports", - new HashMap()); + propertySource = new MapPropertySource("mongo.ports", new HashMap<>()); sources.addFirst(propertySource); } return (Map) propertySource.getSource(); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServicesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServicesTests.java index 4ac1457cb9..a286fb363e 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServicesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServicesTests.java @@ -64,7 +64,7 @@ public class UserInfoTokenServicesTests { public void init() { this.resource.setClientId("foo"); given(this.template.getForEntity(any(String.class), eq(Map.class))) - .willReturn(new ResponseEntity(this.map, HttpStatus.OK)); + .willReturn(new ResponseEntity<>(this.map, HttpStatus.OK)); given(this.template.getAccessToken()) .willReturn(new DefaultOAuth2AccessToken("FOO")); given(this.template.getResource()).willReturn(this.resource); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java index fc8ea5439a..95c67693e0 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java @@ -120,7 +120,7 @@ public class ServerPropertiesTests { @Test public void redirectContextRootIsNotConfiguredByDefault() throws Exception { - bind(new HashMap()); + bind(new HashMap<>()); ServerProperties.Tomcat tomcat = this.properties.getTomcat(); assertThat(tomcat.getRedirectContextRoot()).isNull(); } @@ -164,7 +164,7 @@ public class ServerPropertiesTests { @Test public void testCustomizeJettyAccessLog() throws Exception { - Map map = new HashMap(); + Map map = new HashMap<>(); map.put("server.jetty.accesslog.enabled", "true"); map.put("server.jetty.accesslog.filename", "foo.txt"); map.put("server.jetty.accesslog.file-date-format", "yyyymmdd"); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/DefaultServletWebServerFactoryCustomizerTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/DefaultServletWebServerFactoryCustomizerTests.java index ff31665c23..b4372cc5e8 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/DefaultServletWebServerFactoryCustomizerTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/DefaultServletWebServerFactoryCustomizerTests.java @@ -107,7 +107,7 @@ public class DefaultServletWebServerFactoryCustomizerTests { @Test public void tomcatAccessLogFileDateFormatByDefault() { TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(); - Map map = new HashMap(); + Map map = new HashMap<>(); map.put("server.tomcat.accesslog.enabled", "true"); bindProperties(map); this.customizer.customize(factory); @@ -118,7 +118,7 @@ public class DefaultServletWebServerFactoryCustomizerTests { @Test public void tomcatAccessLogFileDateFormatCanBeRedefined() { TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(); - Map map = new HashMap(); + Map map = new HashMap<>(); map.put("server.tomcat.accesslog.enabled", "true"); map.put("server.tomcat.accesslog.file-date-format", "yyyy-MM-dd.HH"); bindProperties(map); @@ -397,7 +397,7 @@ public class DefaultServletWebServerFactoryCustomizerTests { @Test public void customTomcatDisableMaxHttpPostSize() { - Map map = new HashMap(); + Map map = new HashMap<>(); map.put("server.tomcat.max-http-post-size", "-1"); bindProperties(map); TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(0); diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.java index 8ecf52b1bd..218592072e 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.java @@ -126,8 +126,7 @@ public class DevToolsDataSourceAutoConfiguration { InMemoryDatabase(String urlPrefix, String... driverClassNames) { this.urlPrefix = urlPrefix; - this.driverClassNames = new HashSet( - Arrays.asList(driverClassNames)); + this.driverClassNames = new HashSet<>(Arrays.asList(driverClassNames)); } boolean matches(DataSourceProperties properties) { diff --git a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerIntegrationTests.java b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerIntegrationTests.java index 70fb93d2bf..183490b191 100644 --- a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerIntegrationTests.java +++ b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/AbstractEmbeddedServletContainerIntegrationTests.java @@ -58,7 +58,7 @@ public abstract class AbstractEmbeddedServletContainerIntegrationTests { private static List createParameters(String packaging, String container, List> applicationLaunchers) { - List parameters = new ArrayList(); + List parameters = new ArrayList<>(); ApplicationBuilder applicationBuilder = new ApplicationBuilder(temporaryFolder, packaging, container); for (Class launcherClass : applicationLaunchers) { diff --git a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/BootRunApplicationLauncher.java b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/BootRunApplicationLauncher.java index f5a87f5b42..3eb6033d15 100644 --- a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/BootRunApplicationLauncher.java +++ b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/BootRunApplicationLauncher.java @@ -56,7 +56,7 @@ class BootRunApplicationLauncher extends AbstractApplicationLauncher { if (archive.getName().endsWith(".war")) { populateSrcMainWebapp(); } - List classpath = new ArrayList(); + List classpath = new ArrayList<>(); classpath.add(targetClasses.getAbsolutePath()); for (File dependency : dependencies.listFiles()) { classpath.add(dependency.getAbsolutePath()); diff --git a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/IdeApplicationLauncher.java b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/IdeApplicationLauncher.java index 4bb6485572..949c8cb145 100644 --- a/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/IdeApplicationLauncher.java +++ b/spring-boot-integration-tests/spring-boot-integration-tests-embedded-servlet-container/src/test/java/org/springframework/boot/context/embedded/IdeApplicationLauncher.java @@ -67,7 +67,7 @@ class IdeApplicationLauncher extends AbstractApplicationLauncher { if (archive.getName().endsWith(".war")) { populateSrcMainWebapp(); } - List classpath = new ArrayList(); + List classpath = new ArrayList<>(); classpath.add(targetClasses.getAbsolutePath()); for (File dependency : dependencies.listFiles()) { classpath.add(dependency.getAbsolutePath()); diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySource.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySource.java index eaba4fc3bf..bd6696cf8f 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySource.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySource.java @@ -60,7 +60,7 @@ public class AnnotationsPropertySource extends EnumerablePropertySource private Map getProperties(Class source) { Map properties = new LinkedHashMap<>(); - collectProperties(source, source, properties, new HashSet>()); + collectProperties(source, source, properties, new HashSet<>()); return Collections.unmodifiableMap(properties); } diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextBootstrapper.java b/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextBootstrapper.java index 3ce6e5f1c6..88e601b9a6 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextBootstrapper.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextBootstrapper.java @@ -219,7 +219,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr ContextConfiguration configuration) { ContextConfigurationAttributes attributes = new ContextConfigurationAttributes( candidateConfig.getTestClass(), configuration); - Set> configurationClasses = new HashSet>( + Set> configurationClasses = new HashSet<>( Arrays.asList(attributes.getClasses())); for (Class candidate : candidateConfig.getClasses()) { if (configurationClasses.contains(candidate)) { diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactory.java b/spring-boot-test/src/main/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactory.java index b6abcdc20d..d83c3e9cf4 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactory.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactory.java @@ -60,7 +60,7 @@ class DuplicateJsonObjectContextCustomizerFactory implements ContextCustomizerFa } private List findJsonObjects() { - List jsonObjects = new ArrayList(); + List jsonObjects = new ArrayList<>(); try { Enumeration resources = getClass().getClassLoader() .getResources("org/json/JSONObject.class"); diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/json/JacksonTester.java b/spring-boot-test/src/main/java/org/springframework/boot/test/json/JacksonTester.java index 91c79a1e5a..ffc6e0df60 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/json/JacksonTester.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/json/JacksonTester.java @@ -158,7 +158,7 @@ public class JacksonTester extends AbstractJsonMarshalTester { * @return the new instance */ public JacksonTester forView(Class view) { - return new JacksonTester(this.getResourceLoadClass(), this.getType(), + return new JacksonTester<>(this.getResourceLoadClass(), this.getType(), this.objectMapper, view); } diff --git a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootArchiveSupport.java b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootArchiveSupport.java index 0dabcaf3cf..10876ea74c 100644 --- a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootArchiveSupport.java +++ b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootArchiveSupport.java @@ -46,7 +46,7 @@ class BootArchiveSupport { private static final Set DEFAULT_LAUNCHER_CLASSES; static { - Set defaultLauncherClasses = new HashSet(); + Set defaultLauncherClasses = new HashSet<>(); defaultLauncherClasses.add("org.springframework.boot.loader.JarLauncher"); defaultLauncherClasses.add("org.springframework.boot.loader.PropertiesLauncher"); defaultLauncherClasses.add("org.springframework.boot.loader.WarLauncher"); @@ -121,7 +121,7 @@ class BootArchiveSupport { } private void configureExclusions() { - Set excludes = new HashSet(); + Set excludes = new HashSet<>(); if (this.excludeDevtools) { excludes.add("**/spring-boot-devtools-*.jar"); } diff --git a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootZipCopyAction.java b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootZipCopyAction.java index 71dd5b8e1d..9ce874dfc3 100644 --- a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootZipCopyAction.java +++ b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootZipCopyAction.java @@ -132,7 +132,7 @@ class BootZipCopyAction implements CopyAction { private Spec writeLoaderClasses(ZipArchiveOutputStream out) { try (ZipInputStream in = new ZipInputStream(getClass() .getResourceAsStream("/META-INF/loader/spring-boot-loader.jar"))) { - Set entries = new HashSet(); + Set entries = new HashSet<>(); java.util.zip.ZipEntry entry; while ((entry = in.getNextEntry()) != null) { if (entry.isDirectory() && !entry.getName().startsWith("META-INF/")) { diff --git a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/LaunchScriptConfiguration.java b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/LaunchScriptConfiguration.java index 40ee454fb5..8aa4cae905 100644 --- a/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/LaunchScriptConfiguration.java +++ b/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/LaunchScriptConfiguration.java @@ -34,7 +34,7 @@ public class LaunchScriptConfiguration implements Serializable { private boolean included = false; - private final Map properties = new HashMap(); + private final Map properties = new HashMap<>(); private File script; diff --git a/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/PomCondition.java b/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/PomCondition.java index b3d8f293a6..c991ebe04b 100644 --- a/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/PomCondition.java +++ b/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/PomCondition.java @@ -40,7 +40,7 @@ class PomCondition extends Condition { private Set notExpectedContents; PomCondition() { - this(new HashSet(), new HashSet()); + this(new HashSet<>(), new HashSet<>()); } private PomCondition(Set expectedContents, Set notExpectedContents) { diff --git a/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/testkit/GradleBuild.java b/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/testkit/GradleBuild.java index 24328e4556..68922cd64f 100644 --- a/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/testkit/GradleBuild.java +++ b/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/testkit/GradleBuild.java @@ -160,7 +160,7 @@ public class GradleBuild implements TestRule { if (this.gradleVersion != null) { gradleRunner.withGradleVersion(this.gradleVersion); } - List allArguments = new ArrayList(); + List allArguments = new ArrayList<>(); allArguments.add("-PpluginClasspath=" + pluginClasspath()); allArguments.add("-PbootVersion=" + getBootVersion()); allArguments.add("--stacktrace"); 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 b361c7ee52..a79d23256e 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 @@ -330,7 +330,7 @@ public class PropertiesLauncher extends Launcher { @Override protected ClassLoader createClassLoader(List archives) throws Exception { - Set urls = new LinkedHashSet(archives.size()); + Set urls = new LinkedHashSet<>(archives.size()); for (Archive archive : archives) { urls.add(archive.getUrl()); } @@ -522,7 +522,7 @@ public class PropertiesLauncher extends Launcher { root = ""; } EntryFilter filter = new PrefixMatchingArchiveFilter(root); - List archives = new ArrayList(parent.getNestedArchives(filter)); + List archives = new ArrayList<>(parent.getNestedArchives(filter)); if (("".equals(root) || ".".equals(root)) && !path.endsWith(".jar") && parent != this.parent) { // You can't find the root with an entry filter so it has to be added diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/util/SystemPropertyUtils.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/util/SystemPropertyUtils.java index 2bbfa8bf0f..42cc44ade2 100644 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/util/SystemPropertyUtils.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/util/SystemPropertyUtils.java @@ -66,7 +66,7 @@ public abstract class SystemPropertyUtils { if (text == null) { return text; } - return parseStringValue(null, text, text, new HashSet()); + return parseStringValue(null, text, text, new HashSet<>()); } /** @@ -83,7 +83,7 @@ public abstract class SystemPropertyUtils { if (text == null) { return text; } - return parseStringValue(properties, text, text, new HashSet()); + return parseStringValue(properties, text, text, new HashSet<>()); } private static String parseStringValue(Properties properties, String value, diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java index c62bd797bc..b1a3059a53 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java @@ -266,7 +266,7 @@ public class PropertiesLauncherTests { } private List archives() throws Exception { - List archives = new ArrayList(); + List archives = new ArrayList<>(); String path = System.getProperty("java.class.path"); for (String url : path.split(File.pathSeparator)) { archives.add(archive(url)); diff --git a/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunner.java b/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunner.java index 6a61981469..d09fcd5411 100644 --- a/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunner.java +++ b/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunner.java @@ -100,7 +100,7 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { } private URL[] extractUrls(URLClassLoader classLoader) throws Exception { - List extractedUrls = new ArrayList(); + List extractedUrls = new ArrayList<>(); for (URL url : classLoader.getURLs()) { if (isSurefireBooterJar(url)) { extractedUrls.addAll(extractUrlsFromManifestClassPath(url)); @@ -117,7 +117,7 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { } private List extractUrlsFromManifestClassPath(URL booterJar) throws Exception { - List urls = new ArrayList(); + List urls = new ArrayList<>(); for (String entry : getClassPath(booterJar)) { urls.add(new URL(entry)); } @@ -133,7 +133,7 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { private URL[] processUrls(URL[] urls, Class testClass) throws Exception { ClassPathEntryFilter filter = new ClassPathEntryFilter(testClass); - List processedUrls = new ArrayList(); + List processedUrls = new ArrayList<>(); processedUrls.addAll(getAdditionalUrls(testClass)); for (URL url : urls) { if (!filter.isExcluded(url)) { @@ -173,7 +173,7 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, null); DependencyResult result = repositorySystem.resolveDependencies(session, dependencyRequest); - List resolvedArtifacts = new ArrayList(); + List resolvedArtifacts = new ArrayList<>(); for (ArtifactResult artifact : result.getArtifactResults()) { resolvedArtifacts.add(artifact.getArtifact().getFile().toURI().toURL()); } @@ -181,7 +181,7 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { } private List createDependencies(String[] allCoordinates) { - List dependencies = new ArrayList(); + List dependencies = new ArrayList<>(); for (String coordinate : allCoordinates) { dependencies.add(new Dependency(new DefaultArtifact(coordinate), null)); } @@ -254,8 +254,7 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { private List wrapFrameworkMethods( List methods) { - List wrapped = new ArrayList( - methods.size()); + List wrapped = new ArrayList<>(methods.size()); for (FrameworkMethod frameworkMethod : methods) { wrapped.add(new ModifiedClassPathFrameworkMethod( frameworkMethod.getMethod())); diff --git a/spring-boot/src/main/java/org/springframework/boot/EnvironmentConverter.java b/spring-boot/src/main/java/org/springframework/boot/EnvironmentConverter.java index d99ca1cf1d..8087f70fe8 100644 --- a/spring-boot/src/main/java/org/springframework/boot/EnvironmentConverter.java +++ b/spring-boot/src/main/java/org/springframework/boot/EnvironmentConverter.java @@ -42,7 +42,7 @@ final class EnvironmentConverter { private static final Set SERVLET_ENVIRONMENT_SOURCE_NAMES; static { - final Set names = new HashSet(); + final Set names = new HashSet<>(); names.add(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME); names.add(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME); names.add(StandardServletEnvironment.JNDI_PROPERTY_SOURCE_NAME); @@ -109,7 +109,7 @@ final class EnvironmentConverter { } private void removeAllPropertySources(MutablePropertySources propertySources) { - Set names = new HashSet(); + Set names = new HashSet<>(); for (PropertySource propertySource : propertySources) { names.add(propertySource.getName()); } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyName.java b/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyName.java index 8516461a70..f621665692 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyName.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyName.java @@ -451,7 +451,7 @@ public final class ConfigurationPropertyName if (name.length() == 0) { return EMPTY; } - List elements = new ArrayList(10); + List elements = new ArrayList<>(10); process(name, '.', (elementValue, start, end, indexed) -> { if (elementValue.length() > 0) { if (!indexed) { @@ -496,7 +496,7 @@ public final class ConfigurationPropertyName if (name.length() == 0) { return EMPTY; } - List elements = new ArrayList(10); + List elements = new ArrayList<>(10); process(name, separator, (elementValue, start, end, indexed) -> { elementValue = elementValueProcessor.apply(elementValue); if (!isIndexed(elementValue)) { diff --git a/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedYamlLoader.java b/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedYamlLoader.java index 5e8a3996f3..a11aa76ad2 100644 --- a/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedYamlLoader.java +++ b/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedYamlLoader.java @@ -78,7 +78,7 @@ class OriginTrackedYamlLoader extends YamlProcessor { } public Map load() { - final Map result = new LinkedHashMap(); + final Map result = new LinkedHashMap<>(); process((properties, map) -> { result.putAll(getFlattenedMap(map)); }); diff --git a/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaProperties.java b/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaProperties.java index e09c527821..96a8cd5cee 100644 --- a/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaProperties.java +++ b/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaProperties.java @@ -91,21 +91,21 @@ public class NarayanaProperties { /** * Comma-separated list of orphan filters. */ - private List xaResourceOrphanFilters = new ArrayList(Arrays.asList( + private List xaResourceOrphanFilters = new ArrayList<>(Arrays.asList( "com.arjuna.ats.internal.jta.recovery.arjunacore.JTATransactionLogXAResourceOrphanFilter", "com.arjuna.ats.internal.jta.recovery.arjunacore.JTANodeNameXAResourceOrphanFilter")); /** * Comma-separated list of recovery modules. */ - private List recoveryModules = new ArrayList(Arrays.asList( + private List recoveryModules = new ArrayList<>(Arrays.asList( "com.arjuna.ats.internal.arjuna.recovery.AtomicActionRecoveryModule", "com.arjuna.ats.internal.jta.recovery.arjunacore.XARecoveryModule")); /** * Comma-separated list of expiry scanners. */ - private List expiryScanners = new ArrayList(Collections.singletonList( + private List expiryScanners = new ArrayList<>(Collections.singletonList( "com.arjuna.ats.internal.arjuna.recovery.ExpiredTransactionStatusManagerScanner")); public String getLogDir() { diff --git a/spring-boot/src/main/java/org/springframework/boot/web/context/ServerPortInfoApplicationContextInitializer.java b/spring-boot/src/main/java/org/springframework/boot/web/context/ServerPortInfoApplicationContextInitializer.java index ee13f5bddf..5d2555eb42 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/context/ServerPortInfoApplicationContextInitializer.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/context/ServerPortInfoApplicationContextInitializer.java @@ -88,7 +88,7 @@ public class ServerPortInfoApplicationContextInitializer MutablePropertySources sources = environment.getPropertySources(); PropertySource source = sources.get("server.ports"); if (source == null) { - source = new MapPropertySource("server.ports", new HashMap()); + source = new MapPropertySource("server.ports", new HashMap<>()); sources.addFirst(source); } ((Map) source.getSource()).put(propertyName, port); diff --git a/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactory.java b/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactory.java index f223912c91..9674e3ab7f 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactory.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactory.java @@ -489,7 +489,7 @@ public class UndertowServletWebServerFactory extends AbstractServletWebServerFac File root = getValidDocumentRoot(); File docBase = getCanonicalDocumentRoot(root); List metaInfResourceUrls = getUrlsOfJarsWithMetaInfResources(); - List resourceJarUrls = new ArrayList(); + List resourceJarUrls = new ArrayList<>(); List resourceManagers = new ArrayList(); ResourceManager rootResourceManager = docBase.isDirectory() ? new FileResourceManager(docBase, 0) : new JarResourceManager(docBase); diff --git a/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessorTests.java b/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessorTests.java index 6b3e1dab6c..a60e901920 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessorTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessorTests.java @@ -444,7 +444,7 @@ public class ConfigurationPropertiesBindingPostProcessorTests { this.context = new AnnotationConfigApplicationContext(); MutablePropertySources sources = this.context.getEnvironment() .getPropertySources(); - Map source = new LinkedHashMap(); + Map source = new LinkedHashMap<>(); source.put("example.one", "foo"); sources.addFirst(new MapPropertySource("test-source", source)); this.context.register(PrototypePropertiesConfig.class); diff --git a/spring-boot/src/test/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessorTests.java b/spring-boot/src/test/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessorTests.java index f1abc115bb..94a3908015 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessorTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessorTests.java @@ -154,7 +154,7 @@ public class WebServerFactoryCustomizerBeanPostProcessorTests { WebServerFactoryCustomizer one = (f) -> called.add("one"); WebServerFactoryCustomizer two = (f) -> called.add("two"); WebServerFactoryCustomizer all = (f) -> called.add("all"); - Map beans = new LinkedHashMap(); + Map beans = new LinkedHashMap<>(); beans.put("one", one); beans.put("two", two); beans.put("all", all); From 4a189bdee7d1bd7fbdbd2593a8c9b8636a90bd39 Mon Sep 17 00:00:00 2001 From: Emanuel Campolo Date: Tue, 18 Jul 2017 11:51:31 -0300 Subject: [PATCH 2/6] Replace Collections.sort() with direct sort call Replace existing `Collections.sort(...)` calls with `.sort(...)` directly on the collection instance. See gh-9781 --- .../boot/actuate/hypermedia/EndpointDocumentation.java | 2 +- .../actuate/autoconfigure/EndpointAutoConfiguration.java | 2 +- .../boot/actuate/health/OrderedHealthAggregator.java | 3 +-- .../boot/autoconfigure/AutoConfigurationSorter.java | 2 +- .../cli/command/init/ServiceCapabilitiesReportGenerator.java | 5 ++--- .../springframework/boot/cli/compiler/GroovyCompiler.java | 2 +- .../springframework/boot/loader/tools/MainClassFinder.java | 2 +- .../java/org/springframework/boot/SpringApplication.java | 2 +- .../config/DelegatingApplicationContextInitializer.java | 3 +-- .../springframework/boot/logging/java/JavaLoggingSystem.java | 2 +- .../boot/logging/log4j2/Log4J2LoggingSystem.java | 2 +- .../boot/logging/logback/LogbackLoggingSystem.java | 3 +-- .../boot/web/server/ErrorPageRegistrarBeanPostProcessor.java | 2 +- .../server/WebServerFactoryCustomizerBeanPostProcessor.java | 2 +- .../boot/web/servlet/ServletContextInitializerBeans.java | 2 +- 15 files changed, 16 insertions(+), 20 deletions(-) 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 bd452e2cca..bbad0c1fbb 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 @@ -199,7 +199,7 @@ public class EndpointDocumentation { private Collection getEndpoints() { List endpoints = new ArrayList<>( this.mvcEndpoints.getEndpoints()); - Collections.sort(endpoints, new Comparator() { + endpoints.sort(new Comparator() { @Override public int compare(MvcEndpoint o1, MvcEndpoint o2) { return o1.getPath().compareTo(o2.getPath()); diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointAutoConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointAutoConfiguration.java index 357dacd433..aed327ccab 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointAutoConfiguration.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointAutoConfiguration.java @@ -149,7 +149,7 @@ public class EndpointAutoConfiguration { if (this.publicMetrics != null) { publicMetrics.addAll(this.publicMetrics); } - Collections.sort(publicMetrics, AnnotationAwareOrderComparator.INSTANCE); + publicMetrics.sort(AnnotationAwareOrderComparator.INSTANCE); return new MetricsEndpoint(publicMetrics); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/OrderedHealthAggregator.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/OrderedHealthAggregator.java index cb1b52ade3..9a05319486 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/OrderedHealthAggregator.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/OrderedHealthAggregator.java @@ -18,7 +18,6 @@ package org.springframework.boot.actuate.health; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; import java.util.Comparator; import java.util.List; @@ -80,7 +79,7 @@ public class OrderedHealthAggregator extends AbstractHealthAggregator { return Status.UNKNOWN; } // Sort given Status instances by configured order - Collections.sort(filteredCandidates, new StatusComparator(this.statusOrder)); + filteredCandidates.sort(new StatusComparator(this.statusOrder)); return filteredCandidates.get(0); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationSorter.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationSorter.java index d30bbabb42..ac6e1b8a96 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationSorter.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationSorter.java @@ -60,7 +60,7 @@ class AutoConfigurationSorter { // Initially sort alphabetically Collections.sort(orderedClassNames); // Then sort by order - Collections.sort(orderedClassNames, new Comparator() { + orderedClassNames.sort(new Comparator() { @Override public int compare(String o1, String o2) { diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGenerator.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGenerator.java index 0e1f776265..15a422f47d 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGenerator.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGenerator.java @@ -94,9 +94,8 @@ class ServiceCapabilitiesReportGenerator { private List getSortedDependencies(InitializrServiceMetadata metadata) { ArrayList dependencies = new ArrayList<>(metadata.getDependencies()); - Collections.sort(dependencies, new Comparator() { - @Override - public int compare(Dependency o1, Dependency o2) { + dependencies.sort(new Comparator() { + @Override public int compare(Dependency o1, Dependency o2) { return o1.getId().compareTo(o2.getId()); } }); diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyCompiler.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyCompiler.java index 9f9172455d..fdac83bb42 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyCompiler.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyCompiler.java @@ -124,7 +124,7 @@ public class GroovyCompiler { .load(SpringBootAstTransformation.class)) { this.transformations.add(transformation); } - Collections.sort(this.transformations, AnnotationAwareOrderComparator.INSTANCE); + this.transformations.sort(AnnotationAwareOrderComparator.INSTANCE); } /** 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 e02525e691..984bfde51d 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 @@ -234,7 +234,7 @@ public abstract class MainClassFinder { static T doWithMainClasses(JarFile jarFile, String classesLocation, MainClassCallback callback) throws IOException { List classEntries = getClassEntries(jarFile, classesLocation); - Collections.sort(classEntries, new ClassEntryComparator()); + classEntries.sort(new ClassEntryComparator()); for (JarEntry entry : classEntries) { try (InputStream inputStream = new BufferedInputStream( jarFile.getInputStream(entry))) { diff --git a/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java b/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java index ba0767e68c..8bb0e2936a 100644 --- a/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java +++ b/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java @@ -1309,7 +1309,7 @@ public class SpringApplication { private static Set asUnmodifiableOrderedSet(Collection elements) { List list = new ArrayList<>(); list.addAll(elements); - Collections.sort(list, AnnotationAwareOrderComparator.INSTANCE); + list.sort(AnnotationAwareOrderComparator.INSTANCE); return new LinkedHashSet<>(list); } diff --git a/spring-boot/src/main/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializer.java b/spring-boot/src/main/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializer.java index 5d2fa55ad0..800d605fd8 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializer.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializer.java @@ -17,7 +17,6 @@ package org.springframework.boot.context.config; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import org.springframework.beans.BeanUtils; @@ -110,7 +109,7 @@ public class DelegatingApplicationContextInitializer implements @SuppressWarnings({ "unchecked", "rawtypes" }) private void applyInitializers(ConfigurableApplicationContext context, List> initializers) { - Collections.sort(initializers, new AnnotationAwareOrderComparator()); + initializers.sort(new AnnotationAwareOrderComparator()); for (ApplicationContextInitializer initializer : initializers) { initializer.initialize(context); } diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/java/JavaLoggingSystem.java b/spring-boot/src/main/java/org/springframework/boot/logging/java/JavaLoggingSystem.java index 779e5a3529..b5a566551d 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/java/JavaLoggingSystem.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/java/JavaLoggingSystem.java @@ -133,7 +133,7 @@ public class JavaLoggingSystem extends AbstractLoggingSystem { while (names.hasMoreElements()) { result.add(getLoggerConfiguration(names.nextElement())); } - Collections.sort(result, CONFIGURATION_COMPARATOR); + result.sort(CONFIGURATION_COMPARATOR); return Collections.unmodifiableList(result); } diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystem.java b/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystem.java index b78142cc1a..231111d456 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystem.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystem.java @@ -220,7 +220,7 @@ public class Log4J2LoggingSystem extends Slf4JLoggingSystem { for (LoggerConfig loggerConfig : configuration.getLoggers().values()) { result.add(convertLoggerConfiguration(loggerConfig)); } - Collections.sort(result, CONFIGURATION_COMPARATOR); + result.sort(CONFIGURATION_COMPARATOR); return result; } diff --git a/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackLoggingSystem.java b/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackLoggingSystem.java index 8633366b8d..7547b51afe 100644 --- a/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackLoggingSystem.java +++ b/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackLoggingSystem.java @@ -20,7 +20,6 @@ import java.net.URL; import java.security.CodeSource; import java.security.ProtectionDomain; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.Set; @@ -213,7 +212,7 @@ public class LogbackLoggingSystem extends Slf4JLoggingSystem { for (ch.qos.logback.classic.Logger logger : getLoggerContext().getLoggerList()) { result.add(getLoggerConfiguration(logger)); } - Collections.sort(result, CONFIGURATION_COMPARATOR); + result.sort(CONFIGURATION_COMPARATOR); return result; } diff --git a/spring-boot/src/main/java/org/springframework/boot/web/server/ErrorPageRegistrarBeanPostProcessor.java b/spring-boot/src/main/java/org/springframework/boot/web/server/ErrorPageRegistrarBeanPostProcessor.java index 186b3d6604..4c0a4e6d43 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/server/ErrorPageRegistrarBeanPostProcessor.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/server/ErrorPageRegistrarBeanPostProcessor.java @@ -78,7 +78,7 @@ public class ErrorPageRegistrarBeanPostProcessor // Look up does not include the parent context this.registrars = new ArrayList<>(this.beanFactory .getBeansOfType(ErrorPageRegistrar.class, false, false).values()); - Collections.sort(this.registrars, AnnotationAwareOrderComparator.INSTANCE); + this.registrars.sort(AnnotationAwareOrderComparator.INSTANCE); this.registrars = Collections.unmodifiableList(this.registrars); } return this.registrars; diff --git a/spring-boot/src/main/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessor.java b/spring-boot/src/main/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessor.java index 0f65be6c8a..9cbb8bc6f5 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessor.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessor.java @@ -114,7 +114,7 @@ public class WebServerFactoryCustomizerBeanPostProcessor if (this.customizers == null) { // Look up does not include the parent context this.customizers = new ArrayList<>(getWebServerFactoryCustomizerBeans()); - Collections.sort(this.customizers, AnnotationAwareOrderComparator.INSTANCE); + this.customizers.sort(AnnotationAwareOrderComparator.INSTANCE); this.customizers = Collections.unmodifiableList(this.customizers); } return this.customizers; diff --git a/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java b/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java index 450199aa36..15a467a82d 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java @@ -238,7 +238,7 @@ public class ServletContextInitializerBeans } } beans.addAll(map.entrySet()); - Collections.sort(beans, comparator); + beans.sort(comparator); return beans; } From 798fe5ed53d37edbd9ae9d23a96b4a00c86b07b4 Mon Sep 17 00:00:00 2001 From: Emanuel Campolo Date: Tue, 18 Jul 2017 11:52:47 -0300 Subject: [PATCH 3/6] Collapse catch clauses Use multi-catch for exceptions whenever possible. See gh-9781 --- .../actuate/cache/AbstractJmxCacheStatisticsProvider.java | 5 +---- .../boot/autoconfigure/condition/OnBeanCondition.java | 5 +---- .../boot/autoconfigure/http/HttpMessageConverters.java | 5 +---- .../data/mongo/MongoDataAutoConfigurationTests.java | 4 ---- .../boot/cli/compiler/grape/AetherGrapeEngine.java | 5 +---- .../devtools/remote/client/ClassPathChangeUploader.java | 5 +---- .../boot/devtools/tunnel/client/HttpTunnelConnection.java | 5 +---- .../org/springframework/boot/maven/AbstractRunMojo.java | 3 --- .../boot/maven/SpringApplicationAdminClient.java | 7 ++----- .../java/org/springframework/boot/maven/StartMojo.java | 6 +----- .../org/springframework/boot/BeanDefinitionLoader.java | 5 +---- .../AtomikosDependsOnBeanFactoryPostProcessor.java | 5 +---- .../BitronixDependentBeanFactoryPostProcessor.java | 7 ++----- .../jta/narayana/NarayanaBeanFactoryPostProcessor.java | 7 ++----- .../boot/liquibase/SpringPackageScanClassResolver.java | 8 ++------ .../boot/web/embedded/tomcat/TomcatErrorPage.java | 5 +---- .../context/ServletWebServerApplicationContext.java | 8 +------- 17 files changed, 19 insertions(+), 76 deletions(-) diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/AbstractJmxCacheStatisticsProvider.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/AbstractJmxCacheStatisticsProvider.java index 418ce193ff..d922a8ef11 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/AbstractJmxCacheStatisticsProvider.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/AbstractJmxCacheStatisticsProvider.java @@ -107,16 +107,13 @@ public abstract class AbstractJmxCacheStatisticsProvider Object attribute = getMBeanServer().getAttribute(objectName, attributeName); return type.cast(attribute); } - catch (MBeanException ex) { + catch (MBeanException | ReflectionException ex) { throw new IllegalStateException(ex); } catch (AttributeNotFoundException ex) { throw new IllegalStateException("Unexpected: MBean with name '" + objectName + "' " + "does not expose attribute with name " + attributeName, ex); } - catch (ReflectionException ex) { - throw new IllegalStateException(ex); - } catch (InstanceNotFoundException ex) { logger.warn("Cache statistics are no longer available", ex); return null; diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnBeanCondition.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnBeanCondition.java index b03dd47d06..6e307d6682 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnBeanCondition.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnBeanCondition.java @@ -255,10 +255,7 @@ class OnBeanCondition extends SpringBootCondition implements ConfigurationCondit ClassUtils.forName(type, classLoader), considerHierarchy); return result; } - catch (ClassNotFoundException ex) { - return Collections.emptySet(); - } - catch (NoClassDefFoundError ex) { + catch (ClassNotFoundException | NoClassDefFoundError ex) { return Collections.emptySet(); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/HttpMessageConverters.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/HttpMessageConverters.java index 69815b553e..44cef8b713 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/HttpMessageConverters.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/HttpMessageConverters.java @@ -240,10 +240,7 @@ public class HttpMessageConverters implements Iterable> try { list.add(Class.forName(className)); } - catch (ClassNotFoundException ex) { - // Ignore - } - catch (NoClassDefFoundError ex) { + catch (ClassNotFoundException | NoClassDefFoundError ex) { // Ignore } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java index 264aa0d326..3e133911dc 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java @@ -27,7 +27,6 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.springframework.beans.factory.BeanCreationException; -import org.springframework.beans.factory.UnsatisfiedDependencyException; import org.springframework.boot.autoconfigure.AutoConfigurationPackages; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.autoconfigure.data.mongo.city.City; @@ -135,9 +134,6 @@ public class MongoDataAutoConfigurationTests { fail("Create FieldNamingStrategy interface should fail"); } // We seem to have an inconsistent exception, accept either - catch (UnsatisfiedDependencyException ex) { - // Expected - } catch (BeanCreationException ex) { // Expected } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngine.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngine.java index 976473a450..248c1b6fa9 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngine.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngine.java @@ -131,10 +131,7 @@ public class AetherGrapeEngine implements GrapeEngine { classLoader.addURL(file.toURI().toURL()); } } - catch (ArtifactResolutionException ex) { - throw new DependencyResolutionFailedException(ex); - } - catch (MalformedURLException ex) { + catch (ArtifactResolutionException | MalformedURLException ex) { throw new DependencyResolutionFailedException(ex); } return null; diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploader.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploader.java index 6c1bf79096..5bf05c841c 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploader.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploader.java @@ -80,10 +80,7 @@ public class ClassPathChangeUploader try { this.uri = new URL(url).toURI(); } - catch (URISyntaxException ex) { - throw new IllegalArgumentException("Malformed URL '" + url + "'"); - } - catch (MalformedURLException ex) { + catch (URISyntaxException | MalformedURLException ex) { throw new IllegalArgumentException("Malformed URL '" + url + "'"); } this.requestFactory = requestFactory; diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnection.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnection.java index 086530f232..ad9bb502ec 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnection.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnection.java @@ -84,10 +84,7 @@ public class HttpTunnelConnection implements TunnelConnection { try { this.uri = new URL(url).toURI(); } - catch (URISyntaxException ex) { - throw new IllegalArgumentException("Malformed URL '" + url + "'"); - } - catch (MalformedURLException ex) { + catch (URISyntaxException | MalformedURLException ex) { throw new IllegalArgumentException("Malformed URL '" + url + "'"); } this.requestFactory = requestFactory; diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractRunMojo.java b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractRunMojo.java index c5d00d30d3..f098542ac2 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractRunMojo.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractRunMojo.java @@ -371,9 +371,6 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo { addDependencies(urls); return urls.toArray(new URL[urls.size()]); } - catch (MalformedURLException ex) { - throw new MojoExecutionException("Unable to build classpath", ex); - } catch (IOException ex) { throw new MojoExecutionException("Unable to build classpath", ex); } diff --git a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/SpringApplicationAdminClient.java b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/SpringApplicationAdminClient.java index 066423e676..e7d892d3cd 100644 --- a/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/SpringApplicationAdminClient.java +++ b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/SpringApplicationAdminClient.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. @@ -73,10 +73,7 @@ class SpringApplicationAdminClient { throw new MojoExecutionException("Failed to retrieve Ready attribute", ex.getCause()); } - catch (MBeanException ex) { - throw new MojoExecutionException(ex.getMessage(), ex); - } - catch (IOException ex) { + catch (MBeanException | IOException ex) { throw new MojoExecutionException(ex.getMessage(), ex); } } 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 7661cbaf2f..549ca05c3b 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 @@ -94,11 +94,7 @@ public class StartMojo extends AbstractRunMojo { try { waitForSpringApplication(); } - catch (MojoExecutionException ex) { - runProcess.kill(); - throw ex; - } - catch (MojoFailureException ex) { + catch (MojoExecutionException | MojoFailureException ex) { runProcess.kill(); throw ex; } diff --git a/spring-boot/src/main/java/org/springframework/boot/BeanDefinitionLoader.java b/spring-boot/src/main/java/org/springframework/boot/BeanDefinitionLoader.java index edf7db9159..6453c60b9a 100644 --- a/spring-boot/src/main/java/org/springframework/boot/BeanDefinitionLoader.java +++ b/spring-boot/src/main/java/org/springframework/boot/BeanDefinitionLoader.java @@ -191,10 +191,7 @@ class BeanDefinitionLoader { try { return load(ClassUtils.forName(resolvedSource, null)); } - catch (IllegalArgumentException ex) { - // swallow exception and continue - } - catch (ClassNotFoundException ex) { + catch (IllegalArgumentException | ClassNotFoundException ex) { // swallow exception and continue } // Attempt as resources diff --git a/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessor.java b/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessor.java index 22dd96db3f..c3b9cbdde5 100644 --- a/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessor.java +++ b/spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosDependsOnBeanFactoryPostProcessor.java @@ -91,10 +91,7 @@ public class AtomikosDependsOnBeanFactoryPostProcessor try { return beanFactory.getBeanNamesForType(Class.forName(type), true, false); } - catch (ClassNotFoundException ex) { - // Ignore - } - catch (NoClassDefFoundError ex) { + catch (ClassNotFoundException | NoClassDefFoundError ex) { // Ignore } return NO_BEANS; diff --git a/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixDependentBeanFactoryPostProcessor.java b/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixDependentBeanFactoryPostProcessor.java index d2b097e324..100aa5a33f 100644 --- a/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixDependentBeanFactoryPostProcessor.java +++ b/spring-boot/src/main/java/org/springframework/boot/jta/bitronix/BitronixDependentBeanFactoryPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 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. @@ -67,10 +67,7 @@ public class BitronixDependentBeanFactoryPostProcessor try { return beanFactory.getBeanNamesForType(Class.forName(type), true, false); } - catch (ClassNotFoundException ex) { - // Ignore - } - catch (NoClassDefFoundError ex) { + catch (ClassNotFoundException | NoClassDefFoundError ex) { // Ignore } return NO_BEANS; diff --git a/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaBeanFactoryPostProcessor.java b/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaBeanFactoryPostProcessor.java index 7ca2ca5b53..7ea2b997bb 100644 --- a/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaBeanFactoryPostProcessor.java +++ b/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaBeanFactoryPostProcessor.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. @@ -70,10 +70,7 @@ public class NarayanaBeanFactoryPostProcessor try { return beanFactory.getBeanNamesForType(Class.forName(type), true, false); } - catch (ClassNotFoundException ex) { - // Ignore - } - catch (NoClassDefFoundError ex) { + catch (ClassNotFoundException | NoClassDefFoundError ex) { // Ignore } return NO_BEANS; diff --git a/spring-boot/src/main/java/org/springframework/boot/liquibase/SpringPackageScanClassResolver.java b/spring-boot/src/main/java/org/springframework/boot/liquibase/SpringPackageScanClassResolver.java index c19e6bb155..90ac46584b 100644 --- a/spring-boot/src/main/java/org/springframework/boot/liquibase/SpringPackageScanClassResolver.java +++ b/spring-boot/src/main/java/org/springframework/boot/liquibase/SpringPackageScanClassResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 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. @@ -78,11 +78,7 @@ public class SpringPackageScanClassResolver extends DefaultPackageScanClassResol MetadataReader reader = readerFactory.getMetadataReader(resource); return ClassUtils.forName(reader.getClassMetadata().getClassName(), loader); } - catch (ClassNotFoundException ex) { - handleFailure(resource, ex); - return null; - } - catch (LinkageError ex) { + catch (ClassNotFoundException | LinkageError ex) { handleFailure(resource, ex); return null; } diff --git a/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatErrorPage.java b/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatErrorPage.java index 8941598694..93d25fb2a0 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatErrorPage.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatErrorPage.java @@ -58,10 +58,7 @@ class TomcatErrorPage { .instantiateClass(ClassUtils.forName(ERROR_PAGE_CLASS, null)); } } - catch (ClassNotFoundException ex) { - // Swallow and continue - } - catch (LinkageError ex) { + catch (ClassNotFoundException | LinkageError ex) { // Swallow and continue } return null; diff --git a/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContext.java b/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContext.java index aaab116489..d24099ebc9 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContext.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContext.java @@ -273,13 +273,7 @@ public class ServletWebServerApplicationContext extends GenericWebApplicationCon + elapsedTime + " ms"); } } - catch (RuntimeException ex) { - logger.error("Context initialization failed", ex); - servletContext.setAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex); - throw ex; - } - catch (Error ex) { + catch (RuntimeException | Error ex) { logger.error("Context initialization failed", ex); servletContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex); From d16af4366454ccac7addea96fa08561b2ceb4283 Mon Sep 17 00:00:00 2001 From: Emanuel Campolo Date: Tue, 18 Jul 2017 12:04:54 -0300 Subject: [PATCH 4/6] Replace try with try-with-resources Update existing try/finally/close blocks to use "try with resources" See gh-9781 --- .../boot/devtools/tunnel/client/TunnelClient.java | 8 ++------ .../springframework/boot/loader/tools/JarWriter.java | 12 ++---------- 2 files changed, 4 insertions(+), 16 deletions(-) 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 2289af9c54..c28c8841ca 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 @@ -170,10 +170,9 @@ public class TunnelClient implements SmartInitializingSingleton { private void handleConnection(SocketChannel socketChannel) throws Exception { Closeable closeable = new SocketCloseable(socketChannel); - WritableByteChannel outputChannel = TunnelClient.this.tunnelConnection - .open(socketChannel, closeable); TunnelClient.this.listeners.fireOpenEvent(socketChannel); - try { + try (WritableByteChannel outputChannel = TunnelClient.this.tunnelConnection + .open(socketChannel, closeable)) { logger.trace("Accepted connection to tunnel client from " + socketChannel.socket().getRemoteSocketAddress()); while (true) { @@ -189,9 +188,6 @@ public class TunnelClient implements SmartInitializingSingleton { } } } - finally { - outputChannel.close(); - } } protected void stopAcceptingConnections() { 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 4cf1d45f8a..3cdc2b930a 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 @@ -186,8 +186,7 @@ public class JarWriter implements LoaderClassesWriter, AutoCloseable { private long getNestedLibraryTime(File file) { try { - JarFile jarFile = new JarFile(file); - try { + try (JarFile jarFile = new JarFile(file)) { Enumeration entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); @@ -196,9 +195,6 @@ public class JarWriter implements LoaderClassesWriter, AutoCloseable { } } } - finally { - jarFile.close(); - } } catch (Exception ex) { // Ignore and just use the source file timestamp @@ -381,13 +377,9 @@ public class JarWriter implements LoaderClassesWriter, AutoCloseable { private long size; CrcAndSize(File file) throws IOException { - FileInputStream inputStream = new FileInputStream(file); - try { + try (FileInputStream inputStream = new FileInputStream(file)) { load(inputStream); } - finally { - inputStream.close(); - } } CrcAndSize(InputStream inputStream) throws IOException { From 2626a3a795aad593494480fa1d8a7c29e1e82d3a Mon Sep 17 00:00:00 2001 From: Emanuel Campolo Date: Mon, 24 Jul 2017 23:11:47 -0700 Subject: [PATCH 5/6] Use lambdas when possible Replace anonymous inner classes with lambda declarations (when possible using method references). See gh-9781 --- .../hypermedia/EndpointDocumentation.java | 61 +++--- .../CacheStatisticsAutoConfiguration.java | 14 +- .../EndpointWebMvcAutoConfiguration.java | 9 +- ...ermediaManagementContextConfiguration.java | 9 +- .../actuate/endpoint/ShutdownEndpoint.java | 25 ++- .../health/DataSourceHealthIndicator.java | 15 +- .../actuate/health/RabbitHealthIndicator.java | 17 +- .../metrics/buffer/BufferMetricReader.java | 14 +- .../boot/actuate/metrics/buffer/Buffers.java | 25 +-- .../metrics/buffer/CounterBuffers.java | 30 +-- .../actuate/metrics/buffer/GaugeBuffers.java | 15 +- .../metrics/dropwizard/ReservoirFactory.java | 9 +- .../reader/MetricRegistryMetricReader.java | 18 +- .../repository/InMemoryMetricRepository.java | 16 +- .../rich/InMemoryRichGaugeRepository.java | 35 ++-- .../EndpointAutoConfigurationTests.java | 19 +- .../EndpointMvcIntegrationTests.java | 10 +- .../EndpointWebMvcAutoConfigurationTests.java | 9 +- ...HealthIndicatorAutoConfigurationTests.java | 7 +- ...InfoContributorAutoConfigurationTests.java | 5 +- ...mentWebSecurityAutoConfigurationTests.java | 12 +- .../MetricExportAutoConfigurationTests.java | 10 +- .../MetricFilterAutoConfigurationTests.java | 72 +++---- .../PublicMetricsAutoConfigurationTests.java | 12 +- ...oudFoundryEndpointHandlerMappingTests.java | 12 +- .../actuate/endpoint/HealthEndpointTests.java | 10 +- .../actuate/endpoint/InfoEndpointTests.java | 12 +- .../endpoint/MetricsEndpointTests.java | 10 +- .../endpoint/ShutdownEndpointTests.java | 15 +- .../endpoint/ShutdownParentEndpointTests.java | 7 +- ...HeapdumpMvcEndpointSecureOptionsTests.java | 28 +-- .../mvc/HeapdumpMvcEndpointTests.java | 28 +-- .../endpoint/mvc/InfoMvcEndpointTests.java | 28 +-- .../endpoint/mvc/MetricsMvcEndpointTests.java | 27 +-- ...rityHealthMvcEndpointIntegrationTests.java | 24 +-- .../mvc/ShutdownMvcEndpointTests.java | 13 +- .../buffer/BufferGaugeServiceSpeedTests.java | 48 ++--- .../metrics/buffer/CounterBuffersTests.java | 20 +- .../buffer/CounterServiceSpeedTests.java | 48 ++--- .../DefaultCounterServiceSpeedTests.java | 29 +-- .../buffer/DefaultGaugeServiceSpeedTests.java | 32 +-- .../DropwizardCounterServiceSpeedTests.java | 32 +-- .../MetricRegistryMetricReaderTests.java | 18 +- .../util/SimpleInMemoryRepositoryTests.java | 29 +-- .../MessageChannelMetricWriterTests.java | 15 +- .../servlet/MockServletWebServerFactory.java | 2 +- .../trace/WebRequestTraceFilterTests.java | 60 ++---- .../AutoConfigurationSorter.java | 14 +- .../condition/OnClassCondition.java | 11 +- ...rcePoolMetadataProvidersConfiguration.java | 46 ++--- .../jersey/JerseyAutoConfiguration.java | 11 +- .../SpringBootWebSecurityConfiguration.java | 9 +- .../social/SocialWebAutoConfiguration.java | 7 +- ...aultServletWebServerFactoryCustomizer.java | 163 +++++----------- ...tWebSocketReactiveWebServerCustomizer.java | 12 +- .../AutoConfigurationImportSelectorTests.java | 10 +- .../JobLauncherCommandLineRunnerTests.java | 47 ++--- .../cache/CacheAutoConfigurationTests.java | 29 +-- .../cache/support/MockCachingProvider.java | 28 +-- .../CassandraAutoConfigurationTests.java | 7 +- .../jest/JestAutoConfigurationTests.java | 10 +- .../JacksonAutoConfigurationTests.java | 8 +- .../jdbc/DataSourceInitializerTests.java | 10 +- .../AbstractDataSourcePoolMetadataTests.java | 52 ++--- .../ArtemisAutoConfigurationTests.java | 42 ++-- ...gurationReportLoggingInitializerTests.java | 17 +- .../SecurityAutoConfigurationTests.java | 21 +- ...ServerTokenServicesConfigurationTests.java | 59 ++---- .../RestTemplateAutoConfigurationTests.java | 9 +- .../servlet/MockServletWebServerFactory.java | 2 +- .../infrastructure/CommandLineInvoker.java | 11 +- .../cli/command/archive/ArchiveCommand.java | 12 +- .../ServiceCapabilitiesReportGenerator.java | 16 +- .../cli/command/options/OptionHandler.java | 11 +- .../boot/cli/command/shell/Shell.java | 7 +- .../compiler/ExtendedGroovyClassLoader.java | 28 +-- .../cli/compiler/grape/AetherGrapeEngine.java | 14 +- .../springframework/boot/cli/CliTester.java | 36 ++-- .../RepositoryConfigurationFactoryTests.java | 66 +++---- .../grape/AetherGrapeEngineTests.java | 59 +++--- ...rySystemSessionAutoConfigurationTests.java | 21 +- ...rySystemSessionAutoConfigurationTests.java | 47 ++--- .../LocalDevToolsAutoConfiguration.java | 9 +- .../devtools/livereload/LiveReloadServer.java | 18 +- .../client/RemoteClientConfiguration.java | 9 +- .../devtools/remote/server/AccessManager.java | 9 +- .../boot/devtools/restart/FailureHandler.java | 9 +- .../devtools/restart/RestartInitializer.java | 9 +- .../boot/devtools/restart/Restarter.java | 39 ++-- .../ClassLoaderFileRepository.java | 9 +- .../classloader/RestartClassLoader.java | 17 +- .../ClassPathFileSystemWatcherTests.java | 10 +- .../filewatch/FileSystemWatcherTests.java | 26 +-- .../devtools/restart/MainMethodTests.java | 21 +- .../boot/devtools/restart/MockRestarter.java | 34 +--- .../OnInitializedRestarterConditionTests.java | 9 +- .../boot/devtools/restart/RestarterTests.java | 40 ++-- .../SilentExitExceptionHandlerTests.java | 31 ++- .../tunnel/server/HttpTunnelServerTests.java | 26 +-- .../launchscript/SysVinitLaunchScriptIT.java | 15 +- .../json/JsonTestersAutoConfiguration.java | 15 +- .../WebTestClientAutoConfiguration.java | 18 +- .../web/servlet/WebDriverScope.java | 28 ++- .../ImportsContextCustomizerFactory.java | 17 +- .../test/json/AbstractJsonMarshalTester.java | 22 +-- .../test/mock/mockito/DefinitionsParser.java | 11 +- .../mock/mockito/MockitoPostProcessor.java | 12 +- .../test/json/JsonContentAssertTests.java | 11 +- .../test/json/ObjectContentAssertTests.java | 9 +- ...ockBeanForBeanFactoryIntegrationTests.java | 11 +- .../SpringBootMockServletContextTests.java | 11 +- .../web/client/TestRestTemplateTests.java | 182 ++++-------------- .../fieldvalues/FieldValuesParser.java | 9 +- .../boot/loader/tools/JarWriter.java | 7 +- .../boot/loader/tools/Libraries.java | 5 +- .../boot/loader/tools/MainClassFinder.java | 44 ++--- .../boot/loader/tools/Repackager.java | 21 +- .../boot/loader/tools/RunProcess.java | 38 ++-- .../boot/loader/tools/SignalUtils.java | 10 +- .../boot/loader/tools/RepackagerTests.java | 94 +++------ .../loader/ExecutableArchiveLauncher.java | 11 +- .../boot/loader/LaunchedURLClassLoader.java | 40 ++-- .../boot/loader/PropertiesLauncher.java | 13 +- .../boot/loader/jar/JarFile.java | 13 +- .../data/RandomAccessDataFileTests.java | 42 ++-- .../springframework/boot/maven/StartMojo.java | 9 +- .../classpath/ModifiedClassPathRunner.java | 19 +- .../web/servlet/MockServletWebServer.java | 56 ++---- .../boot/StartupInfoLogger.java | 37 +--- .../ConfigurationBeanFactoryMetaData.java | 11 +- .../boot/context/properties/bind/Binder.java | 4 +- .../boot/env/OriginTrackedYamlLoader.java | 4 +- ...PortInfoApplicationContextInitializer.java | 11 +- .../UndertowServletWebServerFactory.java | 10 +- .../ServletContextInitializerBeans.java | 10 +- .../ServletWebServerApplicationContext.java | 7 +- .../boot/ExitCodeGeneratorsTests.java | 15 +- .../boot/SpringApplicationTests.java | 97 +++------- ...gApplicationAdminMXBeanRegistrarTests.java | 18 +- .../SpringApplicationBuilderTests.java | 7 +- .../ConfigFileApplicationListenerTests.java | 4 +- .../LoggingApplicationListenerTests.java | 9 +- .../logging/java/JavaLoggingSystemTests.java | 10 +- .../web/client/RestTemplateBuilderTests.java | 10 +- .../JettyServletWebServerFactoryTests.java | 46 ++--- .../TomcatServletWebServerFactoryTests.java | 27 +-- .../UndertowServletWebServerFactoryTests.java | 19 +- .../AbstractServletWebServerFactoryTests.java | 119 +++++------- .../server/MockServletWebServerFactory.java | 2 +- .../SpringBootServletInitializerTests.java | 17 +- 150 files changed, 983 insertions(+), 2596 deletions(-) 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 bbad0c1fbb..175d22414e 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 @@ -52,8 +52,6 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.test.web.servlet.ResultHandler; import org.springframework.util.FileCopyUtils; import org.springframework.util.StringUtils; @@ -161,32 +159,9 @@ public class EndpointDocumentation { @Test public void endpoints() throws Exception { - final File docs = new File("src/main/asciidoc"); - final Map model = new LinkedHashMap<>(); - final List endpoints = new ArrayList<>(); - model.put("endpoints", endpoints); - for (MvcEndpoint endpoint : getEndpoints()) { - final String endpointPath = (StringUtils.hasText(endpoint.getPath()) - ? endpoint.getPath() : "/"); - if (!SKIPPED.contains(endpointPath)) { - String output = endpointPath.substring(1); - output = output.length() > 0 ? output : "./"; - this.mockMvc - .perform(get("/application" + endpointPath) - .accept(ActuatorMediaTypes.APPLICATION_ACTUATOR_V2_JSON)) - .andExpect(status().isOk()).andDo(document(output)) - .andDo(new ResultHandler() { - - @Override - public void handle(MvcResult mvcResult) throws Exception { - EndpointDoc endpoint = new EndpointDoc(docs, - endpointPath); - endpoints.add(endpoint); - } - - }); - } - } + File docs = new File("src/main/asciidoc"); + Map model = new LinkedHashMap<>(); + model.put("endpoints", getEndpointDocs(docs)); File file = new File(RESTDOCS_OUTPUT_DIR + "/endpoints.adoc"); file.getParentFile().mkdirs(); try (PrintWriter writer = new PrintWriter(file, "UTF-8")) { @@ -196,18 +171,36 @@ public class EndpointDocumentation { } } + private List getEndpointDocs(File docs) throws Exception { + final List endpoints = new ArrayList<>(); + for (MvcEndpoint endpoint : getEndpoints()) { + String path = endpoint.getPath(); + path = (StringUtils.hasText(path) ? path : "/"); + if (!SKIPPED.contains(path)) { + documentEndpoint(path); + endpoints.add(new EndpointDoc(docs, path)); + } + } + return endpoints; + } + private Collection getEndpoints() { List endpoints = new ArrayList<>( this.mvcEndpoints.getEndpoints()); - endpoints.sort(new Comparator() { - @Override - public int compare(MvcEndpoint o1, MvcEndpoint o2) { - return o1.getPath().compareTo(o2.getPath()); - } - }); + endpoints.sort(Comparator.comparing(MvcEndpoint::getPath)); return endpoints; } + private String documentEndpoint(final String endpointPath) throws Exception { + String output = endpointPath.substring(1); + output = (output.length() > 0 ? output : "./"); + this.mockMvc + .perform(get("/application" + endpointPath) + .accept(ActuatorMediaTypes.APPLICATION_ACTUATOR_V2_JSON)) + .andExpect(status().isOk()).andDo(document(output)); + return output; + } + public static class EndpointDoc { private String path; diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/CacheStatisticsAutoConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/CacheStatisticsAutoConfiguration.java index 71e1a276de..5ecdf8ff3c 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/CacheStatisticsAutoConfiguration.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/CacheStatisticsAutoConfiguration.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. @@ -137,15 +137,11 @@ public class CacheStatisticsAutoConfiguration { @Bean public CacheStatisticsProvider noOpCacheStatisticsProvider() { - return new CacheStatisticsProvider() { - @Override - public CacheStatistics getCacheStatistics(CacheManager cacheManager, - Cache cache) { - if (cacheManager instanceof NoOpCacheManager) { - return NO_OP_STATS; - } - return null; + return (cacheManager, cache) -> { + if (cacheManager instanceof NoOpCacheManager) { + return NO_OP_STATS; } + return null; }; } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfiguration.java index 84b84fdd42..ec81ef731e 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfiguration.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfiguration.java @@ -120,14 +120,7 @@ public class EndpointWebMvcAutoConfiguration @Bean public ManagementServletContext managementServletContext( final ManagementServerProperties properties) { - return new ManagementServletContext() { - - @Override - public String getContextPath() { - return properties.getContextPath(); - } - - }; + return properties::getContextPath; } @Override diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcHypermediaManagementContextConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcHypermediaManagementContextConfiguration.java index 1aca690d5c..2e839e8319 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcHypermediaManagementContextConfiguration.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcHypermediaManagementContextConfiguration.java @@ -101,14 +101,7 @@ public class EndpointWebMvcHypermediaManagementContextConfiguration { @Bean public ManagementServletContext managementServletContext( final ManagementServerProperties properties) { - return new ManagementServletContext() { - - @Override - public String getContextPath() { - return properties.getContextPath(); - } - - }; + return properties::getContextPath; } @ConditionalOnEnabledEndpoint("actuator") diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/ShutdownEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/ShutdownEndpoint.java index a64c7a42b6..5c6f124be4 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/ShutdownEndpoint.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/ShutdownEndpoint.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,23 +62,22 @@ public class ShutdownEndpoint extends AbstractEndpoint> return SHUTDOWN_MESSAGE; } finally { - Thread thread = new Thread(new Runnable() { - @Override - public void run() { - try { - Thread.sleep(500L); - } - catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - } - ShutdownEndpoint.this.context.close(); - } - }); + Thread thread = new Thread(this::performShutdown); thread.setContextClassLoader(getClass().getClassLoader()); thread.start(); } } + private void performShutdown() { + try { + Thread.sleep(500L); + } + catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } + this.context.close(); + } + @Override public void setApplicationContext(ApplicationContext context) throws BeansException { if (context instanceof ConfigurableApplicationContext) { diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DataSourceHealthIndicator.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DataSourceHealthIndicator.java index 51b6e3353a..371fd73a1e 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DataSourceHealthIndicator.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DataSourceHealthIndicator.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. @@ -26,7 +26,6 @@ import javax.sql.DataSource; import org.springframework.beans.factory.InitializingBean; import org.springframework.boot.jdbc.DatabaseDriver; -import org.springframework.dao.DataAccessException; import org.springframework.dao.support.DataAccessUtils; import org.springframework.jdbc.IncorrectResultSetColumnCountException; import org.springframework.jdbc.core.ConnectionCallback; @@ -120,13 +119,11 @@ public class DataSourceHealthIndicator extends AbstractHealthIndicator } private String getProduct() { - return this.jdbcTemplate.execute(new ConnectionCallback() { - @Override - public String doInConnection(Connection connection) - throws SQLException, DataAccessException { - return connection.getMetaData().getDatabaseProductName(); - } - }); + return this.jdbcTemplate.execute((ConnectionCallback) this::getProduct); + } + + private String getProduct(Connection connection) throws SQLException { + return connection.getMetaData().getDatabaseProductName(); } protected String getValidationQuery(String product) { diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/RabbitHealthIndicator.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/RabbitHealthIndicator.java index cf6d4935b7..93e4fffbd8 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/RabbitHealthIndicator.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/RabbitHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 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. @@ -16,11 +16,6 @@ package org.springframework.boot.actuate.health; -import java.util.Map; - -import com.rabbitmq.client.Channel; - -import org.springframework.amqp.rabbit.core.ChannelCallback; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.util.Assert; @@ -46,14 +41,8 @@ public class RabbitHealthIndicator extends AbstractHealthIndicator { } private String getVersion() { - return this.rabbitTemplate.execute(new ChannelCallback() { - @Override - public String doInRabbit(Channel channel) throws Exception { - Map serverProperties = channel.getConnection() - .getServerProperties(); - return serverProperties.get("version").toString(); - } - }); + return this.rabbitTemplate.execute((channel) -> channel.getConnection() + .getServerProperties().get("version").toString()); } } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/BufferMetricReader.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/BufferMetricReader.java index 5ea7b957b2..ae0070fafe 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/BufferMetricReader.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/BufferMetricReader.java @@ -19,7 +19,6 @@ package org.springframework.boot.actuate.metrics.buffer; import java.util.ArrayList; import java.util.Date; import java.util.List; -import java.util.function.BiConsumer; import java.util.function.Predicate; import java.util.regex.Pattern; @@ -48,7 +47,7 @@ public class BufferMetricReader implements MetricReader, PrefixMetricReader { } @Override - public Metric findOne(final String name) { + public Metric findOne(String name) { Buffer buffer = this.counterBuffers.find(name); if (buffer == null) { buffer = this.gaugeBuffers.find(name); @@ -81,17 +80,10 @@ public class BufferMetricReader implements MetricReader, PrefixMetricReader { private > void collectMetrics( Buffers buffers, Predicate predicate, final List> metrics) { - buffers.forEach(predicate, new BiConsumer() { - - @Override - public void accept(String name, B value) { - metrics.add(asMetric(name, value)); - } - - }); + buffers.forEach(predicate, (name, value) -> metrics.add(asMetric(name, value))); } - private Metric asMetric(final String name, Buffer buffer) { + private Metric asMetric(String name, Buffer buffer) { return new Metric<>(name, buffer.getValue(), new Date(buffer.getTimestamp())); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/Buffers.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/Buffers.java index 29cacda935..f7bad60d51 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/Buffers.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/Buffers.java @@ -19,7 +19,6 @@ package org.springframework.boot.actuate.metrics.buffer; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; import java.util.function.Consumer; -import java.util.function.Function; import java.util.function.Predicate; /** @@ -34,20 +33,15 @@ abstract class Buffers> { private final ConcurrentHashMap buffers = new ConcurrentHashMap<>(); public void forEach(final Predicate predicate, - final BiConsumer consumer) { - this.buffers.forEach(new BiConsumer() { - - @Override - public void accept(String name, B value) { - if (predicate.test(name)) { - consumer.accept(name, value); - } + BiConsumer consumer) { + this.buffers.forEach((name, value) -> { + if (predicate.test(name)) { + consumer.accept(name, value); } - }); } - public B find(final String name) { + public B find(String name) { return this.buffers.get(name); } @@ -55,15 +49,10 @@ abstract class Buffers> { return this.buffers.size(); } - protected final void doWith(final String name, final Consumer consumer) { + protected final void doWith(String name, Consumer consumer) { B buffer = this.buffers.get(name); if (buffer == null) { - buffer = this.buffers.computeIfAbsent(name, new Function() { - @Override - public B apply(String name) { - return createBuffer(); - } - }); + buffer = this.buffers.computeIfAbsent(name, (k) -> createBuffer()); } consumer.accept(buffer); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/CounterBuffers.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/CounterBuffers.java index ef7b3855d4..7381fde6c5 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/CounterBuffers.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/CounterBuffers.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. @@ -16,8 +16,6 @@ package org.springframework.boot.actuate.metrics.buffer; -import java.util.function.Consumer; - /** * Fast writes to in-memory metrics store using {@link CounterBuffer}. * @@ -26,27 +24,17 @@ import java.util.function.Consumer; */ public class CounterBuffers extends Buffers { - public void increment(final String name, final long delta) { - doWith(name, new Consumer() { - - @Override - public void accept(CounterBuffer buffer) { - buffer.setTimestamp(System.currentTimeMillis()); - buffer.add(delta); - } - + public void increment(String name, long delta) { + doWith(name, (buffer) -> { + buffer.setTimestamp(System.currentTimeMillis()); + buffer.add(delta); }); } - public void reset(final String name) { - doWith(name, new Consumer() { - - @Override - public void accept(CounterBuffer buffer) { - buffer.setTimestamp(System.currentTimeMillis()); - buffer.reset(); - } - + public void reset(String name) { + doWith(name, (buffer) -> { + buffer.setTimestamp(System.currentTimeMillis()); + buffer.reset(); }); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/GaugeBuffers.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/GaugeBuffers.java index d3302a924f..6ed4623185 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/GaugeBuffers.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/buffer/GaugeBuffers.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. @@ -16,8 +16,6 @@ package org.springframework.boot.actuate.metrics.buffer; -import java.util.function.Consumer; - /** * Fast writes to in-memory metrics store using {@link GaugeBuffer}. * @@ -26,13 +24,10 @@ import java.util.function.Consumer; */ public class GaugeBuffers extends Buffers { - public void set(final String name, final double value) { - doWith(name, new Consumer() { - @Override - public void accept(GaugeBuffer buffer) { - buffer.setTimestamp(System.currentTimeMillis()); - buffer.setValue(value); - } + public void set(String name, double value) { + doWith(name, (buffer) -> { + buffer.setTimestamp(System.currentTimeMillis()); + buffer.setValue(value); }); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/dropwizard/ReservoirFactory.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/dropwizard/ReservoirFactory.java index 2d7f79871b..b3a20b6edf 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/dropwizard/ReservoirFactory.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/dropwizard/ReservoirFactory.java @@ -32,14 +32,7 @@ public interface ReservoirFactory { /** * Default empty {@link ReservoirFactory} implementation. */ - ReservoirFactory NONE = new ReservoirFactory() { - - @Override - public Reservoir getReservoir(String name) { - return null; - } - - }; + ReservoirFactory NONE = (name) -> null; /** * Return the {@link Reservoir} instance to use or {@code null} if a custom reservoir diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/reader/MetricRegistryMetricReader.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/reader/MetricRegistryMetricReader.java index ae7f04d151..76a9da6988 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/reader/MetricRegistryMetricReader.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/reader/MetricRegistryMetricReader.java @@ -18,7 +18,6 @@ package org.springframework.boot.actuate.metrics.reader; import java.beans.PropertyDescriptor; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; @@ -113,18 +112,15 @@ public class MetricRegistryMetricReader implements MetricReader, MetricRegistryL @Override public Iterable> findAll() { - return new Iterable>() { - @Override - public Iterator> iterator() { - Set> metrics = new HashSet<>(); - for (String name : MetricRegistryMetricReader.this.names.keySet()) { - Metric metric = findOne(name); - if (metric != null) { - metrics.add(metric); - } + return () -> { + Set> metrics = new HashSet<>(); + for (String name : MetricRegistryMetricReader.this.names.keySet()) { + Metric metric = findOne(name); + if (metric != null) { + metrics.add(metric); } - return metrics.iterator(); } + return metrics.iterator(); }; } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/repository/InMemoryMetricRepository.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/repository/InMemoryMetricRepository.java index d4e8d66a33..37f9e71a15 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/repository/InMemoryMetricRepository.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/repository/InMemoryMetricRepository.java @@ -21,7 +21,6 @@ import java.util.concurrent.ConcurrentNavigableMap; import org.springframework.boot.actuate.metrics.Metric; import org.springframework.boot.actuate.metrics.util.SimpleInMemoryRepository; -import org.springframework.boot.actuate.metrics.util.SimpleInMemoryRepository.Callback; import org.springframework.boot.actuate.metrics.writer.Delta; /** @@ -43,17 +42,12 @@ public class InMemoryMetricRepository implements MetricRepository { final String metricName = delta.getName(); final int amount = delta.getValue().intValue(); final Date timestamp = delta.getTimestamp(); - this.metrics.update(metricName, new Callback>() { - - @Override - public Metric modify(Metric current) { - if (current != null) { - return new Metric<>(metricName, current.increment(amount).getValue(), - timestamp); - } - return new Metric<>(metricName, (long) amount, timestamp); + this.metrics.update(metricName, (current) -> { + if (current != null) { + return new Metric<>(metricName, current.increment(amount).getValue(), + timestamp); } - + return new Metric<>(metricName, (long) amount, timestamp); }); } diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/rich/InMemoryRichGaugeRepository.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/rich/InMemoryRichGaugeRepository.java index b1aff342a5..6ecc54eb10 100644 --- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/rich/InMemoryRichGaugeRepository.java +++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/rich/InMemoryRichGaugeRepository.java @@ -18,7 +18,6 @@ package org.springframework.boot.actuate.metrics.rich; import org.springframework.boot.actuate.metrics.Metric; import org.springframework.boot.actuate.metrics.util.SimpleInMemoryRepository; -import org.springframework.boot.actuate.metrics.util.SimpleInMemoryRepository.Callback; import org.springframework.boot.actuate.metrics.writer.Delta; import org.springframework.boot.actuate.metrics.writer.MetricWriter; @@ -36,19 +35,14 @@ public class InMemoryRichGaugeRepository implements RichGaugeRepository { private final SimpleInMemoryRepository repository = new SimpleInMemoryRepository<>(); @Override - public void increment(final Delta delta) { - this.repository.update(delta.getName(), new Callback() { - - @Override - public RichGauge modify(RichGauge current) { - double value = ((Number) delta.getValue()).doubleValue(); - if (current == null) { - return new RichGauge(delta.getName(), value); - } - current.set(current.getValue() + value); - return current; + public void increment(Delta delta) { + this.repository.update(delta.getName(), (current) -> { + double value = ((Number) delta.getValue()).doubleValue(); + if (current == null) { + return new RichGauge(delta.getName(), value); } - + current.set(current.getValue() + value); + return current; }); } @@ -56,17 +50,12 @@ public class InMemoryRichGaugeRepository implements RichGaugeRepository { public void set(Metric metric) { final String name = metric.getName(); final double value = metric.getValue().doubleValue(); - this.repository.update(name, new Callback() { - - @Override - public RichGauge modify(RichGauge current) { - if (current == null) { - return new RichGauge(name, value); - } - current.set(value); - return current; + this.repository.update(name, (current) -> { + if (current == null) { + return new RichGauge(name, value); } - + current.set(value); + return current; }); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointAutoConfigurationTests.java index 668167341f..02b63e68b0 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointAutoConfigurationTests.java @@ -17,7 +17,6 @@ package org.springframework.boot.actuate.autoconfigure; import java.io.IOException; -import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; @@ -277,12 +276,9 @@ public class EndpointAutoConfigurationTests { @Bean PublicMetrics customPublicMetrics() { - return new PublicMetrics() { - @Override - public Collection> metrics() { - Metric metric = new Metric<>("foo", 1); - return Collections.>singleton(metric); - } + return () -> { + Metric metric = new Metric<>("foo", 1); + return Collections.>singleton(metric); }; } @@ -294,12 +290,9 @@ public class EndpointAutoConfigurationTests { @Bean @Order(InfoContributorAutoConfiguration.DEFAULT_ORDER - 1) public InfoContributor myInfoContributor() { - return new InfoContributor() { - @Override - public void contribute(Info.Builder builder) { - builder.withDetail("name", "bar"); - builder.withDetail("version", "1.0"); - } + return (builder) -> { + builder.withDetail("name", "bar"); + builder.withDetail("version", "1.0"); }; } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointMvcIntegrationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointMvcIntegrationTests.java index cf56833f01..9a83e37006 100755 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointMvcIntegrationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointMvcIntegrationTests.java @@ -36,7 +36,6 @@ import org.junit.runner.RunWith; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.Endpoint; -import org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping; import org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMappingCustomizer; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; @@ -134,14 +133,7 @@ public class EndpointMvcIntegrationTests { @Bean public EndpointHandlerMappingCustomizer mappingCustomizer() { - return new EndpointHandlerMappingCustomizer() { - - @Override - public void customize(EndpointHandlerMapping mapping) { - mapping.setInterceptors(interceptor()); - } - - }; + return (mapping) -> mapping.setInterceptors(interceptor()); } @Bean 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 118a3e1ac0..5e0146dae3 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 @@ -808,14 +808,7 @@ public class EndpointWebMvcAutoConfigurationTests { @Bean public EndpointHandlerMappingCustomizer mappingCustomizer() { - return new EndpointHandlerMappingCustomizer() { - - @Override - public void customize(EndpointHandlerMapping mapping) { - mapping.setInterceptors(interceptor()); - } - - }; + return (mapping) -> mapping.setInterceptors(interceptor()); } @Bean diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/HealthIndicatorAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/HealthIndicatorAutoConfigurationTests.java index f8db8df9a2..91dc8a7833 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/HealthIndicatorAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/HealthIndicatorAutoConfigurationTests.java @@ -447,12 +447,7 @@ public class HealthIndicatorAutoConfigurationTests { @Bean public HealthIndicator customHealthIndicator() { - return new HealthIndicator() { - @Override - public Health health() { - return Health.down().build(); - } - }; + return () -> Health.down().build(); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/InfoContributorAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/InfoContributorAutoConfigurationTests.java index a9c8c953e0..fd25d5c105 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/InfoContributorAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/InfoContributorAutoConfigurationTests.java @@ -190,10 +190,7 @@ public class InfoContributorAutoConfigurationTests { @Bean public InfoContributor customInfoContributor() { - return new InfoContributor() { - @Override - public void contribute(Info.Builder builder) { - } + return (builder) -> { }; } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ManagementWebSecurityAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ManagementWebSecurityAutoConfigurationTests.java index 65646e782c..2336638e99 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ManagementWebSecurityAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/ManagementWebSecurityAutoConfigurationTests.java @@ -42,8 +42,6 @@ import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.UserDetails; @@ -284,14 +282,8 @@ public class ManagementWebSecurityAutoConfigurationTests { @Bean public AuthenticationManager myAuthenticationManager() { - this.authenticationManager = new AuthenticationManager() { - - @Override - public Authentication authenticate(Authentication authentication) - throws AuthenticationException { - return new TestingAuthenticationToken("foo", "bar"); - } - }; + this.authenticationManager = ( + authentication) -> new TestingAuthenticationToken("foo", "bar"); return this.authenticationManager; } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricExportAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricExportAutoConfigurationTests.java index ac29bd75e3..c3fd908e72 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricExportAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricExportAutoConfigurationTests.java @@ -39,9 +39,6 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.integration.channel.FixedSubscriberChannel; -import org.springframework.messaging.Message; -import org.springframework.messaging.MessageHandler; -import org.springframework.messaging.MessagingException; import org.springframework.messaging.SubscribableChannel; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.test.util.ReflectionTestUtils; @@ -169,12 +166,7 @@ public class MetricExportAutoConfigurationTests { @Bean public SubscribableChannel metricsChannel() { - return new FixedSubscriberChannel(new MessageHandler() { - - @Override - public void handleMessage(Message message) throws MessagingException { - } - + return new FixedSubscriberChannel((message) -> { }); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricFilterAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricFilterAutoConfigurationTests.java index 4b6ce78750..e52ed84b50 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricFilterAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/MetricFilterAutoConfigurationTests.java @@ -26,8 +26,6 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Test; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.springframework.boot.actuate.metrics.CounterService; import org.springframework.boot.actuate.metrics.GaugeService; @@ -100,12 +98,9 @@ public class MetricFilterAutoConfigurationTests { "/test/path"); final MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); - willAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - response.setStatus(200); - return null; - } + willAnswer((invocation) -> { + response.setStatus(200); + return null; }).given(chain).doFilter(request, response); filter.doFilter(request, response, chain); verify(context.getBean(CounterService.class)).increment("status.200.test.path"); @@ -364,12 +359,9 @@ public class MetricFilterAutoConfigurationTests { "/test/path"); final MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); - willAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - response.setStatus(200); - return null; - } + willAnswer((invocation) -> { + response.setStatus(200); + return null; }).given(chain).doFilter(request, response); filter.doFilter(request, response, chain); verify(context.getBean(GaugeService.class)).submit(eq("response.test.path"), @@ -395,12 +387,9 @@ public class MetricFilterAutoConfigurationTests { "/test/path"); final MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); - willAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - response.setStatus(200); - return null; - } + willAnswer((invocation) -> { + response.setStatus(200); + return null; }).given(chain).doFilter(request, response); filter.doFilter(request, response, chain); verify(context.getBean(GaugeService.class), never()).submit(anyString(), @@ -420,13 +409,10 @@ public class MetricFilterAutoConfigurationTests { "/test/path"); final MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); - willAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - response.setStatus(200); - response.setCommitted(true); - throw new IOException(); - } + willAnswer((invocation) -> { + response.setStatus(200); + response.setCommitted(true); + throw new IOException(); }).given(chain).doFilter(request, response); try { filter.doFilter(request, response, chain); @@ -505,16 +491,12 @@ public class MetricFilterAutoConfigurationTests { @RequestMapping("create") public DeferredResult> create() { final DeferredResult> result = new DeferredResult<>(); - new Thread(new Runnable() { - @Override - public void run() { - try { - MetricFilterTestController.this.latch.await(); - result.setResult( - new ResponseEntity<>("Done", HttpStatus.CREATED)); - } - catch (InterruptedException ex) { - } + new Thread(() -> { + try { + MetricFilterTestController.this.latch.await(); + result.setResult(new ResponseEntity<>("Done", HttpStatus.CREATED)); + } + catch (InterruptedException ex) { } }).start(); return result; @@ -523,16 +505,12 @@ public class MetricFilterAutoConfigurationTests { @RequestMapping("createFailure") public DeferredResult> createFailure() { final DeferredResult> result = new DeferredResult<>(); - new Thread(new Runnable() { - @Override - public void run() { - try { - MetricFilterTestController.this.latch.await(); - result.setErrorResult(new Exception("It failed")); - } - catch (InterruptedException ex) { - - } + new Thread(() -> { + try { + MetricFilterTestController.this.latch.await(); + result.setErrorResult(new Exception("It failed")); + } + catch (InterruptedException ex) { } }).start(); return result; diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/PublicMetricsAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/PublicMetricsAutoConfigurationTests.java index f4d3138636..b81290f0b0 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/PublicMetricsAutoConfigurationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/PublicMetricsAutoConfigurationTests.java @@ -16,7 +16,6 @@ package org.springframework.boot.actuate.autoconfigure; -import java.sql.Connection; import java.sql.SQLException; import java.util.Collection; import java.util.Collections; @@ -54,7 +53,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.core.annotation.Order; -import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.ConnectionCallback; import org.springframework.jdbc.core.JdbcTemplate; @@ -140,18 +138,10 @@ public class PublicMetricsAutoConfigurationTests { Collection> metrics = bean.metrics(); assertMetrics(metrics, "datasource.tomcat.active", "datasource.tomcat.usage", "datasource.commonsDbcp.active", "datasource.commonsDbcp.usage"); - // Hikari won't work unless a first connection has been retrieved JdbcTemplate jdbcTemplate = new JdbcTemplate( this.context.getBean("hikariDS", DataSource.class)); - jdbcTemplate.execute(new ConnectionCallback() { - @Override - public Void doInConnection(Connection connection) - throws SQLException, DataAccessException { - return null; - } - }); - + jdbcTemplate.execute((ConnectionCallback) (connection) -> null); Collection> anotherMetrics = bean.metrics(); assertMetrics(anotherMetrics, "datasource.tomcat.active", "datasource.tomcat.usage", "datasource.hikariDS.active", diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryEndpointHandlerMappingTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryEndpointHandlerMappingTests.java index 77f61c24c9..339bfe9eef 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryEndpointHandlerMappingTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cloudfoundry/CloudFoundryEndpointHandlerMappingTests.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. @@ -26,7 +26,6 @@ import org.springframework.boot.actuate.endpoint.mvc.AbstractEndpointHandlerMapp import org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter; import org.springframework.boot.actuate.endpoint.mvc.HalJsonMvcEndpoint; import org.springframework.boot.actuate.endpoint.mvc.HealthMvcEndpoint; -import org.springframework.boot.actuate.endpoint.mvc.ManagementServletContext; import org.springframework.boot.actuate.endpoint.mvc.NamedMvcEndpoint; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.boot.actuate.health.OrderedHealthAggregator; @@ -118,14 +117,7 @@ public class CloudFoundryEndpointHandlerMappingTests private static class TestHalJsonMvcEndpoint extends HalJsonMvcEndpoint { TestHalJsonMvcEndpoint() { - super(new ManagementServletContext() { - - @Override - public String getContextPath() { - return ""; - } - - }); + super(() -> ""); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/HealthEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/HealthEndpointTests.java index 84c40c73f9..c81022f1c8 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/HealthEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/HealthEndpointTests.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. @@ -61,13 +61,7 @@ public class HealthEndpointTests extends AbstractEndpointTests { @Bean public HealthIndicator statusHealthIndicator() { - return new HealthIndicator() { - - @Override - public Health health() { - return new Health.Builder().status("FINE").build(); - } - }; + return () -> new Health.Builder().status("FINE").build(); } @Bean diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/InfoEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/InfoEndpointTests.java index 20dafc229d..0566d32b03 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/InfoEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/InfoEndpointTests.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. @@ -21,7 +21,6 @@ import java.util.Map; import org.junit.Test; -import org.springframework.boot.actuate.info.Info; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; @@ -54,14 +53,7 @@ public class InfoEndpointTests extends AbstractEndpointTests { @Bean public InfoContributor infoContributor() { - return new InfoContributor() { - - @Override - public void contribute(Info.Builder builder) { - builder.withDetail("key1", "value1"); - } - - }; + return (builder) -> builder.withDetail("key1", "value1"); } @Bean diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/MetricsEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/MetricsEndpointTests.java index 200d8a3d63..c5840c4e55 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/MetricsEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/MetricsEndpointTests.java @@ -100,14 +100,8 @@ public class MetricsEndpointTests extends AbstractEndpointTests @Bean public MetricsEndpoint endpoint() { - final Metric metric = new Metric<>("a", 0.5f); - PublicMetrics metrics = new PublicMetrics() { - @Override - public Collection> metrics() { - return Collections.>singleton(metric); - } - }; - return new MetricsEndpoint(metrics); + Metric metric = new Metric<>("a", 0.5f); + return new MetricsEndpoint(() -> Collections.singleton(metric)); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ShutdownEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ShutdownEndpointTests.java index 93d6f24577..81cf5d4d66 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ShutdownEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ShutdownEndpointTests.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. @@ -88,15 +88,10 @@ public class ShutdownEndpointTests extends AbstractEndpointTests listener() { - return new ApplicationListener() { - - @Override - public void onApplicationEvent(ContextClosedEvent event) { - Config.this.threadContextClassLoader = Thread.currentThread() - .getContextClassLoader(); - Config.this.latch.countDown(); - } - + return (event) -> { + this.threadContextClassLoader = Thread.currentThread() + .getContextClassLoader(); + this.latch.countDown(); }; } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ShutdownParentEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ShutdownParentEndpointTests.java index 256f8ab29a..2db08db4bb 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ShutdownParentEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ShutdownParentEndpointTests.java @@ -89,12 +89,7 @@ public class ShutdownParentEndpointTests { @Bean public ApplicationListener listener() { - return new ApplicationListener() { - @Override - public void onApplicationEvent(ContextClosedEvent event) { - Config.this.latch.countDown(); - } - }; + return (event) -> this.latch.countDown(); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HeapdumpMvcEndpointSecureOptionsTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HeapdumpMvcEndpointSecureOptionsTests.java index bb496b6119..5bb1a3bd11 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HeapdumpMvcEndpointSecureOptionsTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HeapdumpMvcEndpointSecureOptionsTests.java @@ -16,7 +16,6 @@ package org.springframework.boot.actuate.endpoint.mvc; -import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; @@ -110,24 +109,17 @@ public class HeapdumpMvcEndpointSecureOptionsTests { @Override protected HeapDumper createHeapDumper() { - return new HeapDumper() { - - @Override - public void dumpHeap(File file, boolean live) - throws IOException, InterruptedException { - if (!TestHeapdumpMvcEndpoint.this.available) { - throw new HeapDumperUnavailableException("Not available", null); - } - if (TestHeapdumpMvcEndpoint.this.locked) { - throw new InterruptedException(); - } - if (file.exists()) { - throw new IOException("File exists"); - } - FileCopyUtils.copy(TestHeapdumpMvcEndpoint.this.heapDump.getBytes(), - file); + return (file, live) -> { + if (!TestHeapdumpMvcEndpoint.this.available) { + throw new HeapDumperUnavailableException("Not available", null); } - + if (TestHeapdumpMvcEndpoint.this.locked) { + throw new InterruptedException(); + } + if (file.exists()) { + throw new IOException("File exists"); + } + FileCopyUtils.copy(this.heapDump.getBytes(), file); }; } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HeapdumpMvcEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HeapdumpMvcEndpointTests.java index 3f20a25220..2117a0a8e7 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HeapdumpMvcEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HeapdumpMvcEndpointTests.java @@ -16,7 +16,6 @@ package org.springframework.boot.actuate.endpoint.mvc; -import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import java.util.zip.GZIPInputStream; @@ -150,24 +149,17 @@ public class HeapdumpMvcEndpointTests { @Override protected HeapDumper createHeapDumper() { - return new HeapDumper() { - - @Override - public void dumpHeap(File file, boolean live) - throws IOException, InterruptedException { - if (!TestHeapdumpMvcEndpoint.this.available) { - throw new HeapDumperUnavailableException("Not available", null); - } - if (TestHeapdumpMvcEndpoint.this.locked) { - throw new InterruptedException(); - } - if (file.exists()) { - throw new IOException("File exists"); - } - FileCopyUtils.copy(TestHeapdumpMvcEndpoint.this.heapDump.getBytes(), - file); + return (file, live) -> { + if (!TestHeapdumpMvcEndpoint.this.available) { + throw new HeapDumperUnavailableException("Not available", null); } - + if (TestHeapdumpMvcEndpoint.this.locked) { + throw new InterruptedException(); + } + if (file.exists()) { + throw new IOException("File exists"); + } + FileCopyUtils.copy(this.heapDump.getBytes(), file); }; } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/InfoMvcEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/InfoMvcEndpointTests.java index d23a817d39..eb925246d9 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/InfoMvcEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/InfoMvcEndpointTests.java @@ -28,7 +28,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.autoconfigure.AuditAutoConfiguration; import org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration; import org.springframework.boot.actuate.endpoint.InfoEndpoint; -import org.springframework.boot.actuate.info.Info; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration; import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; @@ -110,28 +109,21 @@ public class InfoMvcEndpointTests { @Bean public InfoContributor beanName1() { - return new InfoContributor() { - - @Override - public void contribute(Info.Builder builder) { - Map content = new LinkedHashMap<>(); - content.put("key11", "value11"); - content.put("key12", "value12"); - builder.withDetail("beanName1", content); - } + return (builder) -> { + Map content = new LinkedHashMap<>(); + content.put("key11", "value11"); + content.put("key12", "value12"); + builder.withDetail("beanName1", content); }; } @Bean public InfoContributor beanName2() { - return new InfoContributor() { - @Override - public void contribute(Info.Builder builder) { - Map content = new LinkedHashMap<>(); - content.put("key21", "value21"); - content.put("key22", "value22"); - builder.withDetail("beanName2", content); - } + return (builder) -> { + Map content = new LinkedHashMap<>(); + content.put("key21", "value21"); + content.put("key22", "value22"); + builder.withDetail("beanName2", content); }; } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MetricsMvcEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MetricsMvcEndpointTests.java index 7e4e21d863..c59af65e2e 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MetricsMvcEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/MetricsMvcEndpointTests.java @@ -17,7 +17,6 @@ package org.springframework.boot.actuate.endpoint.mvc; import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; import org.junit.Before; @@ -28,7 +27,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.autoconfigure.AuditAutoConfiguration; import org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration; import org.springframework.boot.actuate.endpoint.MetricsEndpoint; -import org.springframework.boot.actuate.endpoint.PublicMetrics; import org.springframework.boot.actuate.metrics.Metric; import org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration; import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; @@ -182,21 +180,16 @@ public class MetricsMvcEndpointTests { @Bean public MetricsEndpoint endpoint() { - return new MetricsEndpoint(new PublicMetrics() { - - @Override - public Collection> metrics() { - ArrayList> metrics = new ArrayList<>(); - metrics.add(new Metric<>("foo", 1)); - metrics.add(new Metric<>("bar.png", 1)); - metrics.add(new Metric<>("group1.a", 1)); - metrics.add(new Metric<>("group1.b", 1)); - metrics.add(new Metric<>("group2.a", 1)); - metrics.add(new Metric<>("group2_a", 1)); - metrics.add(new Metric("baz", null)); - return Collections.unmodifiableList(metrics); - } - + return new MetricsEndpoint(() -> { + ArrayList> metrics = new ArrayList<>(); + metrics.add(new Metric<>("foo", 1)); + metrics.add(new Metric<>("bar.png", 1)); + metrics.add(new Metric<>("group1.a", 1)); + metrics.add(new Metric<>("group1.b", 1)); + metrics.add(new Metric<>("group2.a", 1)); + metrics.add(new Metric<>("group2_a", 1)); + metrics.add(new Metric("baz", null)); + return Collections.unmodifiableList(metrics); }); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/NoSpringSecurityHealthMvcEndpointIntegrationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/NoSpringSecurityHealthMvcEndpointIntegrationTests.java index 122a7d039e..95b2f3a46a 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/NoSpringSecurityHealthMvcEndpointIntegrationTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/NoSpringSecurityHealthMvcEndpointIntegrationTests.java @@ -36,7 +36,6 @@ import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockServletContext; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.RequestPostProcessor; @@ -93,16 +92,10 @@ public class NoSpringSecurityHealthMvcEndpointIntegrationTests { } private RequestPostProcessor getRequestPostProcessor() { - return new RequestPostProcessor() { - - @Override - public MockHttpServletRequest postProcessRequest( - MockHttpServletRequest request) { - Principal principal = mock(Principal.class); - request.setUserPrincipal(principal); - return request; - } - + return (request) -> { + Principal principal = mock(Principal.class); + request.setUserPrincipal(principal); + return request; }; } @@ -115,14 +108,7 @@ public class NoSpringSecurityHealthMvcEndpointIntegrationTests { @Bean public HealthIndicator testHealthIndicator() { - return new HealthIndicator() { - - @Override - public Health health() { - return Health.up().withDetail("hello", "world").build(); - } - - }; + return () -> Health.up().withDetail("hello", "world").build(); } } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/ShutdownMvcEndpointTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/ShutdownMvcEndpointTests.java index 908c73f704..d180f451bf 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/ShutdownMvcEndpointTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/ShutdownMvcEndpointTests.java @@ -22,8 +22,6 @@ import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; @@ -123,14 +121,9 @@ public class ShutdownMvcEndpointTests { throws BeansException { ConfigurableApplicationContext mockContext = mock( ConfigurableApplicationContext.class); - willAnswer(new Answer() { - - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - TestShutdownEndpoint.this.contextCloseLatch.countDown(); - return null; - } - + willAnswer((invocation) -> { + TestShutdownEndpoint.this.contextCloseLatch.countDown(); + return null; }).given(mockContext).close(); super.setApplicationContext(mockContext); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/BufferGaugeServiceSpeedTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/BufferGaugeServiceSpeedTests.java index 322f1d97b0..7aa995718a 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/BufferGaugeServiceSpeedTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/BufferGaugeServiceSpeedTests.java @@ -26,8 +26,6 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.DoubleAdder; import java.util.concurrent.atomic.LongAdder; -import java.util.function.BiConsumer; -import java.util.function.Consumer; import java.util.regex.Pattern; import org.junit.AfterClass; @@ -38,7 +36,6 @@ import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; import org.springframework.boot.actuate.metrics.GaugeService; -import org.springframework.boot.actuate.metrics.Metric; import org.springframework.util.StopWatch; import static org.assertj.core.api.Assertions.assertThat; @@ -79,7 +76,7 @@ public class BufferGaugeServiceSpeedTests { @BeforeClass public static void prime() throws FileNotFoundException { err = new NullPrintWriter(); - final Random random = new Random(); + Random random = new Random(); for (int i = 0; i < 1000; i++) { sample[i] = names[random.nextInt(names.length)]; } @@ -98,21 +95,11 @@ public class BufferGaugeServiceSpeedTests { watch.start("readRaw" + count); for (String name : names) { this.gauges.forEach(Pattern.compile(name).asPredicate(), - new BiConsumer() { - @Override - public void accept(String name, GaugeBuffer value) { - err.println(name + "=" + value); - } - }); + (key, value) -> err.println(key + "=" + value)); } - final DoubleAdder total = new DoubleAdder(); + DoubleAdder total = new DoubleAdder(); this.gauges.forEach(Pattern.compile(".*").asPredicate(), - new BiConsumer() { - @Override - public void accept(String name, GaugeBuffer value) { - total.add(value.getValue()); - } - }); + (name, value) -> total.add(value.getValue())); watch.stop(); System.err.println("Read(" + count + ")=" + watch.getLastTaskTimeMillis() + "ms"); assertThat(number * threadCount < total.longValue()).isTrue(); @@ -124,19 +111,9 @@ public class BufferGaugeServiceSpeedTests { double rate = number / watch.getLastTaskTimeMillis() * 1000; System.err.println("Rate(" + count + ")=" + rate + ", " + watch); watch.start("readReader" + count); - this.reader.findAll().forEach(new Consumer>() { - @Override - public void accept(Metric metric) { - err.println(metric); - } - }); - final LongAdder total = new LongAdder(); - this.reader.findAll().forEach(new Consumer>() { - @Override - public void accept(Metric value) { - total.add(value.getValue().intValue()); - } - }); + this.reader.findAll().forEach((metric) -> err.println(metric)); + LongAdder total = new LongAdder(); + this.reader.findAll().forEach((value) -> total.add(value.getValue().intValue())); watch.stop(); System.err.println("Read(" + count + ")=" + watch.getLastTaskTimeMillis() + "ms"); assertThat(0 < total.longValue()).isTrue(); @@ -145,13 +122,10 @@ public class BufferGaugeServiceSpeedTests { private void iterate(String taskName) throws Exception { watch.start(taskName + count++); ExecutorService pool = Executors.newFixedThreadPool(threadCount); - Runnable task = new Runnable() { - @Override - public void run() { - for (int i = 0; i < number; i++) { - String name = sample[i % sample.length]; - BufferGaugeServiceSpeedTests.this.service.submit(name, count + i); - } + Runnable task = () -> { + for (int i = 0; i < number; i++) { + String name = sample[i % sample.length]; + BufferGaugeServiceSpeedTests.this.service.submit(name, count + i); } }; Collection> futures = new HashSet<>(); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/CounterBuffersTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/CounterBuffersTests.java index 0722c5f67e..72b4a0f07f 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/CounterBuffersTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/CounterBuffersTests.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. @@ -16,8 +16,6 @@ package org.springframework.boot.actuate.metrics.buffer; -import java.util.function.Consumer; - import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -36,23 +34,15 @@ public class CounterBuffersTests { @Test public void inAndOut() { this.buffers.increment("foo", 2); - this.buffers.doWith("foo", new Consumer() { - @Override - public void accept(CounterBuffer buffer) { - CounterBuffersTests.this.value = buffer.getValue(); - } - }); + this.buffers.doWith("foo", + (buffer) -> CounterBuffersTests.this.value = buffer.getValue()); assertThat(this.value).isEqualTo(2); } @Test public void getNonExistent() { - this.buffers.doWith("foo", new Consumer() { - @Override - public void accept(CounterBuffer buffer) { - CounterBuffersTests.this.value = buffer.getValue(); - } - }); + this.buffers.doWith("foo", + (buffer) -> CounterBuffersTests.this.value = buffer.getValue()); assertThat(this.value).isEqualTo(0); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/CounterServiceSpeedTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/CounterServiceSpeedTests.java index f309fabd04..e3e9354649 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/CounterServiceSpeedTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/CounterServiceSpeedTests.java @@ -25,8 +25,6 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.LongAdder; -import java.util.function.BiConsumer; -import java.util.function.Consumer; import java.util.regex.Pattern; import org.junit.AfterClass; @@ -37,7 +35,6 @@ import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; import org.springframework.boot.actuate.metrics.CounterService; -import org.springframework.boot.actuate.metrics.Metric; import org.springframework.util.StopWatch; import static org.assertj.core.api.Assertions.assertThat; @@ -78,7 +75,7 @@ public class CounterServiceSpeedTests { @BeforeClass public static void prime() throws FileNotFoundException { err = new NullPrintWriter(); - final Random random = new Random(); + Random random = new Random(); for (int i = 0; i < 1000; i++) { sample[i] = names[random.nextInt(names.length)]; } @@ -97,21 +94,11 @@ public class CounterServiceSpeedTests { watch.start("readRaw" + count); for (String name : names) { this.counters.forEach(Pattern.compile(name).asPredicate(), - new BiConsumer() { - @Override - public void accept(String name, CounterBuffer value) { - err.println(name + "=" + value); - } - }); + (key, value) -> err.println(key + "=" + value)); } - final LongAdder total = new LongAdder(); + LongAdder total = new LongAdder(); this.counters.forEach(Pattern.compile(".*").asPredicate(), - new BiConsumer() { - @Override - public void accept(String name, CounterBuffer value) { - total.add(value.getValue()); - } - }); + (name, value) -> total.add(value.getValue())); watch.stop(); System.err.println("Read(" + count + ")=" + watch.getLastTaskTimeMillis() + "ms"); assertThat(total.longValue()).isEqualTo(number * threadCount); @@ -123,19 +110,9 @@ public class CounterServiceSpeedTests { double rate = number / watch.getLastTaskTimeMillis() * 1000; System.err.println("Rate(" + count + ")=" + rate + ", " + watch); watch.start("readReader" + count); - this.reader.findAll().forEach(new Consumer>() { - @Override - public void accept(Metric metric) { - err.println(metric); - } - }); - final LongAdder total = new LongAdder(); - this.reader.findAll().forEach(new Consumer>() { - @Override - public void accept(Metric value) { - total.add(value.getValue().intValue()); - } - }); + this.reader.findAll().forEach(err::println); + LongAdder total = new LongAdder(); + this.reader.findAll().forEach((value) -> total.add(value.getValue().intValue())); watch.stop(); System.err.println("Read(" + count + ")=" + watch.getLastTaskTimeMillis() + "ms"); assertThat(total.longValue()).isEqualTo(number * threadCount); @@ -144,13 +121,10 @@ public class CounterServiceSpeedTests { private void iterate(String taskName) throws Exception { watch.start(taskName + count++); ExecutorService pool = Executors.newFixedThreadPool(threadCount); - Runnable task = new Runnable() { - @Override - public void run() { - for (int i = 0; i < number; i++) { - String name = sample[i % sample.length]; - CounterServiceSpeedTests.this.service.increment(name); - } + Runnable task = () -> { + for (int i = 0; i < number; i++) { + String name = sample[i % sample.length]; + CounterServiceSpeedTests.this.service.increment(name); } }; Collection> futures = new HashSet<>(); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DefaultCounterServiceSpeedTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DefaultCounterServiceSpeedTests.java index 4b9720705b..d4e6b37f81 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DefaultCounterServiceSpeedTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DefaultCounterServiceSpeedTests.java @@ -25,7 +25,6 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.LongAdder; -import java.util.function.Consumer; import org.junit.BeforeClass; import org.junit.experimental.theories.DataPoints; @@ -34,7 +33,6 @@ import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; import org.springframework.boot.actuate.metrics.CounterService; -import org.springframework.boot.actuate.metrics.Metric; import org.springframework.boot.actuate.metrics.reader.MetricReader; import org.springframework.boot.actuate.metrics.repository.InMemoryMetricRepository; import org.springframework.boot.actuate.metrics.writer.DefaultCounterService; @@ -87,13 +85,10 @@ public class DefaultCounterServiceSpeedTests { public void counters(String input) throws Exception { watch.start("counters" + count++); ExecutorService pool = Executors.newFixedThreadPool(threadCount); - Runnable task = new Runnable() { - @Override - public void run() { - for (int i = 0; i < number; i++) { - String name = sample[i % sample.length]; - DefaultCounterServiceSpeedTests.this.counterService.increment(name); - } + Runnable task = () -> { + for (int i = 0; i < number; i++) { + String name = sample[i % sample.length]; + DefaultCounterServiceSpeedTests.this.counterService.increment(name); } }; Collection> futures = new HashSet<>(); @@ -107,19 +102,9 @@ public class DefaultCounterServiceSpeedTests { double rate = number / watch.getLastTaskTimeMillis() * 1000; System.err.println("Counters rate(" + count + ")=" + rate + ", " + watch); watch.start("read" + count); - this.reader.findAll().forEach(new Consumer>() { - @Override - public void accept(Metric metric) { - err.println(metric); - } - }); - final LongAdder total = new LongAdder(); - this.reader.findAll().forEach(new Consumer>() { - @Override - public void accept(Metric value) { - total.add(value.getValue().intValue()); - } - }); + this.reader.findAll().forEach(err::println); + LongAdder total = new LongAdder(); + this.reader.findAll().forEach((value) -> total.add(value.getValue().intValue())); watch.stop(); System.err.println("Read(" + count + ")=" + watch.getLastTaskTimeMillis() + "ms"); assertThat(total.longValue()).isEqualTo(number * threadCount); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DefaultGaugeServiceSpeedTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DefaultGaugeServiceSpeedTests.java index bc869573af..b8d8398d9d 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DefaultGaugeServiceSpeedTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DefaultGaugeServiceSpeedTests.java @@ -25,7 +25,6 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.LongAdder; -import java.util.function.Consumer; import org.junit.BeforeClass; import org.junit.experimental.theories.DataPoints; @@ -34,7 +33,6 @@ import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; import org.springframework.boot.actuate.metrics.GaugeService; -import org.springframework.boot.actuate.metrics.Metric; import org.springframework.boot.actuate.metrics.reader.MetricReader; import org.springframework.boot.actuate.metrics.repository.InMemoryMetricRepository; import org.springframework.boot.actuate.metrics.writer.DefaultGaugeService; @@ -77,7 +75,7 @@ public class DefaultGaugeServiceSpeedTests { @BeforeClass public static void prime() throws FileNotFoundException { err = new NullPrintWriter(); - final Random random = new Random(); + Random random = new Random(); for (int i = 0; i < 1000; i++) { sample[i] = names[random.nextInt(names.length)]; } @@ -87,14 +85,10 @@ public class DefaultGaugeServiceSpeedTests { public void gauges(String input) throws Exception { watch.start("gauges" + count++); ExecutorService pool = Executors.newFixedThreadPool(threadCount); - Runnable task = new Runnable() { - @Override - public void run() { - for (int i = 0; i < number; i++) { - String name = sample[i % sample.length]; - DefaultGaugeServiceSpeedTests.this.gaugeService.submit(name, - count + i); - } + Runnable task = () -> { + for (int i = 0; i < number; i++) { + String name = sample[i % sample.length]; + DefaultGaugeServiceSpeedTests.this.gaugeService.submit(name, count + i); } }; Collection> futures = new HashSet<>(); @@ -108,19 +102,9 @@ public class DefaultGaugeServiceSpeedTests { double rate = number / watch.getLastTaskTimeMillis() * 1000; System.err.println("Gauges rate(" + count + ")=" + rate + ", " + watch); watch.start("read" + count); - this.reader.findAll().forEach(new Consumer>() { - @Override - public void accept(Metric metric) { - err.println(metric); - } - }); - final LongAdder total = new LongAdder(); - this.reader.findAll().forEach(new Consumer>() { - @Override - public void accept(Metric value) { - total.add(value.getValue().intValue()); - } - }); + this.reader.findAll().forEach(err::println); + LongAdder total = new LongAdder(); + this.reader.findAll().forEach((value) -> total.add(value.getValue().intValue())); watch.stop(); System.err.println("Read(" + count + ")=" + watch.getLastTaskTimeMillis() + "ms"); assertThat(0 < total.longValue()).isTrue(); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DropwizardCounterServiceSpeedTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DropwizardCounterServiceSpeedTests.java index 3b547b2ca7..bb1c958861 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DropwizardCounterServiceSpeedTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/buffer/DropwizardCounterServiceSpeedTests.java @@ -25,7 +25,6 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.LongAdder; -import java.util.function.Consumer; import com.codahale.metrics.MetricRegistry; import org.junit.BeforeClass; @@ -35,7 +34,6 @@ import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; import org.springframework.boot.actuate.metrics.CounterService; -import org.springframework.boot.actuate.metrics.Metric; import org.springframework.boot.actuate.metrics.dropwizard.DropwizardMetricServices; import org.springframework.boot.actuate.metrics.reader.MetricReader; import org.springframework.boot.actuate.metrics.reader.MetricRegistryMetricReader; @@ -79,7 +77,7 @@ public class DropwizardCounterServiceSpeedTests { @BeforeClass public static void prime() throws FileNotFoundException { err = new NullPrintWriter(); - final Random random = new Random(); + Random random = new Random(); for (int i = 0; i < 1000; i++) { sample[i] = names[random.nextInt(names.length)]; } @@ -89,14 +87,10 @@ public class DropwizardCounterServiceSpeedTests { public void counters(String input) throws Exception { watch.start("counters" + count++); ExecutorService pool = Executors.newFixedThreadPool(threadCount); - Runnable task = new Runnable() { - @Override - public void run() { - for (int i = 0; i < number; i++) { - String name = sample[i % sample.length]; - DropwizardCounterServiceSpeedTests.this.counterService - .increment(name); - } + Runnable task = () -> { + for (int i = 0; i < number; i++) { + String name = sample[i % sample.length]; + DropwizardCounterServiceSpeedTests.this.counterService.increment(name); } }; Collection> futures = new HashSet<>(); @@ -110,19 +104,9 @@ public class DropwizardCounterServiceSpeedTests { double rate = number / watch.getLastTaskTimeMillis() * 1000; System.err.println("Counters rate(" + count + ")=" + rate + ", " + watch); watch.start("read" + count); - this.reader.findAll().forEach(new Consumer>() { - @Override - public void accept(Metric metric) { - err.println(metric); - } - }); - final LongAdder total = new LongAdder(); - this.reader.findAll().forEach(new Consumer>() { - @Override - public void accept(Metric value) { - total.add(value.getValue().intValue()); - } - }); + this.reader.findAll().forEach(err::println); + LongAdder total = new LongAdder(); + this.reader.findAll().forEach((value) -> total.add(value.getValue().intValue())); watch.stop(); System.err.println("Read(" + count + ")=" + watch.getLastTaskTimeMillis() + "ms"); assertThat(total.longValue()).isEqualTo(number * threadCount); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/reader/MetricRegistryMetricReaderTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/reader/MetricRegistryMetricReaderTests.java index b409551aa4..c69eee736f 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/reader/MetricRegistryMetricReaderTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/reader/MetricRegistryMetricReaderTests.java @@ -41,14 +41,7 @@ public class MetricRegistryMetricReaderTests { @Test public void nonNumberGaugesAreTolerated() { - this.metricRegistry.register("test", new Gauge>() { - - @Override - public Set getValue() { - return new HashSet<>(); - } - - }); + this.metricRegistry.register("test", (Gauge>) HashSet::new); assertThat(this.metricReader.findOne("test")).isNull(); this.metricRegistry.remove("test"); assertThat(this.metricReader.findOne("test")).isNull(); @@ -57,14 +50,7 @@ public class MetricRegistryMetricReaderTests { @Test @SuppressWarnings("unchecked") public void numberGauge() { - this.metricRegistry.register("test", new Gauge() { - - @Override - public Number getValue() { - return Integer.valueOf(5); - } - - }); + this.metricRegistry.register("test", (Gauge) () -> Integer.valueOf(5)); Metric metric = (Metric) this.metricReader.findOne("test"); assertThat(metric.getValue()).isEqualTo(Integer.valueOf(5)); this.metricRegistry.remove("test"); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/util/SimpleInMemoryRepositoryTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/util/SimpleInMemoryRepositoryTests.java index 049a606dd4..dd80db3f3f 100755 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/util/SimpleInMemoryRepositoryTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/util/SimpleInMemoryRepositoryTests.java @@ -27,8 +27,6 @@ import java.util.concurrent.TimeUnit; import org.junit.Test; -import org.springframework.boot.actuate.metrics.util.SimpleInMemoryRepository.Callback; - import static org.assertj.core.api.Assertions.assertThat; /** @@ -49,23 +47,13 @@ public class SimpleInMemoryRepositoryTests { @Test public void updateExisting() { this.repository.set("foo", "spam"); - this.repository.update("foo", new Callback() { - @Override - public String modify(String current) { - return "bar"; - } - }); + this.repository.update("foo", (current) -> "bar"); assertThat(this.repository.findOne("foo")).isEqualTo("bar"); } @Test public void updateNonexistent() { - this.repository.update("foo", new Callback() { - @Override - public String modify(String current) { - return "bar"; - } - }); + this.repository.update("foo", (current) -> "bar"); assertThat(this.repository.findOne("foo")).isEqualTo("bar"); } @@ -114,16 +102,11 @@ public class SimpleInMemoryRepositoryTests { @Override public Boolean call() throws Exception { - this.repository.update("foo", new Callback() { - - @Override - public Integer modify(Integer current) { - if (current == null) { - return RepositoryUpdate.this.delta; - } - return current + RepositoryUpdate.this.delta; + this.repository.update("foo", (current) -> { + if (current == null) { + return RepositoryUpdate.this.delta; } - + return current + RepositoryUpdate.this.delta; }); return true; } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/writer/MessageChannelMetricWriterTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/writer/MessageChannelMetricWriterTests.java index be497c13c5..2f42dee707 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/writer/MessageChannelMetricWriterTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/writer/MessageChannelMetricWriterTests.java @@ -20,8 +20,6 @@ import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.springframework.boot.actuate.metrics.Metric; import org.springframework.messaging.Message; @@ -51,15 +49,10 @@ public class MessageChannelMetricWriterTests { @Before public void setup() { MockitoAnnotations.initMocks(this); - given(this.channel.send(any(Message.class))).willAnswer(new Answer() { - - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - MessageChannelMetricWriterTests.this.handler - .handleMessage(invocation.getArgument(0)); - return true; - } - + given(this.channel.send(any(Message.class))).willAnswer((invocation) -> { + MessageChannelMetricWriterTests.this.handler + .handleMessage(invocation.getArgument(0)); + return true; }); this.writer = new MessageChannelMetricWriter(this.channel); this.handler = new MetricWriterMessageHandler(this.observer); diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/servlet/MockServletWebServerFactory.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/servlet/MockServletWebServerFactory.java index d2b9c8bdac..f1c30b728c 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/servlet/MockServletWebServerFactory.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/servlet/MockServletWebServerFactory.java @@ -69,7 +69,7 @@ public class MockServletWebServerFactory extends AbstractServletWebServerFactory public MockServletWebServer(ServletContextInitializer[] initializers, int port) { super(Arrays.stream(initializers) - .map((i) -> (Initializer) (s) -> i.onStartup(s)) + .map((initializer) -> (Initializer) initializer::onStartup) .toArray(Initializer[]::new), port); } diff --git a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/WebRequestTraceFilterTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/WebRequestTraceFilterTests.java index 4f5c552b5d..3859d61bc9 100644 --- a/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/WebRequestTraceFilterTests.java +++ b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/WebRequestTraceFilterTests.java @@ -24,10 +24,7 @@ import java.util.Collections; import java.util.EnumSet; import java.util.Map; -import javax.servlet.FilterChain; import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; import org.junit.Test; @@ -93,30 +90,17 @@ public class WebRequestTraceFilterTests { request.setPathInfo(url); tmp.deleteOnExit(); request.setAuthType("authType"); - Principal principal = new Principal() { - - @Override - public String getName() { - return "principalTest"; - } - - }; + Principal principal = () -> "principalTest"; request.setUserPrincipal(principal); MockHttpServletResponse response = new MockHttpServletResponse(); response.addHeader("Content-Type", "application/json"); response.addHeader("Set-Cookie", "a=b"); - this.filter.doFilterInternal(request, response, new FilterChain() { - - @Override - public void doFilter(ServletRequest request, ServletResponse response) - throws IOException, ServletException { - BufferedReader bufferedReader = request.getReader(); - while (bufferedReader.readLine() != null) { - // read the contents as normal (forces cache to fill up) - } - response.getWriter().println("Goodbye, World!"); + this.filter.doFilterInternal(request, response, (req, resp) -> { + BufferedReader bufferedReader = req.getReader(); + while (bufferedReader.readLine() != null) { + // read the contents as normal (forces cache to fill up) } - + resp.getWriter().println("Goodbye, World!"); }); assertThat(this.repository.findAll()).hasSize(1); Map trace = this.repository.findAll().iterator().next().getInfo(); @@ -146,11 +130,7 @@ public class WebRequestTraceFilterTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo"); MockHttpServletResponse response = new MockHttpServletResponse(); response.addHeader("Content-Type", "application/json"); - this.filter.doFilterInternal(request, response, new FilterChain() { - @Override - public void doFilter(ServletRequest request, ServletResponse response) - throws IOException, ServletException { - } + this.filter.doFilterInternal(request, response, (req, resp) -> { }); Map info = this.repository.findAll().iterator().next().getInfo(); Map headers = (Map) info.get("headers"); @@ -177,13 +157,7 @@ public class WebRequestTraceFilterTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo"); request.addHeader("Authorization", "my-auth-header"); MockHttpServletResponse response = new MockHttpServletResponse(); - this.filter.doFilterInternal(request, response, new FilterChain() { - - @Override - public void doFilter(ServletRequest request, ServletResponse response) - throws IOException, ServletException { - } - + this.filter.doFilterInternal(request, response, (req, resp) -> { }); Map info = this.repository.findAll().iterator().next().getInfo(); Map headers = (Map) info.get("headers"); @@ -199,13 +173,7 @@ public class WebRequestTraceFilterTests { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo"); request.addHeader("Authorization", "my-auth-header"); MockHttpServletResponse response = new MockHttpServletResponse(); - this.filter.doFilterInternal(request, response, new FilterChain() { - - @Override - public void doFilter(ServletRequest request, ServletResponse response) - throws IOException, ServletException { - } - + this.filter.doFilterInternal(request, response, (req, resp) -> { }); Map info = this.repository.findAll().iterator().next().getInfo(); Map headers = (Map) info.get("headers"); @@ -279,14 +247,8 @@ public class WebRequestTraceFilterTests { MockHttpServletResponse response = new MockHttpServletResponse(); try { - this.filter.doFilterInternal(request, response, new FilterChain() { - - @Override - public void doFilter(ServletRequest request, ServletResponse response) - throws IOException, ServletException { - throw new RuntimeException(); - } - + this.filter.doFilterInternal(request, response, (req, resp) -> { + throw new RuntimeException(); }); fail("Exception was swallowed"); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationSorter.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationSorter.java index ac6e1b8a96..b048908aca 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationSorter.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationSorter.java @@ -20,7 +20,6 @@ import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; @@ -60,15 +59,10 @@ class AutoConfigurationSorter { // Initially sort alphabetically Collections.sort(orderedClassNames); // Then sort by order - orderedClassNames.sort(new Comparator() { - - @Override - public int compare(String o1, String o2) { - int i1 = classes.get(o1).getOrder(); - int i2 = classes.get(o2).getOrder(); - return (i1 < i2) ? -1 : (i1 > i2) ? 1 : 0; - } - + orderedClassNames.sort((o1, o2) -> { + int i1 = classes.get(o1).getOrder(); + int i2 = classes.get(o2).getOrder(); + return (i1 < i2) ? -1 : (i1 > i2) ? 1 : 0; }); // Then respect @AutoConfigureBefore @AutoConfigureAfter orderedClassNames = sortByAnnotation(classes, orderedClassNames); diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnClassCondition.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnClassCondition.java index 6a3a42e556..75fbc54969 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnClassCondition.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnClassCondition.java @@ -253,15 +253,8 @@ class OnClassCondition extends SpringBootCondition private volatile ConditionOutcome[] outcomes; private ThreadedOutcomesResolver(final OutcomesResolver outcomesResolver) { - this.thread = new Thread(new Runnable() { - - @Override - public void run() { - ThreadedOutcomesResolver.this.outcomes = outcomesResolver - .resolveOutcomes(); - } - - }); + this.thread = new Thread( + () -> this.outcomes = outcomesResolver.resolveOutcomes()); this.thread.start(); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/DataSourcePoolMetadataProvidersConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/DataSourcePoolMetadataProvidersConfiguration.java index 526c999410..c5102405ed 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/DataSourcePoolMetadataProvidersConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/metadata/DataSourcePoolMetadataProvidersConfiguration.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. @@ -16,8 +16,6 @@ package org.springframework.boot.autoconfigure.jdbc.metadata; -import javax.sql.DataSource; - import com.zaxxer.hikari.HikariDataSource; import org.apache.commons.dbcp2.BasicDataSource; @@ -41,16 +39,12 @@ public class DataSourcePoolMetadataProvidersConfiguration { @Bean public DataSourcePoolMetadataProvider tomcatPoolDataSourceMetadataProvider() { - return new DataSourcePoolMetadataProvider() { - @Override - public DataSourcePoolMetadata getDataSourcePoolMetadata( - DataSource dataSource) { - if (dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource) { - return new TomcatDataSourcePoolMetadata( - (org.apache.tomcat.jdbc.pool.DataSource) dataSource); - } - return null; + return (dataSource) -> { + if (dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource) { + return new TomcatDataSourcePoolMetadata( + (org.apache.tomcat.jdbc.pool.DataSource) dataSource); } + return null; }; } @@ -62,16 +56,12 @@ public class DataSourcePoolMetadataProvidersConfiguration { @Bean public DataSourcePoolMetadataProvider hikariPoolDataSourceMetadataProvider() { - return new DataSourcePoolMetadataProvider() { - @Override - public DataSourcePoolMetadata getDataSourcePoolMetadata( - DataSource dataSource) { - if (dataSource instanceof HikariDataSource) { - return new HikariDataSourcePoolMetadata( - (HikariDataSource) dataSource); - } - return null; + return (dataSource) -> { + if (dataSource instanceof HikariDataSource) { + return new HikariDataSourcePoolMetadata( + (HikariDataSource) dataSource); } + return null; }; } @@ -83,16 +73,12 @@ public class DataSourcePoolMetadataProvidersConfiguration { @Bean public DataSourcePoolMetadataProvider commonsDbcp2PoolDataSourceMetadataProvider() { - return new DataSourcePoolMetadataProvider() { - @Override - public DataSourcePoolMetadata getDataSourcePoolMetadata( - DataSource dataSource) { - if (dataSource instanceof BasicDataSource) { - return new CommonsDbcp2DataSourcePoolMetadata( - (BasicDataSource) dataSource); - } - return null; + return (dataSource) -> { + if (dataSource instanceof BasicDataSource) { + return new CommonsDbcp2DataSourcePoolMetadata( + (BasicDataSource) dataSource); } + return null; }; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfiguration.java index c85d5f426f..29b202af6b 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfiguration.java @@ -243,13 +243,10 @@ public class JerseyAutoConfiguration implements ServletContextAware { public ResourceConfigCustomizer resourceConfigCustomizer( final ObjectMapper objectMapper) { addJaxbAnnotationIntrospectorIfPresent(objectMapper); - return new ResourceConfigCustomizer() { - @Override - public void customize(ResourceConfig config) { - config.register(JacksonFeature.class); - config.register(new ObjectMapperContextResolver(objectMapper), - ContextResolver.class); - } + return (ResourceConfig config) -> { + config.register(JacksonFeature.class); + config.register(new ObjectMapperContextResolver(objectMapper), + ContextResolver.class); }; } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SpringBootWebSecurityConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SpringBootWebSecurityConfiguration.java index cd243eaf03..0439bb0e59 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SpringBootWebSecurityConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SpringBootWebSecurityConfiguration.java @@ -20,8 +20,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import javax.servlet.http.HttpServletRequest; - import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; @@ -230,12 +228,7 @@ public class SpringBootWebSecurityConfiguration { @Override protected void configure(HttpSecurity http) throws Exception { - http.requestMatcher(new RequestMatcher() { - @Override - public boolean matches(HttpServletRequest request) { - return false; - } - }); + http.requestMatcher(request -> false); } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/social/SocialWebAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/social/SocialWebAutoConfiguration.java index 45adb754d2..47c509cdac 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/social/SocialWebAutoConfiguration.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/social/SocialWebAutoConfiguration.java @@ -140,12 +140,7 @@ public class SocialWebAutoConfiguration { @Override public UserIdSource getUserIdSource() { - return new UserIdSource() { - @Override - public String getUserId() { - return "anonymous"; - } - }; + return () -> "anonymous"; } } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DefaultServletWebServerFactoryCustomizer.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DefaultServletWebServerFactoryCustomizer.java index 8604e5c73d..5f2330273a 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DefaultServletWebServerFactoryCustomizer.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DefaultServletWebServerFactoryCustomizer.java @@ -23,10 +23,7 @@ import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.SessionCookieConfig; -import io.undertow.Undertow; import io.undertow.UndertowOptions; -import org.apache.catalina.Context; -import org.apache.catalina.connector.Connector; import org.apache.catalina.valves.AccessLogValve; import org.apache.catalina.valves.RemoteIpValve; import org.apache.coyote.AbstractProtocol; @@ -47,10 +44,7 @@ import org.springframework.boot.autoconfigure.web.ServerProperties.Session; import org.springframework.boot.cloud.CloudPlatform; import org.springframework.boot.web.embedded.jetty.JettyServerCustomizer; import org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory; -import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer; -import org.springframework.boot.web.embedded.tomcat.TomcatContextCustomizer; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; -import org.springframework.boot.web.embedded.undertow.UndertowBuilderCustomizer; import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory; import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.boot.web.servlet.ServletContextInitializer; @@ -269,49 +263,34 @@ public class DefaultServletWebServerFactoryCustomizer private static void customizeAcceptCount(TomcatServletWebServerFactory factory, final int acceptCount) { - factory.addConnectorCustomizers(new TomcatConnectorCustomizer() { - - @Override - public void customize(Connector connector) { - ProtocolHandler handler = connector.getProtocolHandler(); - if (handler instanceof AbstractProtocol) { - AbstractProtocol protocol = (AbstractProtocol) handler; - protocol.setAcceptCount(acceptCount); - } + factory.addConnectorCustomizers((connector) -> { + ProtocolHandler handler = connector.getProtocolHandler(); + if (handler instanceof AbstractProtocol) { + AbstractProtocol protocol = (AbstractProtocol) handler; + protocol.setAcceptCount(acceptCount); } - }); } private static void customizeMaxConnections(TomcatServletWebServerFactory factory, final int maxConnections) { - factory.addConnectorCustomizers(new TomcatConnectorCustomizer() { - - @Override - public void customize(Connector connector) { - ProtocolHandler handler = connector.getProtocolHandler(); - if (handler instanceof AbstractProtocol) { - AbstractProtocol protocol = (AbstractProtocol) handler; - protocol.setMaxConnections(maxConnections); - } + factory.addConnectorCustomizers((connector) -> { + ProtocolHandler handler = connector.getProtocolHandler(); + if (handler instanceof AbstractProtocol) { + AbstractProtocol protocol = (AbstractProtocol) handler; + protocol.setMaxConnections(maxConnections); } - }); } private static void customizeConnectionTimeout( TomcatServletWebServerFactory factory, final int connectionTimeout) { - factory.addConnectorCustomizers(new TomcatConnectorCustomizer() { - - @Override - public void customize(Connector connector) { - ProtocolHandler handler = connector.getProtocolHandler(); - if (handler instanceof AbstractProtocol) { - AbstractProtocol protocol = (AbstractProtocol) handler; - protocol.setConnectionTimeout(connectionTimeout); - } + factory.addConnectorCustomizers((connector) -> { + ProtocolHandler handler = connector.getProtocolHandler(); + if (handler instanceof AbstractProtocol) { + AbstractProtocol protocol = (AbstractProtocol) handler; + protocol.setConnectionTimeout(connectionTimeout); } - }); } @@ -342,16 +321,11 @@ public class DefaultServletWebServerFactoryCustomizer @SuppressWarnings("rawtypes") private static void customizeMaxThreads(TomcatServletWebServerFactory factory, final int maxThreads) { - factory.addConnectorCustomizers(new TomcatConnectorCustomizer() { - @Override - public void customize(Connector connector) { - - ProtocolHandler handler = connector.getProtocolHandler(); - if (handler instanceof AbstractProtocol) { - AbstractProtocol protocol = (AbstractProtocol) handler; - protocol.setMaxThreads(maxThreads); - } - + factory.addConnectorCustomizers((connector) -> { + ProtocolHandler handler = connector.getProtocolHandler(); + if (handler instanceof AbstractProtocol) { + AbstractProtocol protocol = (AbstractProtocol) handler; + protocol.setMaxThreads(maxThreads); } }); } @@ -359,16 +333,11 @@ public class DefaultServletWebServerFactoryCustomizer @SuppressWarnings("rawtypes") private static void customizeMinThreads(TomcatServletWebServerFactory factory, final int minSpareThreads) { - factory.addConnectorCustomizers(new TomcatConnectorCustomizer() { - @Override - public void customize(Connector connector) { - - ProtocolHandler handler = connector.getProtocolHandler(); - if (handler instanceof AbstractProtocol) { - AbstractProtocol protocol = (AbstractProtocol) handler; - protocol.setMinSpareThreads(minSpareThreads); - } - + factory.addConnectorCustomizers((connector) -> { + ProtocolHandler handler = connector.getProtocolHandler(); + if (handler instanceof AbstractProtocol) { + AbstractProtocol protocol = (AbstractProtocol) handler; + protocol.setMinSpareThreads(minSpareThreads); } }); } @@ -376,30 +345,19 @@ public class DefaultServletWebServerFactoryCustomizer @SuppressWarnings("rawtypes") private static void customizeMaxHttpHeaderSize( TomcatServletWebServerFactory factory, final int maxHttpHeaderSize) { - factory.addConnectorCustomizers(new TomcatConnectorCustomizer() { - - @Override - public void customize(Connector connector) { - ProtocolHandler handler = connector.getProtocolHandler(); - if (handler instanceof AbstractHttp11Protocol) { - AbstractHttp11Protocol protocol = (AbstractHttp11Protocol) handler; - protocol.setMaxHttpHeaderSize(maxHttpHeaderSize); - } + factory.addConnectorCustomizers((connector) -> { + ProtocolHandler handler = connector.getProtocolHandler(); + if (handler instanceof AbstractHttp11Protocol) { + AbstractHttp11Protocol protocol = (AbstractHttp11Protocol) handler; + protocol.setMaxHttpHeaderSize(maxHttpHeaderSize); } - }); } private static void customizeMaxHttpPostSize( TomcatServletWebServerFactory factory, final int maxHttpPostSize) { - factory.addConnectorCustomizers(new TomcatConnectorCustomizer() { - - @Override - public void customize(Connector connector) { - connector.setMaxPostSize(maxHttpPostSize); - } - - }); + factory.addConnectorCustomizers( + (connector) -> connector.setMaxPostSize(maxHttpPostSize)); } private static void customizeAccessLog(ServerProperties.Tomcat tomcatProperties, @@ -422,14 +380,8 @@ public class DefaultServletWebServerFactoryCustomizer private static void customizeRedirectContextRoot( TomcatServletWebServerFactory factory, final boolean redirectContextRoot) { - factory.addContextCustomizers(new TomcatContextCustomizer() { - - @Override - public void customize(Context context) { - context.setMapperContextRootRedirectEnabled(redirectContextRoot); - } - - }); + factory.addContextCustomizers((context) -> context + .setMapperContextRootRedirectEnabled(redirectContextRoot)); } } @@ -482,39 +434,20 @@ public class DefaultServletWebServerFactoryCustomizer private static void customizeConnectionTimeout( UndertowServletWebServerFactory factory, final int connectionTimeout) { - factory.addBuilderCustomizers(new UndertowBuilderCustomizer() { - @Override - public void customize(Undertow.Builder builder) { - builder.setSocketOption(UndertowOptions.NO_REQUEST_TIMEOUT, - connectionTimeout); - } - }); + factory.addBuilderCustomizers((builder) -> builder.setSocketOption( + UndertowOptions.NO_REQUEST_TIMEOUT, connectionTimeout)); } private static void customizeMaxHttpHeaderSize( UndertowServletWebServerFactory factory, final int maxHttpHeaderSize) { - factory.addBuilderCustomizers(new UndertowBuilderCustomizer() { - - @Override - public void customize(Undertow.Builder builder) { - builder.setServerOption(UndertowOptions.MAX_HEADER_SIZE, - maxHttpHeaderSize); - } - - }); + factory.addBuilderCustomizers((builder) -> builder + .setServerOption(UndertowOptions.MAX_HEADER_SIZE, maxHttpHeaderSize)); } private static void customizeMaxHttpPostSize( UndertowServletWebServerFactory factory, final long maxHttpPostSize) { - factory.addBuilderCustomizers(new UndertowBuilderCustomizer() { - - @Override - public void customize(Undertow.Builder builder) { - builder.setServerOption(UndertowOptions.MAX_ENTITY_SIZE, - maxHttpPostSize); - } - - }); + factory.addBuilderCustomizers((builder -> builder + .setServerOption(UndertowOptions.MAX_ENTITY_SIZE, maxHttpPostSize))); } } @@ -551,19 +484,13 @@ public class DefaultServletWebServerFactoryCustomizer private static void customizeConnectionTimeout( JettyServletWebServerFactory factory, final int connectionTimeout) { - factory.addServerCustomizers(new JettyServerCustomizer() { - - @Override - public void customize(Server server) { - for (org.eclipse.jetty.server.Connector connector : server - .getConnectors()) { - if (connector instanceof AbstractConnector) { - ((AbstractConnector) connector) - .setIdleTimeout(connectionTimeout); - } + factory.addServerCustomizers((server) -> { + for (org.eclipse.jetty.server.Connector connector : server + .getConnectors()) { + if (connector instanceof AbstractConnector) { + ((AbstractConnector) connector).setIdleTimeout(connectionTimeout); } } - }); } diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/reactive/TomcatWebSocketReactiveWebServerCustomizer.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/reactive/TomcatWebSocketReactiveWebServerCustomizer.java index b1fe9465eb..f890609e67 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/reactive/TomcatWebSocketReactiveWebServerCustomizer.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/reactive/TomcatWebSocketReactiveWebServerCustomizer.java @@ -16,10 +16,8 @@ package org.springframework.boot.autoconfigure.websocket.reactive; -import org.apache.catalina.Context; import org.apache.tomcat.websocket.server.WsContextListener; -import org.springframework.boot.web.embedded.tomcat.TomcatContextCustomizer; import org.springframework.boot.web.embedded.tomcat.TomcatReactiveWebServerFactory; import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.core.Ordered; @@ -35,14 +33,8 @@ public class TomcatWebSocketReactiveWebServerCustomizer @Override public void customize(TomcatReactiveWebServerFactory factory) { - factory.addContextCustomizers(new TomcatContextCustomizer() { - - @Override - public void customize(Context context) { - context.addApplicationListener(WsContextListener.class.getName()); - } - - }); + factory.addContextCustomizers((context) -> context + .addApplicationListener(WsContextListener.class.getName())); } @Override diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java index 0c8804055b..5c2f94603a 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java @@ -249,15 +249,7 @@ public class AutoConfigurationImportSelectorTests { @Override protected List getAutoConfigurationImportListeners() { return Collections.singletonList( - new AutoConfigurationImportListener() { - - @Override - public void onAutoConfigurationImportEvent( - AutoConfigurationImportEvent event) { - TestAutoConfigurationImportSelector.this.lastEvent = event; - } - - }); + (event) -> this.lastEvent = event); } public AutoConfigurationImportEvent getLastEvent() { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunnerTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunnerTests.java index adad8fbb1a..af07d33a5c 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunnerTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherCommandLineRunnerTests.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. @@ -23,7 +23,6 @@ import org.springframework.batch.core.Job; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.JobParametersBuilder; import org.springframework.batch.core.Step; -import org.springframework.batch.core.StepContribution; import org.springframework.batch.core.configuration.annotation.BatchConfigurer; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; @@ -35,9 +34,7 @@ import org.springframework.batch.core.launch.support.RunIdIncrementer; import org.springframework.batch.core.launch.support.SimpleJobLauncher; import org.springframework.batch.core.repository.JobRepository; import org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean; -import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.batch.core.step.tasklet.Tasklet; -import org.springframework.batch.repeat.RepeatStatus; import org.springframework.batch.support.transaction.ResourcelessTransactionManager; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Configuration; @@ -80,13 +77,8 @@ public class JobLauncherCommandLineRunnerTests { PlatformTransactionManager transactionManager = this.context .getBean(PlatformTransactionManager.class); this.steps = new StepBuilderFactory(jobRepository, transactionManager); - this.step = this.steps.get("step").tasklet(new Tasklet() { - @Override - public RepeatStatus execute(StepContribution contribution, - ChunkContext chunkContext) throws Exception { - return null; - } - }).build(); + Tasklet tasklet = (contribution, chunkContext) -> null; + this.step = this.steps.get("step").tasklet(tasklet).build(); this.job = this.jobs.get("job").start(this.step).build(); this.jobExplorer = this.context.getBean(JobExplorer.class); this.runner = new JobLauncherCommandLineRunner(this.jobLauncher, @@ -115,13 +107,8 @@ public class JobLauncherCommandLineRunnerTests { @Test public void retryFailedExecution() throws Exception { this.job = this.jobs.get("job") - .start(this.steps.get("step").tasklet(new Tasklet() { - @Override - public RepeatStatus execute(StepContribution contribution, - ChunkContext chunkContext) throws Exception { - throw new RuntimeException("Planned"); - } - }).build()).incrementer(new RunIdIncrementer()).build(); + .start(this.steps.get("step").tasklet(throwingTasklet()).build()) + .incrementer(new RunIdIncrementer()).build(); this.runner.execute(this.job, new JobParameters()); this.runner.execute(this.job, new JobParameters()); assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(1); @@ -130,13 +117,8 @@ public class JobLauncherCommandLineRunnerTests { @Test public void retryFailedExecutionOnNonRestartableJob() throws Exception { this.job = this.jobs.get("job").preventRestart() - .start(this.steps.get("step").tasklet(new Tasklet() { - @Override - public RepeatStatus execute(StepContribution contribution, - ChunkContext chunkContext) throws Exception { - throw new RuntimeException("Planned"); - } - }).build()).incrementer(new RunIdIncrementer()).build(); + .start(this.steps.get("step").tasklet(throwingTasklet()).build()) + .incrementer(new RunIdIncrementer()).build(); this.runner.execute(this.job, new JobParameters()); this.runner.execute(this.job, new JobParameters()); // A failed job that is not restartable does not re-use the job params of @@ -147,13 +129,8 @@ public class JobLauncherCommandLineRunnerTests { @Test public void retryFailedExecutionWithNonIdentifyingParameters() throws Exception { this.job = this.jobs.get("job") - .start(this.steps.get("step").tasklet(new Tasklet() { - @Override - public RepeatStatus execute(StepContribution contribution, - ChunkContext chunkContext) throws Exception { - throw new RuntimeException("Planned"); - } - }).build()).incrementer(new RunIdIncrementer()).build(); + .start(this.steps.get("step").tasklet(throwingTasklet()).build()) + .incrementer(new RunIdIncrementer()).build(); JobParameters jobParameters = new JobParametersBuilder().addLong("id", 1L, false) .addLong("foo", 2L, false).toJobParameters(); this.runner.execute(this.job, jobParameters); @@ -161,6 +138,12 @@ public class JobLauncherCommandLineRunnerTests { assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(1); } + private Tasklet throwingTasklet() { + return (contribution, chunkContext) -> { + throw new RuntimeException("Planned"); + }; + } + @Configuration @EnableBatchProcessing protected static class BatchConfiguration implements BatchConfigurer { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java index 40c172b24a..9e75542dae 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java @@ -19,7 +19,6 @@ package org.springframework.boot.autoconfigure.cache; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; @@ -69,7 +68,6 @@ import org.springframework.cache.caffeine.CaffeineCacheManager; import org.springframework.cache.concurrent.ConcurrentMapCache; import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.cache.ehcache.EhCacheCacheManager; -import org.springframework.cache.interceptor.CacheOperationInvocationContext; import org.springframework.cache.interceptor.CacheResolver; import org.springframework.cache.jcache.JCacheCacheManager; import org.springframework.cache.support.NoOpCacheManager; @@ -965,16 +963,13 @@ public class CacheAutoConfigurationTests { @Bean JCacheManagerCustomizer myCustomizer() { - return new JCacheManagerCustomizer() { - @Override - public void customize(javax.cache.CacheManager cacheManager) { - MutableConfiguration config = new MutableConfiguration<>(); - config.setExpiryPolicyFactory( - CreatedExpiryPolicy.factoryOf(Duration.TEN_MINUTES)); - config.setStatisticsEnabled(true); - cacheManager.createCache("custom1", config); - cacheManager.destroyCache("bar"); - } + return (cacheManager) -> { + MutableConfiguration config = new MutableConfiguration<>(); + config.setExpiryPolicyFactory( + CreatedExpiryPolicy.factoryOf(Duration.TEN_MINUTES)); + config.setStatisticsEnabled(true); + cacheManager.createCache("custom1", config); + cacheManager.destroyCache("bar"); }; } @@ -1053,15 +1048,7 @@ public class CacheAutoConfigurationTests { @Bean // The @Bean annotation is important, see CachingConfigurerSupport Javadoc public CacheResolver cacheResolver() { - return new CacheResolver() { - - @Override - public Collection resolveCaches( - CacheOperationInvocationContext context) { - return Collections.singleton(mock(Cache.class)); - } - - }; + return (context) -> Collections.singleton(mock(Cache.class)); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/support/MockCachingProvider.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/support/MockCachingProvider.java index 63d9b500de..d303f59a5d 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/support/MockCachingProvider.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/support/MockCachingProvider.java @@ -27,9 +27,6 @@ import javax.cache.configuration.Configuration; import javax.cache.configuration.OptionalFeature; import javax.cache.spi.CachingProvider; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; @@ -52,24 +49,17 @@ public class MockCachingProvider implements CachingProvider { given(cacheManager.getClassLoader()).willReturn(classLoader); final Map caches = new HashMap<>(); given(cacheManager.getCacheNames()).willReturn(caches.keySet()); - given(cacheManager.getCache(anyString())).willAnswer(new Answer() { - @Override - public Cache answer(InvocationOnMock invocationOnMock) throws Throwable { - String cacheName = (String) invocationOnMock.getArguments()[0]; - return caches.get(cacheName); - } + given(cacheManager.getCache(anyString())).willAnswer((invocation) -> { + String cacheName = (String) invocation.getArguments()[0]; + return caches.get(cacheName); }); given(cacheManager.createCache(anyString(), any(Configuration.class))) - .will(new Answer() { - @Override - public Cache answer(InvocationOnMock invocationOnMock) - throws Throwable { - String cacheName = (String) invocationOnMock.getArguments()[0]; - Cache cache = mock(Cache.class); - given(cache.getName()).willReturn(cacheName); - caches.put(cacheName, cache); - return cache; - } + .will((invocation) -> { + String cacheName = (String) invocation.getArguments()[0]; + Cache cache = mock(Cache.class); + given(cache.getName()).willReturn(cacheName); + caches.put(cacheName, cache); + return cache; }); return cacheManager; } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java index 54cad5ae89..9294c3da26 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java @@ -143,12 +143,7 @@ public class CassandraAutoConfigurationTests { @Bean public ClusterBuilderCustomizer customizer() { - return new ClusterBuilderCustomizer() { - @Override - public void customize(Cluster.Builder clusterBuilder) { - clusterBuilder.withClusterName("overridden-name"); - } - }; + return (clusterBuilder) -> clusterBuilder.withClusterName("overridden-name"); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfigurationTests.java index 1296709c35..ab4936b855 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/jest/JestAutoConfigurationTests.java @@ -24,7 +24,6 @@ import com.google.gson.Gson; import io.searchbox.action.Action; import io.searchbox.client.JestClient; import io.searchbox.client.JestResult; -import io.searchbox.client.config.HttpClientConfig; import io.searchbox.client.http.JestHttpClient; import io.searchbox.core.Index; import io.searchbox.core.Search; @@ -183,14 +182,7 @@ public class JestAutoConfigurationTests { @Bean public HttpClientConfigBuilderCustomizer customizer() { - return new HttpClientConfigBuilderCustomizer() { - - @Override - public void customize(HttpClientConfig.Builder builder) { - builder.gson(BuilderCustomizer.this.gson); - } - - }; + return (builder) -> builder.gson(BuilderCustomizer.this.gson); } Gson getGson() { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java index 41ffc0fcbd..9dc7dfbac2 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java @@ -533,13 +533,7 @@ public class JacksonAutoConfigurationTests { @Bean public Jackson2ObjectMapperBuilderCustomizer customDateFormat() { - return new Jackson2ObjectMapperBuilderCustomizer() { - @Override - public void customize( - Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder) { - jackson2ObjectMapperBuilder.dateFormat(new MyDateFormat()); - } - }; + return (builder) -> builder.dateFormat(new MyDateFormat()); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerTests.java index 9e3c49d916..0468eafaa3 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerTests.java @@ -350,14 +350,8 @@ public class DataSourceInitializerTests { @Override public Resource[] getResources(String locationPattern) throws IOException { Resource[] resources = this.resolver.getResources(locationPattern); - Arrays.sort(resources, new Comparator() { - - @Override - public int compare(Resource r1, Resource r2) { - return r2.getFilename().compareTo(r1.getFilename()); - } - - }); + Arrays.sort(resources, + Comparator.comparing(Resource::getFilename).reversed()); return resources; } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/AbstractDataSourcePoolMetadataTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/AbstractDataSourcePoolMetadataTests.java index 934d8150de..4e53224ef3 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/AbstractDataSourcePoolMetadataTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/metadata/AbstractDataSourcePoolMetadataTests.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. @@ -16,13 +16,9 @@ package org.springframework.boot.autoconfigure.jdbc.metadata; -import java.sql.Connection; -import java.sql.SQLException; - import org.junit.Test; import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; -import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.ConnectionCallback; import org.springframework.jdbc.core.JdbcTemplate; @@ -57,13 +53,7 @@ public abstract class AbstractDataSourcePoolMetadataTests() { - @Override - public Void doInConnection(Connection connection) - throws SQLException, DataAccessException { - return null; - } - }); + jdbcTemplate.execute((ConnectionCallback) (connection) -> null); assertThat(getDataSourceMetadata().getActive()).isEqualTo(Integer.valueOf(0)); assertThat(getDataSourceMetadata().getUsage()).isEqualTo(Float.valueOf(0)); } @@ -72,16 +62,10 @@ public abstract class AbstractDataSourcePoolMetadataTests() { - @Override - public Void doInConnection(Connection connection) - throws SQLException, DataAccessException { - assertThat(getDataSourceMetadata().getActive()) - .isEqualTo(Integer.valueOf(1)); - assertThat(getDataSourceMetadata().getUsage()) - .isEqualTo(Float.valueOf(0.5F)); - return null; - } + jdbcTemplate.execute((ConnectionCallback) (connection) -> { + assertThat(getDataSourceMetadata().getActive()).isEqualTo(Integer.valueOf(1)); + assertThat(getDataSourceMetadata().getUsage()).isEqualTo(Float.valueOf(0.5F)); + return null; }); } @@ -89,25 +73,13 @@ public abstract class AbstractDataSourcePoolMetadataTests() { - - @Override - public Void doInConnection(Connection connection) - throws SQLException, DataAccessException { - jdbcTemplate.execute(new ConnectionCallback() { - - @Override - public Void doInConnection(Connection connection) - throws SQLException, DataAccessException { - assertThat(getDataSourceMetadata().getActive()).isEqualTo(2); - assertThat(getDataSourceMetadata().getUsage()).isEqualTo(1.0f); - return null; - } - - }); + jdbcTemplate.execute((ConnectionCallback) (connection) -> { + jdbcTemplate.execute((ConnectionCallback) connection1 -> { + assertThat(getDataSourceMetadata().getActive()).isEqualTo(2); + assertThat(getDataSourceMetadata().getUsage()).isEqualTo(1.0f); return null; - } - + }); + return null; }); } 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 40a4703ada..00984b43b2 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 @@ -23,7 +23,6 @@ import java.util.UUID; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Message; -import javax.jms.Session; import javax.jms.TextMessage; import org.apache.activemq.artemis.api.core.TransportConfiguration; @@ -336,25 +335,22 @@ public class ArtemisAutoConfigurationTests { public void checkDestination(final String name, final boolean pubSub, final boolean shouldExist) { - this.jmsTemplate.execute(new SessionCallback() { - @Override - public Void doInJms(Session session) throws JMSException { - try { - Destination destination = DestinationChecker.this.destinationResolver - .resolveDestinationName(session, name, pubSub); - if (!shouldExist) { - throw new IllegalStateException("Destination '" + name - + "' was not expected but got " + destination); - } + this.jmsTemplate.execute((SessionCallback) (session) -> { + try { + Destination destination = this.destinationResolver + .resolveDestinationName(session, name, pubSub); + if (!shouldExist) { + throw new IllegalStateException("Destination '" + name + + "' was not expected but got " + destination); } - catch (JMSException e) { - if (shouldExist) { - throw new IllegalStateException("Destination '" + name - + "' was expected but got " + e.getMessage()); - } - } - return null; } + catch (JMSException ex) { + if (shouldExist) { + throw new IllegalStateException("Destination '" + name + + "' was expected but got " + ex.getMessage()); + } + } + return null; }); } @@ -408,13 +404,9 @@ public class ArtemisAutoConfigurationTests { @Bean public ArtemisConfigurationCustomizer myArtemisCustomize() { - return new ArtemisConfigurationCustomizer() { - @Override - public void customize( - org.apache.activemq.artemis.core.config.Configuration configuration) { - configuration.setClusterPassword("Foobar"); - configuration.setName("customFooBar"); - } + return (configuration) -> { + configuration.setClusterPassword("Foobar"); + configuration.setName("customFooBar"); }; } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/AutoConfigurationReportLoggingInitializerTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/AutoConfigurationReportLoggingInitializerTests.java index bbd09ee9b0..9f80fbb671 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/AutoConfigurationReportLoggingInitializerTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/AutoConfigurationReportLoggingInitializerTests.java @@ -62,9 +62,8 @@ public class AutoConfigurationReportLoggingInitializerTests { this.initializer.initialize(context); context.register(Config.class); context.refresh(); - withDebugLogging(() -> { - this.initializer.onApplicationEvent(new ContextRefreshedEvent(context)); - }); + withDebugLogging(() -> this.initializer + .onApplicationEvent(new ContextRefreshedEvent(context))); assertThat(this.outputCapture.toString()).contains("AUTO-CONFIGURATION REPORT"); } @@ -78,10 +77,9 @@ public class AutoConfigurationReportLoggingInitializerTests { fail("Did not error"); } catch (Exception ex) { - withDebugLogging(() -> { - this.initializer.onApplicationEvent(new ApplicationFailedEvent( - new SpringApplication(), new String[0], context, ex)); - }); + withDebugLogging( + () -> this.initializer.onApplicationEvent(new ApplicationFailedEvent( + new SpringApplication(), new String[0], context, ex))); } assertThat(this.outputCapture.toString()).contains("AUTO-CONFIGURATION REPORT"); } @@ -112,9 +110,8 @@ public class AutoConfigurationReportLoggingInitializerTests { ConditionEvaluationReport.get(context.getBeanFactory()) .recordExclusions(Arrays.asList("com.foo.Bar")); context.refresh(); - withDebugLogging(() -> { - this.initializer.onApplicationEvent(new ContextRefreshedEvent(context)); - }); + withDebugLogging(() -> this.initializer + .onApplicationEvent(new ContextRefreshedEvent(context))); assertThat(this.outputCapture.toString()) .contains("not a servlet web application (OnWebApplicationCondition)"); } 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 fd27e1d16c..6c5360a0a4 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 @@ -50,7 +50,6 @@ import org.springframework.security.config.annotation.authentication.configurers import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.UserDetailsService; @@ -407,14 +406,8 @@ public class SecurityAutoConfigurationTests { @Bean public AuthenticationManager myAuthenticationManager() { - this.authenticationManager = new AuthenticationManager() { - - @Override - public Authentication authenticate(Authentication authentication) - throws AuthenticationException { - return new TestingAuthenticationToken("foo", "bar"); - } - }; + this.authenticationManager = ( + authentication) -> new TestingAuthenticationToken("foo", "bar"); return this.authenticationManager; } @@ -446,14 +439,8 @@ public class SecurityAutoConfigurationTests { @Override protected void configure(HttpSecurity http) throws Exception { - this.authenticationManager = new AuthenticationManager() { - @Override - public Authentication authenticate(Authentication authentication) - throws AuthenticationException { - return WorkaroundSecurityCustomizer.this.builder.getOrBuild() - .authenticate(authentication); - } - }; + this.authenticationManager = (authentication) -> this.builder.getOrBuild() + .authenticate(authentication); } } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerTokenServicesConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerTokenServicesConfigurationTests.java index e2cf69190d..08f6af383b 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerTokenServicesConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerTokenServicesConfigurationTests.java @@ -16,10 +16,6 @@ package org.springframework.boot.autoconfigure.security.oauth2.resource; -import java.io.IOException; -import java.util.List; -import java.util.Map; - import org.junit.After; import org.junit.Rule; import org.junit.Test; @@ -45,14 +41,9 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.StandardEnvironment; -import org.springframework.http.HttpRequest; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.client.ClientHttpRequestExecution; -import org.springframework.http.client.ClientHttpRequestInterceptor; -import org.springframework.http.client.ClientHttpResponse; import org.springframework.mock.http.client.MockClientHttpResponse; -import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.oauth2.client.OAuth2RestTemplate; import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails; @@ -299,16 +290,8 @@ public class ResourceServerTokenServicesConfigurationTests { @Bean AuthoritiesExtractor authoritiesExtractor() { - return new AuthoritiesExtractor() { - - @Override - public List extractAuthorities( - Map map) { - return AuthorityUtils - .commaSeparatedStringToAuthorityList("ROLE_ADMIN"); - } - - }; + return (map) -> AuthorityUtils + .commaSeparatedStringToAuthorityList("ROLE_ADMIN"); } } @@ -318,14 +301,7 @@ public class ResourceServerTokenServicesConfigurationTests { @Bean PrincipalExtractor principalExtractor() { - return new PrincipalExtractor() { - - @Override - public Object extractPrincipal(Map map) { - return "boot"; - } - - }; + return (map) -> "boot"; } } @@ -372,15 +348,8 @@ public class ResourceServerTokenServicesConfigurationTests { @Override public void customize(OAuth2RestTemplate template) { - template.getInterceptors().add(new ClientHttpRequestInterceptor() { - - @Override - public ClientHttpResponse intercept(HttpRequest request, byte[] body, - ClientHttpRequestExecution execution) throws IOException { - return execution.execute(request, body); - } - - }); + template.getInterceptors() + .add((request, body, execution) -> execution.execute(request, body)); } } @@ -434,18 +403,12 @@ public class ResourceServerTokenServicesConfigurationTests { @Override public void customize(RestTemplate template) { - template.getInterceptors().add(new ClientHttpRequestInterceptor() { - - @Override - public ClientHttpResponse intercept(HttpRequest request, byte[] body, - ClientHttpRequestExecution execution) throws IOException { - String payload = "{\"value\":\"FOO\"}"; - MockClientHttpResponse response = new MockClientHttpResponse( - payload.getBytes(), HttpStatus.OK); - response.getHeaders().setContentType(MediaType.APPLICATION_JSON); - return response; - } - + template.getInterceptors().add((request, body, execution) -> { + String payload = "{\"value\":\"FOO\"}"; + MockClientHttpResponse response = new MockClientHttpResponse( + payload.getBytes(), HttpStatus.OK); + response.getHeaders().setContentType(MediaType.APPLICATION_JSON); + return response; }); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfigurationTests.java index f3d4bd73d0..b7749e088b 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfigurationTests.java @@ -154,13 +154,8 @@ public class RestTemplateAutoConfigurationTests { } private void breakBuilderOnNextCall(RestTemplateBuilder builder) { - builder.additionalCustomizers(new RestTemplateCustomizer() { - - @Override - public void customize(RestTemplate restTemplate) { - throw new IllegalStateException(); - } - + builder.additionalCustomizers((restTemplate) -> { + throw new IllegalStateException(); }); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/MockServletWebServerFactory.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/MockServletWebServerFactory.java index b6df576036..dc3a777d57 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/MockServletWebServerFactory.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/MockServletWebServerFactory.java @@ -69,7 +69,7 @@ public class MockServletWebServerFactory extends AbstractServletWebServerFactory public MockServletWebServer(ServletContextInitializer[] initializers, int port) { super(Arrays.stream(initializers) - .map((i) -> (Initializer) (s) -> i.onStartup(s)) + .map((initializer) -> (Initializer) initializer::onStartup) .toArray(Initializer[]::new), port); } 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 3d1dc546ae..a774cf59f9 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 @@ -18,7 +18,6 @@ package org.springframework.boot.cli.infrastructure; import java.io.BufferedReader; import java.io.File; -import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; @@ -71,14 +70,8 @@ public final class CommandLineInvoker { private File findLaunchScript() throws IOException { File unpacked = new File("target/unpacked-cli"); if (!unpacked.isDirectory()) { - File zip = new File("target").listFiles(new FileFilter() { - - @Override - public boolean accept(File pathname) { - return pathname.getName().endsWith("-bin.zip"); - } - - })[0]; + File zip = new File("target") + .listFiles((pathname) -> pathname.getName().endsWith("-bin.zip"))[0]; try (ZipInputStream input = new ZipInputStream(new FileInputStream(zip))) { ZipEntry entry; while ((entry = input.getNextEntry()) != null) { 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 c37709e6c1..5cd08e09c6 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 @@ -57,9 +57,7 @@ import org.springframework.boot.cli.compiler.RepositoryConfigurationFactory; import org.springframework.boot.cli.compiler.grape.RepositoryConfiguration; import org.springframework.boot.loader.tools.JarWriter; import org.springframework.boot.loader.tools.Layout; -import org.springframework.boot.loader.tools.Libraries; import org.springframework.boot.loader.tools.Library; -import org.springframework.boot.loader.tools.LibraryCallback; import org.springframework.boot.loader.tools.LibraryScope; import org.springframework.boot.loader.tools.Repackager; import org.springframework.core.io.Resource; @@ -198,13 +196,9 @@ abstract class ArchiveCommand extends OptionParsingCommand { libraries.addAll(createLibraries(dependencies)); Repackager repackager = new Repackager(file); repackager.setMainClass(PackagedSpringApplicationLauncher.class.getName()); - repackager.repackage(new Libraries() { - - @Override - public void doWithLibraries(LibraryCallback callback) throws IOException { - for (Library library : libraries) { - callback.library(library); - } + repackager.repackage((callback) -> { + for (Library library : libraries) { + callback.library(library); } }); } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGenerator.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGenerator.java index 15a422f47d..d31ea7f87f 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGenerator.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGenerator.java @@ -94,11 +94,7 @@ class ServiceCapabilitiesReportGenerator { private List getSortedDependencies(InitializrServiceMetadata metadata) { ArrayList dependencies = new ArrayList<>(metadata.getDependencies()); - dependencies.sort(new Comparator() { - @Override public int compare(Dependency o1, Dependency o2) { - return o1.getId().compareTo(o2.getId()); - } - }); + dependencies.sort(Comparator.comparing(Dependency::getId)); return dependencies; } @@ -107,15 +103,7 @@ class ServiceCapabilitiesReportGenerator { report.append("Available project types:" + NEW_LINE); report.append("------------------------" + NEW_LINE); SortedSet> entries = new TreeSet<>( - new Comparator>() { - - @Override - public int compare(Entry o1, - Entry o2) { - return o1.getKey().compareTo(o2.getKey()); - } - - }); + Comparator.comparing(Entry::getKey)); entries.addAll(metadata.getProjectTypes().entrySet()); for (Entry entry : entries) { ProjectType type = entry.getValue(); diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java index b3f6c004c1..677b8ee7a8 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java @@ -130,17 +130,10 @@ public class OptionHandler { @Override public String format(Map options) { - Comparator comparator = new Comparator() { - @Override - public int compare(OptionDescriptor first, OptionDescriptor second) { - return first.options().iterator().next() - .compareTo(second.options().iterator().next()); - } - }; - + Comparator comparator = (first, second) -> first.options() + .iterator().next().compareTo(second.options().iterator().next()); Set sorted = new TreeSet<>(comparator); sorted.addAll(options.values()); - for (OptionDescriptor descriptor : sorted) { if (!descriptor.representsNonOptions()) { this.help.add(new OptionHelpAdapter(descriptor)); diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/Shell.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/Shell.java index b2745217e5..1edac65ab4 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/Shell.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/Shell.java @@ -119,12 +119,7 @@ public class Shell { } private void attachSignalHandler() { - SignalUtils.attachSignalHandler(new Runnable() { - @Override - public void run() { - handleSigInt(); - } - }); + SignalUtils.attachSignalHandler(this::handleSigInt); } /** 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 b1e5be1dab..9e0004f161 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 @@ -122,23 +122,23 @@ public class ExtendedGroovyClassLoader extends GroovyClassLoader { @Override public ClassCollector createCollector(CompilationUnit unit, SourceUnit su) { - InnerLoader loader = AccessController - .doPrivileged(new PrivilegedAction() { - @Override - public InnerLoader run() { - return new InnerLoader(ExtendedGroovyClassLoader.this) { - // Don't return URLs from the inner loader so that Tomcat only - // searches the parent. Fixes 'TLD skipped' issues - @Override - public URL[] getURLs() { - return NO_URLS; - } - }; - } - }); + InnerLoader loader = AccessController.doPrivileged(getInnerLoader()); return new ExtendedClassCollector(loader, unit, su); } + private PrivilegedAction getInnerLoader() { + return () -> new InnerLoader(ExtendedGroovyClassLoader.this) { + + // Don't return URLs from the inner loader so that Tomcat only + // searches the parent. Fixes 'TLD skipped' issues + @Override + public URL[] getURLs() { + return NO_URLS; + } + + }; + } + public CompilerConfiguration getConfiguration() { return this.configuration; } diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngine.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngine.java index 248c1b6fa9..181a97d303 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngine.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngine.java @@ -100,19 +100,11 @@ public class AetherGrapeEngine implements GrapeEngine { || Boolean.getBoolean("groovy.grape.report.downloads")) { return new DetailedProgressReporter(session, System.out); } - else if ("none".equals(progressReporter)) { - return new ProgressReporter() { - - @Override - public void finished() { - - } - + if ("none".equals(progressReporter)) { + return () -> { }; } - else { - return new SummaryProgressReporter(session, System.out); - } + return new SummaryProgressReporter(session, System.out); } @Override diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/CliTester.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/CliTester.java index f25765d8b7..bde1ec0cd0 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/CliTester.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/CliTester.java @@ -26,7 +26,6 @@ import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; @@ -105,25 +104,22 @@ public class CliTester implements TestRule { String... args) { clearUrlHandler(); final String[] sources = getSources(args); - return Executors.newSingleThreadExecutor().submit(new Callable() { - @Override - public T call() throws Exception { - ClassLoader loader = Thread.currentThread().getContextClassLoader(); - System.setProperty("server.port", "0"); - System.setProperty("spring.application.class.name", - "org.springframework.boot.cli.CliTesterSpringApplication"); - System.setProperty("portfile", - new File("target/server.port").getAbsolutePath()); - try { - command.run(sources); - return command; - } - finally { - System.clearProperty("server.port"); - System.clearProperty("spring.application.class.name"); - System.clearProperty("portfile"); - Thread.currentThread().setContextClassLoader(loader); - } + return Executors.newSingleThreadExecutor().submit(() -> { + ClassLoader loader = Thread.currentThread().getContextClassLoader(); + System.setProperty("server.port", "0"); + System.setProperty("spring.application.class.name", + "org.springframework.boot.cli.CliTesterSpringApplication"); + System.setProperty("portfile", + new File("target/server.port").getAbsolutePath()); + try { + command.run(sources); + return command; + } + finally { + System.clearProperty("server.port"); + System.clearProperty("spring.application.class.name"); + System.clearProperty("portfile"); + Thread.currentThread().setContextClassLoader(loader); } }); } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactoryTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactoryTests.java index dc1db57cd9..dae3305c8e 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactoryTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/RepositoryConfigurationFactoryTests.java @@ -36,69 +36,53 @@ public class RepositoryConfigurationFactoryTests { @Test public void defaultRepositories() { - SystemProperties.doWithSystemProperties(new Runnable() { - @Override - public void run() { - List repositoryConfiguration = RepositoryConfigurationFactory - .createDefaultRepositoryConfiguration(); - assertRepositoryConfiguration(repositoryConfiguration, "central", "local", - "spring-snapshot", "spring-milestone"); - } + SystemProperties.doWithSystemProperties(() -> { + List repositoryConfiguration = RepositoryConfigurationFactory + .createDefaultRepositoryConfiguration(); + assertRepositoryConfiguration(repositoryConfiguration, "central", "local", + "spring-snapshot", "spring-milestone"); }, "user.home:src/test/resources/maven-settings/basic"); } @Test public void snapshotRepositoriesDisabled() { - SystemProperties.doWithSystemProperties(new Runnable() { - @Override - public void run() { - List repositoryConfiguration = RepositoryConfigurationFactory - .createDefaultRepositoryConfiguration(); - assertRepositoryConfiguration(repositoryConfiguration, "central", - "local"); - } + SystemProperties.doWithSystemProperties(() -> { + List repositoryConfiguration = RepositoryConfigurationFactory + .createDefaultRepositoryConfiguration(); + assertRepositoryConfiguration(repositoryConfiguration, "central", "local"); }, "user.home:src/test/resources/maven-settings/basic", "disableSpringSnapshotRepos:true"); } @Test public void activeByDefaultProfileRepositories() { - SystemProperties.doWithSystemProperties(new Runnable() { - @Override - public void run() { - List repositoryConfiguration = RepositoryConfigurationFactory - .createDefaultRepositoryConfiguration(); - assertRepositoryConfiguration(repositoryConfiguration, "central", "local", - "spring-snapshot", "spring-milestone", "active-by-default"); - } + SystemProperties.doWithSystemProperties(() -> { + List repositoryConfiguration = RepositoryConfigurationFactory + .createDefaultRepositoryConfiguration(); + assertRepositoryConfiguration(repositoryConfiguration, "central", "local", + "spring-snapshot", "spring-milestone", "active-by-default"); }, "user.home:src/test/resources/maven-settings/active-profile-repositories"); } @Test public void activeByPropertyProfileRepositories() { - SystemProperties.doWithSystemProperties(new Runnable() { - @Override - public void run() { - List repositoryConfiguration = RepositoryConfigurationFactory - .createDefaultRepositoryConfiguration(); - assertRepositoryConfiguration(repositoryConfiguration, "central", "local", - "spring-snapshot", "spring-milestone", "active-by-property"); - } + SystemProperties.doWithSystemProperties(() -> { + List repositoryConfiguration = RepositoryConfigurationFactory + .createDefaultRepositoryConfiguration(); + assertRepositoryConfiguration(repositoryConfiguration, "central", "local", + "spring-snapshot", "spring-milestone", "active-by-property"); }, "user.home:src/test/resources/maven-settings/active-profile-repositories", "foo:bar"); } @Test public void interpolationProfileRepositories() { - SystemProperties.doWithSystemProperties(new Runnable() { - @Override - public void run() { - List repositoryConfiguration = RepositoryConfigurationFactory - .createDefaultRepositoryConfiguration(); - assertRepositoryConfiguration(repositoryConfiguration, "central", "local", - "spring-snapshot", "spring-milestone", "interpolate-releases", - "interpolate-snapshots"); - } + SystemProperties.doWithSystemProperties(() -> { + List repositoryConfiguration = RepositoryConfigurationFactory + .createDefaultRepositoryConfiguration(); + assertRepositoryConfiguration(repositoryConfiguration, "central", "local", + "spring-snapshot", "spring-milestone", "interpolate-releases", + "interpolate-snapshots"); }, "user.home:src/test/resources/maven-settings/active-profile-repositories", "interpolate:true"); } diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineTests.java index 543102fed2..171b034f6f 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/AetherGrapeEngineTests.java @@ -72,54 +72,32 @@ public class AetherGrapeEngineTests { @Test public void proxySelector() { - doWithCustomUserHome(new Runnable() { - - @Override - public void run() { - AetherGrapeEngine grapeEngine = createGrapeEngine(); - - DefaultRepositorySystemSession session = (DefaultRepositorySystemSession) ReflectionTestUtils - .getField(grapeEngine, "session"); - - assertThat(session.getProxySelector() instanceof CompositeProxySelector) - .isTrue(); - } + doWithCustomUserHome(() -> { + AetherGrapeEngine grapeEngine = createGrapeEngine(); + DefaultRepositorySystemSession session = (DefaultRepositorySystemSession) ReflectionTestUtils + .getField(grapeEngine, "session"); + assertThat(session.getProxySelector() instanceof CompositeProxySelector) + .isTrue(); }); } @Test public void repositoryMirrors() { - doWithCustomUserHome(new Runnable() { - - @SuppressWarnings("unchecked") - @Override - public void run() { - AetherGrapeEngine grapeEngine = createGrapeEngine(); - - List repositories = (List) ReflectionTestUtils - .getField(grapeEngine, "repositories"); - assertThat(repositories).hasSize(1); - assertThat(repositories.get(0).getId()).isEqualTo("central-mirror"); - } + doWithCustomUserHome(() -> { + List repositories = getRepositories(); + assertThat(repositories).hasSize(1); + assertThat(repositories.get(0).getId()).isEqualTo("central-mirror"); }); } @Test public void repositoryAuthentication() { - doWithCustomUserHome(new Runnable() { - - @SuppressWarnings("unchecked") - @Override - public void run() { - AetherGrapeEngine grapeEngine = createGrapeEngine(); - - List repositories = (List) ReflectionTestUtils - .getField(grapeEngine, "repositories"); - assertThat(repositories).hasSize(1); - Authentication authentication = repositories.get(0).getAuthentication(); - assertThat(authentication).isNotNull(); - } + doWithCustomUserHome(() -> { + List repositories = getRepositories(); + assertThat(repositories).hasSize(1); + Authentication authentication = repositories.get(0).getAuthentication(); + assertThat(authentication).isNotNull(); }); } @@ -216,6 +194,13 @@ public class AetherGrapeEngineTests { assertThat(urls[0].toExternalForm().endsWith("-sources.jar")).isTrue(); } + @SuppressWarnings("unchecked") + private List getRepositories() { + AetherGrapeEngine grapeEngine = createGrapeEngine(); + return (List) ReflectionTestUtils.getField(grapeEngine, + "repositories"); + } + private Map createDependency(String group, String module, String version) { Map dependency = new HashMap<>(); diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfigurationTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfigurationTests.java index 7bfb5cc96a..3a88bae645 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfigurationTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/GrapeRootRepositorySystemSessionAutoConfigurationTests.java @@ -59,21 +59,12 @@ public class GrapeRootRepositorySystemSessionAutoConfigurationTests { @Test public void noLocalRepositoryWhenNoGrapeRoot() { given(this.repositorySystem.newLocalRepositoryManager(eq(this.session), - any(LocalRepository.class))) - .willAnswer(new Answer() { - - @Override - public LocalRepositoryManager answer( - InvocationOnMock invocation) throws Throwable { - LocalRepository localRepository = invocation - .getArgument(1); - return new SimpleLocalRepositoryManagerFactory() - .newInstance( - GrapeRootRepositorySystemSessionAutoConfigurationTests.this.session, - localRepository); - } - - }); + any(LocalRepository.class))).willAnswer((invocation) -> { + LocalRepository localRepository = invocation.getArgument(1); + return new SimpleLocalRepositoryManagerFactory().newInstance( + GrapeRootRepositorySystemSessionAutoConfigurationTests.this.session, + localRepository); + }); new GrapeRootRepositorySystemSessionAutoConfiguration().apply(this.session, this.repositorySystem); verify(this.repositorySystem, times(0)) diff --git a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfigurationTests.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfigurationTests.java index 9edc8ae347..aac591ce6a 100644 --- a/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfigurationTests.java +++ b/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/grape/SettingsXmlRepositorySystemSessionAutoConfigurationTests.java @@ -26,7 +26,6 @@ import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory; import org.eclipse.aether.repository.Authentication; import org.eclipse.aether.repository.AuthenticationContext; import org.eclipse.aether.repository.LocalRepository; -import org.eclipse.aether.repository.LocalRepositoryManager; import org.eclipse.aether.repository.Proxy; import org.eclipse.aether.repository.RemoteRepository; import org.junit.Before; @@ -35,8 +34,6 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.springframework.boot.cli.testutil.SystemProperties; @@ -78,28 +75,17 @@ public class SettingsXmlRepositorySystemSessionAutoConfigurationTests { final DefaultRepositorySystemSession session = MavenRepositorySystemUtils .newSession(); given(this.repositorySystem.newLocalRepositoryManager(eq(session), - any(LocalRepository.class))) - .willAnswer(new Answer() { - - @Override - public LocalRepositoryManager answer( - InvocationOnMock invocation) throws Throwable { - LocalRepository localRepository = invocation - .getArgument(1); - return new SimpleLocalRepositoryManagerFactory() - .newInstance(session, localRepository); - } - }); - - SystemProperties.doWithSystemProperties(new Runnable() { - @Override - public void run() { - new SettingsXmlRepositorySystemSessionAutoConfiguration().apply(session, - SettingsXmlRepositorySystemSessionAutoConfigurationTests.this.repositorySystem); - } - }, "user.home:src/test/resources/maven-settings/property-interpolation", + any(LocalRepository.class))).willAnswer((invocation) -> { + LocalRepository localRepository = invocation.getArgument(1); + return new SimpleLocalRepositoryManagerFactory().newInstance(session, + localRepository); + }); + SystemProperties.doWithSystemProperties( + () -> new SettingsXmlRepositorySystemSessionAutoConfiguration().apply( + session, + SettingsXmlRepositorySystemSessionAutoConfigurationTests.this.repositorySystem), + "user.home:src/test/resources/maven-settings/property-interpolation", "foo:bar"); - assertThat(session.getLocalRepository().getBasedir().getAbsolutePath()) .endsWith(File.separatorChar + "bar" + File.separatorChar + "repository"); } @@ -107,14 +93,11 @@ public class SettingsXmlRepositorySystemSessionAutoConfigurationTests { private void assertSessionCustomization(String userHome) { final DefaultRepositorySystemSession session = MavenRepositorySystemUtils .newSession(); - SystemProperties.doWithSystemProperties(new Runnable() { - @Override - public void run() { - new SettingsXmlRepositorySystemSessionAutoConfiguration().apply(session, - SettingsXmlRepositorySystemSessionAutoConfigurationTests.this.repositorySystem); - } - }, "user.home:" + userHome); - + SystemProperties.doWithSystemProperties( + () -> new SettingsXmlRepositorySystemSessionAutoConfiguration().apply( + session, + SettingsXmlRepositorySystemSessionAutoConfigurationTests.this.repositorySystem), + "user.home:" + userHome); RemoteRepository repository = new RemoteRepository.Builder("my-server", "default", "http://maven.example.com").build(); assertMirrorSelectorConfiguration(session, repository); diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfiguration.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfiguration.java index f5bdc16b18..e52799806d 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfiguration.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfiguration.java @@ -136,14 +136,7 @@ public class LocalDevToolsAutoConfiguration { @Bean public FileSystemWatcherFactory fileSystemWatcherFactory() { - return new FileSystemWatcherFactory() { - - @Override - public FileSystemWatcher getFileSystemWatcher() { - return newFileSystemWatcher(); - } - - }; + return this::newFileSystemWatcher; } private FileSystemWatcher newFileSystemWatcher() { 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 d14fc81aad..d3a5e60af4 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 @@ -89,14 +89,7 @@ public class LiveReloadServer { * @param port the listen port */ public LiveReloadServer(int port) { - this(port, new ThreadFactory() { - - @Override - public Thread newThread(Runnable runnable) { - return new Thread(runnable); - } - - }); + this(port, Thread::new); } /** @@ -121,14 +114,7 @@ public class LiveReloadServer { logger.debug("Starting live reload server on port " + this.port); this.serverSocket = new ServerSocket(this.port); int localPort = this.serverSocket.getLocalPort(); - this.listenThread = this.threadFactory.newThread(new Runnable() { - - @Override - public void run() { - acceptConnections(); - } - - }); + this.listenThread = this.threadFactory.newThread(this::acceptConnections); this.listenThread.setDaemon(true); this.listenThread.setName("Live Reload Server"); this.listenThread.start(); diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/RemoteClientConfiguration.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/RemoteClientConfiguration.java index e914e47b36..81d1e92b51 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/RemoteClientConfiguration.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/RemoteClientConfiguration.java @@ -194,14 +194,7 @@ public class RemoteClientConfiguration { @Bean public FileSystemWatcherFactory getFileSystemWatcherFactory() { - return new FileSystemWatcherFactory() { - - @Override - public FileSystemWatcher getFileSystemWatcher() { - return newFileSystemWatcher(); - } - - }; + return this::newFileSystemWatcher; } private FileSystemWatcher newFileSystemWatcher() { diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/AccessManager.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/AccessManager.java index 494d281794..83daa19e7c 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/AccessManager.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/server/AccessManager.java @@ -30,14 +30,7 @@ public interface AccessManager { /** * {@link AccessManager} that permits all requests. */ - AccessManager PERMIT_ALL = new AccessManager() { - - @Override - public boolean isAllowed(ServerHttpRequest request) { - return true; - } - - }; + AccessManager PERMIT_ALL = (request) -> true; /** * Determine if the specific request is allowed to be handled by the diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/FailureHandler.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/FailureHandler.java index 7ad9af798a..27309e8f75 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/FailureHandler.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/FailureHandler.java @@ -28,14 +28,7 @@ public interface FailureHandler { /** * {@link FailureHandler} that always aborts. */ - FailureHandler NONE = new FailureHandler() { - - @Override - public Outcome handle(Throwable failure) { - return Outcome.ABORT; - } - - }; + FailureHandler NONE = (failure) -> Outcome.ABORT; /** * Handle a run failure. Implementations may block, for example to wait until specific diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/RestartInitializer.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/RestartInitializer.java index 384b711cc4..46ee801822 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/RestartInitializer.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/RestartInitializer.java @@ -31,14 +31,7 @@ public interface RestartInitializer { /** * {@link RestartInitializer} that doesn't return any URLs. */ - RestartInitializer NONE = new RestartInitializer() { - - @Override - public URL[] getInitialUrls(Thread thread) { - return null; - } - - }; + RestartInitializer NONE = (thread) -> null; /** * Return the initial set of URLs for the {@link Restarter} or {@code null} if no diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/Restarter.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/Restarter.java index 4da7159670..e6261df159 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/Restarter.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/Restarter.java @@ -167,15 +167,10 @@ public class Restarter { private void immediateRestart() { try { - getLeakSafeThread().callAndWait(new Callable() { - - @Override - public Void call() throws Exception { - start(FailureHandler.NONE); - cleanupCaches(); - return null; - } - + getLeakSafeThread().callAndWait(() -> { + start(FailureHandler.NONE); + cleanupCaches(); + return null; }); } catch (Exception ex) { @@ -251,15 +246,10 @@ public class Restarter { return; } this.logger.debug("Restarting application"); - getLeakSafeThread().call(new Callable() { - - @Override - public Void call() throws Exception { - Restarter.this.stop(); - Restarter.this.start(failureHandler); - return null; - } - + getLeakSafeThread().call(() -> { + Restarter.this.stop(); + Restarter.this.start(failureHandler); + return null; }); } @@ -641,15 +631,10 @@ public class Restarter { @Override public Thread newThread(final Runnable runnable) { - return getLeakSafeThread().callAndWait(new Callable() { - - @Override - public Thread call() throws Exception { - Thread thread = new Thread(runnable); - thread.setContextClassLoader(Restarter.this.applicationClassLoader); - return thread; - } - + return getLeakSafeThread().callAndWait(() -> { + Thread thread = new Thread(runnable); + thread.setContextClassLoader(Restarter.this.applicationClassLoader); + return thread; }); } diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileRepository.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileRepository.java index 6692079430..ab1d137d69 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileRepository.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileRepository.java @@ -31,14 +31,7 @@ public interface ClassLoaderFileRepository { /** * Empty {@link ClassLoaderFileRepository} implementation. */ - ClassLoaderFileRepository NONE = new ClassLoaderFileRepository() { - - @Override - public ClassLoaderFile getFile(String name) { - return null; - } - - }; + ClassLoaderFileRepository NONE = (name) -> null; /** * Return a {@link ClassLoaderFile} for the given name or {@code null} if no file is diff --git a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoader.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoader.java index bad78dd338..3f16c6e042 100644 --- a/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoader.java +++ b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoader.java @@ -126,12 +126,8 @@ public class RestartClassLoader extends URLClassLoader implements SmartClassLoad if (file.getKind() == Kind.DELETED) { return null; } - return AccessController.doPrivileged(new PrivilegedAction() { - @Override - public URL run() { - return createFileUrl(name, file); - } - }); + return AccessController + .doPrivileged((PrivilegedAction) () -> createFileUrl(name, file)); } @Override @@ -167,12 +163,9 @@ public class RestartClassLoader extends URLClassLoader implements SmartClassLoad if (file.getKind() == Kind.DELETED) { throw new ClassNotFoundException(name); } - return AccessController.doPrivileged(new PrivilegedAction>() { - @Override - public Class run() { - byte[] bytes = file.getContents(); - return defineClass(name, bytes, 0, bytes.length); - } + return AccessController.doPrivileged((PrivilegedAction>) () -> { + byte[] bytes = file.getContents(); + return defineClass(name, bytes, 0, bytes.length); }); } diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java index e2d1c4d896..fecb1d151b 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java @@ -28,7 +28,6 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; -import org.springframework.boot.devtools.filewatch.ChangedFile; import org.springframework.boot.devtools.filewatch.FileSystemWatcher; import org.springframework.boot.devtools.filewatch.FileSystemWatcherFactory; import org.springframework.context.ApplicationListener; @@ -113,14 +112,7 @@ public class ClassPathFileSystemWatcherTests { @Bean public ClassPathRestartStrategy restartStrategy() { - return new ClassPathRestartStrategy() { - - @Override - public boolean isRestartRequired(ChangedFile file) { - return false; - } - - }; + return (file) -> false; } @Bean diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java index 03ceb3c215..3d7ee8233e 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java @@ -17,7 +17,6 @@ package org.springframework.boot.devtools.filewatch; import java.io.File; -import java.io.FileFilter; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; @@ -221,12 +220,7 @@ public class FileSystemWatcherTests { File folder = this.temp.newFolder(); final Set listener2Changes = new LinkedHashSet<>(); this.watcher.addSourceFolder(folder); - this.watcher.addListener(new FileChangeListener() { - @Override - public void onChange(Set changeSet) { - listener2Changes.addAll(changeSet); - } - }); + this.watcher.addListener(listener2Changes::addAll); this.watcher.start(); File file = touch(new File(folder, "test.txt")); this.watcher.stopAfter(1); @@ -262,14 +256,8 @@ public class FileSystemWatcherTests { File file = touch(new File(folder, "file.txt")); File trigger = touch(new File(folder, "trigger.txt")); this.watcher.addSourceFolder(folder); - this.watcher.setTriggerFilter(new FileFilter() { - - @Override - public boolean accept(File file) { - return file.getName().equals("trigger.txt"); - } - - }); + this.watcher.setTriggerFilter( + (candidate) -> candidate.getName().equals("trigger.txt")); this.watcher.start(); FileCopyUtils.copy("abc".getBytes(), file); Thread.sleep(100); @@ -285,12 +273,8 @@ public class FileSystemWatcherTests { private void setupWatcher(long pollingInterval, long quietPeriod) { this.watcher = new FileSystemWatcher(false, pollingInterval, quietPeriod); - this.watcher.addListener(new FileChangeListener() { - @Override - public void onChange(Set changeSet) { - FileSystemWatcherTests.this.changes.add(changeSet); - } - }); + this.watcher.addListener( + (changeSet) -> FileSystemWatcherTests.this.changes.add(changeSet)); } private File startWithNewFolder() throws IOException { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java index 4bd5c0c0b1..ec5d06acf5 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java @@ -55,12 +55,7 @@ public class MainMethodTests { @Test public void validMainMethod() throws Exception { - MainMethod method = new TestThread(new Runnable() { - @Override - public void run() { - Valid.main(); - } - }).test(); + MainMethod method = new TestThread(Valid::main).test(); assertThat(method.getMethod()).isEqualTo(this.actualMain); assertThat(method.getDeclaringClassName()) .isEqualTo(this.actualMain.getDeclaringClass().getName()); @@ -70,24 +65,14 @@ public class MainMethodTests { public void missingArgsMainMethod() throws Exception { this.thrown.expect(IllegalStateException.class); this.thrown.expectMessage("Unable to find main method"); - new TestThread(new Runnable() { - @Override - public void run() { - MissingArgs.main(); - } - }).test(); + new TestThread(MissingArgs::main).test(); } @Test public void nonStatic() throws Exception { this.thrown.expect(IllegalStateException.class); this.thrown.expectMessage("Unable to find main method"); - new TestThread(new Runnable() { - @Override - public void run() { - new NonStaticMain().main(); - } - }).test(); + new TestThread(() -> new NonStaticMain().main()).test(); } private static class TestThread extends Thread { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MockRestarter.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MockRestarter.java index c315b762ac..d42fd20420 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MockRestarter.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MockRestarter.java @@ -19,13 +19,10 @@ package org.springframework.boot.devtools.restart; import java.net.URL; import java.util.HashMap; import java.util.Map; -import java.util.concurrent.ThreadFactory; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.springframework.beans.factory.ObjectFactory; @@ -64,30 +61,17 @@ public class MockRestarter implements TestRule { Restarter.setInstance(this.mock); given(this.mock.getInitialUrls()).willReturn(new URL[] {}); given(this.mock.getOrAddAttribute(anyString(), (ObjectFactory) any())) - .willAnswer(new Answer() { - - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - String name = (String) invocation.getArguments()[0]; - ObjectFactory factory = (ObjectFactory) invocation - .getArguments()[1]; - Object attribute = MockRestarter.this.attributes.get(name); - if (attribute == null) { - attribute = factory.getObject(); - MockRestarter.this.attributes.put(name, attribute); - } - return attribute; + .willAnswer((invocation) -> { + String name = (String) invocation.getArguments()[0]; + ObjectFactory factory = (ObjectFactory) invocation.getArguments()[1]; + Object attribute = MockRestarter.this.attributes.get(name); + if (attribute == null) { + attribute = factory.getObject(); + MockRestarter.this.attributes.put(name, attribute); } - + return attribute; }); - given(this.mock.getThreadFactory()).willReturn(new ThreadFactory() { - - @Override - public Thread newThread(Runnable r) { - return new Thread(r); - } - - }); + given(this.mock.getThreadFactory()).willReturn(Thread::new); } private void cleanup() { diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/OnInitializedRestarterConditionTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/OnInitializedRestarterConditionTests.java index c8aef1fba0..b52ca26388 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/OnInitializedRestarterConditionTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/OnInitializedRestarterConditionTests.java @@ -67,14 +67,7 @@ public class OnInitializedRestarterConditionTests { @Test public void initialized() throws Exception { - Thread thread = new Thread() { - - @Override - public void run() { - TestInitialized.main(); - }; - - }; + Thread thread = new Thread(TestInitialized::main); thread.start(); synchronized (wait) { wait.wait(); diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java index 193daf4d9a..7ff3e1cfa4 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java @@ -28,7 +28,6 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.springframework.beans.BeansException; import org.springframework.beans.factory.ObjectFactory; import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile; import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile.Kind; @@ -84,14 +83,7 @@ public class RestarterTests { @Test public void testRestart() throws Exception { Restarter.clearInstance(); - Thread thread = new Thread() { - - @Override - public void run() { - SampleApplication.main(); - }; - - }; + Thread thread = new Thread(SampleApplication::main); thread.start(); Thread.sleep(2600); String output = this.out.toString(); @@ -150,12 +142,7 @@ public class RestarterTests { @Test @SuppressWarnings("rawtypes") public void getOrAddAttributeWithExistingAttribute() throws Exception { - Restarter.getInstance().getOrAddAttribute("x", new ObjectFactory() { - @Override - public String getObject() throws BeansException { - return "abc"; - } - }); + Restarter.getInstance().getOrAddAttribute("x", () -> "abc"); ObjectFactory objectFactory = mock(ObjectFactory.class); Object attribute = Restarter.getInstance().getOrAddAttribute("x", objectFactory); assertThat(attribute).isEqualTo("abc"); @@ -166,19 +153,16 @@ public class RestarterTests { public void getThreadFactory() throws Exception { final ClassLoader parentLoader = Thread.currentThread().getContextClassLoader(); final ClassLoader contextClassLoader = new URLClassLoader(new URL[0]); - Thread thread = new Thread() { - @Override - public void run() { - Runnable runnable = mock(Runnable.class); - Thread regular = new Thread(); - ThreadFactory factory = Restarter.getInstance().getThreadFactory(); - Thread viaFactory = factory.newThread(runnable); - // Regular threads will inherit the current thread - assertThat(regular.getContextClassLoader()).isEqualTo(contextClassLoader); - // Factory threads should inherit from the initial thread - assertThat(viaFactory.getContextClassLoader()).isEqualTo(parentLoader); - }; - }; + Thread thread = new Thread(() -> { + Runnable runnable = mock(Runnable.class); + Thread regular = new Thread(); + ThreadFactory factory = Restarter.getInstance().getThreadFactory(); + Thread viaFactory = factory.newThread(runnable); + // Regular threads will inherit the current thread + assertThat(regular.getContextClassLoader()).isEqualTo(contextClassLoader); + // Factory threads should inherit from the initial thread + assertThat(viaFactory.getContextClassLoader()).isEqualTo(parentLoader); + }); thread.setContextClassLoader(contextClassLoader); thread.start(); thread.join(); diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/SilentExitExceptionHandlerTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/SilentExitExceptionHandlerTests.java index 7cc1fc2c4c..2d9b6b1a92 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/SilentExitExceptionHandlerTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/SilentExitExceptionHandlerTests.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. @@ -81,12 +81,8 @@ public class SilentExitExceptionHandlerTests { private Throwable thrown; TestThread() { - setUncaughtExceptionHandler(new UncaughtExceptionHandler() { - @Override - public void uncaughtException(Thread t, Throwable e) { - TestThread.this.thrown = e; - } - }); + setUncaughtExceptionHandler( + (thread, exception) -> TestThread.this.thrown = exception); } public Throwable getThrown() { @@ -119,21 +115,16 @@ public class SilentExitExceptionHandlerTests { @Override protected Thread[] getAllThreads() { final CountDownLatch threadRunning = new CountDownLatch(1); - Thread daemonThread = new Thread(new Runnable() { - - @Override - public void run() { - synchronized (TestSilentExitExceptionHandler.this.monitor) { - threadRunning.countDown(); - try { - TestSilentExitExceptionHandler.this.monitor.wait(); - } - catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - } + Thread daemonThread = new Thread(() -> { + synchronized (TestSilentExitExceptionHandler.this.monitor) { + threadRunning.countDown(); + try { + TestSilentExitExceptionHandler.this.monitor.wait(); + } + catch (InterruptedException ex) { + Thread.currentThread().interrupt(); } } - }); daemonThread.setDaemon(true); daemonThread.start(); diff --git a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java index e8a7d17931..7647b0e5e3 100644 --- a/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java +++ b/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java @@ -33,8 +33,6 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.springframework.boot.devtools.tunnel.payload.HttpTunnelPayload; import org.springframework.boot.devtools.tunnel.server.HttpTunnelServer.HttpConnection; @@ -90,13 +88,10 @@ public class HttpTunnelServerTests { public void setup() throws Exception { MockitoAnnotations.initMocks(this); this.server = new HttpTunnelServer(this.serverConnection); - given(this.serverConnection.open(anyInt())).willAnswer(new Answer() { - @Override - public ByteChannel answer(InvocationOnMock invocation) throws Throwable { - MockServerChannel channel = HttpTunnelServerTests.this.serverChannel; - channel.setTimeout((Integer) invocation.getArguments()[0]); - return channel; - } + given(this.serverConnection.open(anyInt())).willAnswer((invocation) -> { + MockServerChannel channel = HttpTunnelServerTests.this.serverChannel; + channel.setTimeout((Integer) invocation.getArguments()[0]); + return channel; }); this.servletRequest = new MockHttpServletRequest(); this.servletRequest.setAsyncSupported(true); @@ -311,15 +306,10 @@ public class HttpTunnelServerTests { .willThrow(new IllegalArgumentException()); final HttpConnection connection = new HttpConnection(request, this.response); final AtomicBoolean responded = new AtomicBoolean(); - Thread connectionThread = new Thread() { - - @Override - public void run() { - connection.waitForResponse(); - responded.set(true); - } - - }; + Thread connectionThread = new Thread(() -> { + connection.waitForResponse(); + responded.set(true); + }); connectionThread.start(); assertThat(responded.get()).isFalse(); Thread.sleep(sleepBeforeResponse); diff --git a/spring-boot-integration-tests/spring-boot-launch-script-tests/src/test/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIT.java b/spring-boot-integration-tests/spring-boot-launch-script-tests/src/test/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIT.java index 5dd798ff2c..812257651b 100644 --- a/spring-boot-integration-tests/spring-boot-launch-script-tests/src/test/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIT.java +++ b/spring-boot-integration-tests/spring-boot-launch-script-tests/src/test/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIT.java @@ -18,7 +18,6 @@ package org.springframework.boot.launchscript; import java.io.File; import java.io.FileInputStream; -import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; @@ -27,8 +26,6 @@ import java.util.List; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; -import javax.ws.rs.client.ClientRequestContext; -import javax.ws.rs.client.ClientRequestFilter; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; @@ -449,15 +446,9 @@ public class SysVinitLaunchScriptIT { extends DockerCmdExecFactoryImpl { private SpringBootDockerCmdExecFactory() { - withClientRequestFilters(new ClientRequestFilter() { - - @Override - public void filter(ClientRequestContext requestContext) - throws IOException { - // Workaround for https://go-review.googlesource.com/#/c/3821/ - requestContext.getHeaders().add("Connection", "close"); - } - + withClientRequestFilters((requestContext) -> { + // Workaround for https://go-review.googlesource.com/#/c/3821/ + requestContext.getHeaders().add("Connection", "close"); }); } diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonTestersAutoConfiguration.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonTestersAutoConfiguration.java index 79f7ace6ca..4110e31167 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonTestersAutoConfiguration.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonTestersAutoConfiguration.java @@ -43,7 +43,6 @@ import org.springframework.context.annotation.Scope; import org.springframework.core.ResolvableType; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.util.ReflectionUtils; -import org.springframework.util.ReflectionUtils.FieldCallback; /** * Auto-configuration for Json testers. @@ -150,18 +149,10 @@ public class JsonTestersAutoConfiguration { extends InstantiationAwareBeanPostProcessorAdapter { @Override - public Object postProcessAfterInitialization(final Object bean, String beanName) + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { - - ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() { - - @Override - public void doWith(Field field) - throws IllegalArgumentException, IllegalAccessException { - processField(bean, field); - } - - }); + ReflectionUtils.doWithFields(bean.getClass(), + (field) -> processField(bean, field)); return bean; } diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/WebTestClientAutoConfiguration.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/WebTestClientAutoConfiguration.java index 1f8bbb807e..51cc7b83b0 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/WebTestClientAutoConfiguration.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/WebTestClientAutoConfiguration.java @@ -17,6 +17,7 @@ package org.springframework.boot.test.autoconfigure.web.reactive; import java.util.Collection; +import java.util.function.Consumer; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; @@ -26,6 +27,7 @@ import org.springframework.boot.web.codec.CodecCustomizer; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.http.codec.ClientCodecConfigurer; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.util.CollectionUtils; import org.springframework.web.reactive.function.client.ExchangeStrategies; @@ -53,14 +55,18 @@ public class WebTestClientAutoConfiguration { private void customizeWebTestClientCodecs(WebTestClient.Builder builder, ApplicationContext applicationContext) { - Collection codecCustomizers = applicationContext + Collection customizers = applicationContext .getBeansOfType(CodecCustomizer.class).values(); - if (!CollectionUtils.isEmpty(codecCustomizers)) { - builder.exchangeStrategies(ExchangeStrategies.builder().codecs((codecs) -> { - codecCustomizers - .forEach((codecCustomizer) -> codecCustomizer.customize(codecs)); - }).build()); + if (!CollectionUtils.isEmpty(customizers)) { + builder.exchangeStrategies(ExchangeStrategies.builder() + .codecs(applyCustomizers(customizers)).build()); } } + private Consumer applyCustomizers( + Collection customizers) { + return (codecs) -> customizers + .forEach((customizer) -> customizer.customize(codecs)); + } + } diff --git a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverScope.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverScope.java index 9b8637242e..f8aec348ec 100644 --- a/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverScope.java +++ b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverScope.java @@ -21,10 +21,8 @@ import java.util.Map; import org.openqa.selenium.WebDriver; -import org.springframework.beans.BeansException; import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.Scope; import org.springframework.context.ApplicationContext; @@ -116,24 +114,20 @@ class WebDriverScope implements Scope { if (beanFactory.getRegisteredScope(NAME) == null) { beanFactory.registerScope(NAME, new WebDriverScope()); } - context.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() { + context.addBeanFactoryPostProcessor(WebDriverScope::postProcessBeanFactory); + } - @Override - public void postProcessBeanFactory( - ConfigurableListableBeanFactory beanFactory) throws BeansException { - for (String beanClass : BEAN_CLASSES) { - for (String beanName : beanFactory.getBeanNamesForType( - ClassUtils.resolveClassName(beanClass, null))) { - BeanDefinition definition = beanFactory - .getBeanDefinition(beanName); - if (!StringUtils.hasLength(definition.getScope())) { - definition.setScope(NAME); - } - } + private static void postProcessBeanFactory( + ConfigurableListableBeanFactory beanFactory) { + for (String beanClass : BEAN_CLASSES) { + for (String beanName : beanFactory + .getBeanNamesForType(ClassUtils.resolveClassName(beanClass, null))) { + BeanDefinition definition = beanFactory.getBeanDefinition(beanName); + if (!StringUtils.hasLength(definition.getScope())) { + definition.setScope(NAME); } } - - }); + } } /** diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/context/ImportsContextCustomizerFactory.java b/spring-boot-test/src/main/java/org/springframework/boot/test/context/ImportsContextCustomizerFactory.java index c44951548c..3777806a1c 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/context/ImportsContextCustomizerFactory.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/context/ImportsContextCustomizerFactory.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. @@ -27,7 +27,6 @@ import org.springframework.test.context.ContextCustomizer; import org.springframework.test.context.ContextCustomizerFactory; import org.springframework.util.Assert; import org.springframework.util.ReflectionUtils; -import org.springframework.util.ReflectionUtils.MethodCallback; /** * {@link ContextCustomizerFactory} to allow {@code @Import} annotations to be used @@ -49,16 +48,12 @@ class ImportsContextCustomizerFactory implements ContextCustomizerFactory { } private void assertHasNoBeanMethods(Class testClass) { - ReflectionUtils.doWithMethods(testClass, new MethodCallback() { - - @Override - public void doWith(Method method) { - Assert.state(!AnnotatedElementUtils.isAnnotated(method, Bean.class), - "Test classes cannot include @Bean methods"); - } - - }); + ReflectionUtils.doWithMethods(testClass, this::assertHasNoBeanMethods); + } + private void assertHasNoBeanMethods(Method method) { + Assert.state(!AnnotatedElementUtils.isAnnotated(method, Bean.class), + "Test classes cannot include @Bean methods"); } } diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/json/AbstractJsonMarshalTester.java b/spring-boot-test/src/main/java/org/springframework/boot/test/json/AbstractJsonMarshalTester.java index dd528babf7..8f5d9e5285 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/json/AbstractJsonMarshalTester.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/json/AbstractJsonMarshalTester.java @@ -28,7 +28,6 @@ import java.lang.reflect.Field; import org.assertj.core.api.Assertions; -import org.springframework.beans.BeansException; import org.springframework.beans.factory.ObjectFactory; import org.springframework.core.ResolvableType; import org.springframework.core.io.ByteArrayResource; @@ -38,7 +37,6 @@ import org.springframework.core.io.InputStreamResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.springframework.util.ReflectionUtils; -import org.springframework.util.ReflectionUtils.FieldCallback; /** * Base class for AssertJ based JSON marshal testers. Exposes specific Asserts following a @@ -370,29 +368,15 @@ public abstract class AbstractJsonMarshalTester { public void initFields(final Object testInstance, final M marshaller) { Assert.notNull(testInstance, "TestInstance must not be null"); Assert.notNull(marshaller, "Marshaller must not be null"); - initFields(testInstance, new ObjectFactory() { - - @Override - public M getObject() throws BeansException { - return marshaller; - } - - }); + initFields(testInstance, () -> marshaller); } public void initFields(final Object testInstance, final ObjectFactory marshaller) { Assert.notNull(testInstance, "TestInstance must not be null"); Assert.notNull(marshaller, "Marshaller must not be null"); - ReflectionUtils.doWithFields(testInstance.getClass(), new FieldCallback() { - - @Override - public void doWith(Field field) - throws IllegalArgumentException, IllegalAccessException { - doWithField(field, testInstance, marshaller); - } - - }); + ReflectionUtils.doWithFields(testInstance.getClass(), + (field) -> doWithField(field, testInstance, marshaller)); } protected void doWithField(Field field, Object test, diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/DefinitionsParser.java b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/DefinitionsParser.java index e0f4dce879..99348cb188 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/DefinitionsParser.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/DefinitionsParser.java @@ -29,7 +29,6 @@ import org.springframework.core.ResolvableType; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.util.Assert; import org.springframework.util.ReflectionUtils; -import org.springframework.util.ReflectionUtils.FieldCallback; import org.springframework.util.StringUtils; /** @@ -60,15 +59,7 @@ class DefinitionsParser { public void parse(Class source) { parseElement(source); - ReflectionUtils.doWithFields(source, new FieldCallback() { - - @Override - public void doWith(Field field) - throws IllegalArgumentException, IllegalAccessException { - parseElement(field); - } - - }); + ReflectionUtils.doWithFields(source, this::parseElement); } private void parseElement(AnnotatedElement element) { diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessor.java b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessor.java index fab7081390..5022867233 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessor.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessor.java @@ -61,7 +61,6 @@ import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.ReflectionUtils; -import org.springframework.util.ReflectionUtils.FieldCallback; import org.springframework.util.StringUtils; /** @@ -371,15 +370,8 @@ public class MockitoPostProcessor extends InstantiationAwareBeanPostProcessorAda public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, final Object bean, String beanName) throws BeansException { - ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() { - - @Override - public void doWith(Field field) - throws IllegalArgumentException, IllegalAccessException { - postProcessField(bean, field); - } - - }); + ReflectionUtils.doWithFields(bean.getClass(), + (field) -> postProcessField(bean, field)); return pvs; } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.java index b3e185795e..97e67680ed 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.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. @@ -1307,14 +1307,7 @@ public class JsonContentAssertTests { } private AssertProvider forJson(final String json) { - return new AssertProvider() { - - @Override - public JsonContentAssert assertThat() { - return new JsonContentAssert(JsonContentAssertTests.class, json); - } - - }; + return () -> new JsonContentAssert(JsonContentAssertTests.class, json); } } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentAssertTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentAssertTests.java index be83982f24..bec199d4f9 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentAssertTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentAssertTests.java @@ -73,14 +73,7 @@ public class ObjectContentAssertTests { } private AssertProvider> forObject(final Object source) { - return new AssertProvider>() { - - @Override - public ObjectContentAssert assertThat() { - return new ObjectContentAssert<>(source); - } - - }; + return () -> new ObjectContentAssert<>(source); } } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanForBeanFactoryIntegrationTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanForBeanFactoryIntegrationTests.java index c0783da167..35ad796d11 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanForBeanFactoryIntegrationTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanForBeanFactoryIntegrationTests.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. @@ -71,14 +71,7 @@ public class MockBeanForBeanFactoryIntegrationTests { @Override public TestBean getObject() throws Exception { - return new TestBean() { - - @Override - public String hello() { - return "normal"; - } - - }; + return () -> "normal"; } @Override diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/web/SpringBootMockServletContextTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/web/SpringBootMockServletContextTests.java index dda6492c70..180447f359 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/mock/web/SpringBootMockServletContextTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/mock/web/SpringBootMockServletContextTests.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. @@ -17,7 +17,6 @@ package org.springframework.boot.test.mock.web; import java.io.File; -import java.io.FilenameFilter; import java.net.MalformedURLException; import java.net.URL; import java.net.URLDecoder; @@ -87,12 +86,8 @@ public class SpringBootMockServletContextTests implements ServletContextAware { assertThat(resource).isNotEqualTo(nullValue()); File file = new File(URLDecoder.decode(resource.getPath(), "UTF-8")); assertThat(file).exists().isDirectory(); - String[] contents = file.list(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return !(".".equals(name) || "..".equals(name)); - } - }); + String[] contents = file + .list((dir, name) -> !(".".equals(name) || "..".equals(name))); assertThat(contents).isNotEqualTo(nullValue()); assertThat(contents.length).isEqualTo(0); } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java index 94fea8df7f..76f0306a82 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java @@ -154,13 +154,7 @@ public class TestRestTemplateTests { return mock(type); } - }, new ReflectionUtils.MethodFilter() { - @Override - public boolean matches(Method method) { - return Modifier.isPublic(method.getModifiers()); - } - - }); + }, (method) -> Modifier.isPublic(method.getModifiers())); } @@ -217,209 +211,99 @@ public class TestRestTemplateTests { @Test public void deleteHandlesRelativeUris() throws IOException { - verifyRelativeUriHandling(new TestRestTemplateCallback() { - - @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { - testRestTemplate.delete(relativeUri); - } - - }); + verifyRelativeUriHandling(TestRestTemplate::delete); } @Test public void exchangeWithRequestEntityAndClassHandlesRelativeUris() throws IOException { - verifyRelativeUriHandling(new TestRestTemplateCallback() { - - @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { - testRestTemplate.exchange( - new RequestEntity(HttpMethod.GET, relativeUri), - String.class); - } - - }); + verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate + .exchange(new RequestEntity(HttpMethod.GET, relativeUri), + String.class)); } @Test public void exchangeWithRequestEntityAndParameterizedTypeReferenceHandlesRelativeUris() throws IOException { - verifyRelativeUriHandling(new TestRestTemplateCallback() { - - @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { - testRestTemplate.exchange( - new RequestEntity(HttpMethod.GET, relativeUri), + verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate + .exchange(new RequestEntity(HttpMethod.GET, relativeUri), new ParameterizedTypeReference() { - }); - } - - }); + })); } @Test public void exchangeHandlesRelativeUris() throws IOException { - verifyRelativeUriHandling(new TestRestTemplateCallback() { - - @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { - testRestTemplate.exchange(relativeUri, HttpMethod.GET, - new HttpEntity<>(new byte[0]), String.class); - } - - }); + verifyRelativeUriHandling( + (testRestTemplate, relativeUri) -> testRestTemplate.exchange(relativeUri, + HttpMethod.GET, new HttpEntity<>(new byte[0]), String.class)); } @Test public void exchangeWithParameterizedTypeReferenceHandlesRelativeUris() throws IOException { - verifyRelativeUriHandling(new TestRestTemplateCallback() { - - @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { - testRestTemplate.exchange(relativeUri, HttpMethod.GET, - new HttpEntity<>(new byte[0]), + verifyRelativeUriHandling( + (testRestTemplate, relativeUri) -> testRestTemplate.exchange(relativeUri, + HttpMethod.GET, new HttpEntity<>(new byte[0]), new ParameterizedTypeReference() { - }); - } - - }); + })); } @Test public void executeHandlesRelativeUris() throws IOException { - verifyRelativeUriHandling(new TestRestTemplateCallback() { - - @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { - testRestTemplate.execute(relativeUri, HttpMethod.GET, null, null); - } - - }); + verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate + .execute(relativeUri, HttpMethod.GET, null, null)); } @Test public void getForEntityHandlesRelativeUris() throws IOException { - verifyRelativeUriHandling(new TestRestTemplateCallback() { - - @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { - testRestTemplate.getForEntity(relativeUri, String.class); - } - - }); + verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate + .getForEntity(relativeUri, String.class)); } @Test public void getForObjectHandlesRelativeUris() throws IOException { - verifyRelativeUriHandling(new TestRestTemplateCallback() { - - @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { - testRestTemplate.getForObject(relativeUri, String.class); - } - - }); + verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate + .getForObject(relativeUri, String.class)); } @Test public void headForHeadersHandlesRelativeUris() throws IOException { - verifyRelativeUriHandling(new TestRestTemplateCallback() { - - @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { - testRestTemplate.headForHeaders(relativeUri); - } - - }); + verifyRelativeUriHandling(TestRestTemplate::headForHeaders); } @Test public void optionsForAllowHandlesRelativeUris() throws IOException { - verifyRelativeUriHandling(new TestRestTemplateCallback() { - - @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { - testRestTemplate.optionsForAllow(relativeUri); - } - - }); + verifyRelativeUriHandling(TestRestTemplate::optionsForAllow); } @Test public void patchForObjectHandlesRelativeUris() throws IOException { - verifyRelativeUriHandling(new TestRestTemplateCallback() { - - @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { - testRestTemplate.patchForObject(relativeUri, "hello", String.class); - } - - }); + verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate + .patchForObject(relativeUri, "hello", String.class)); } @Test public void postForEntityHandlesRelativeUris() throws IOException { - verifyRelativeUriHandling(new TestRestTemplateCallback() { - - @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { - testRestTemplate.postForEntity(relativeUri, "hello", String.class); - } - - }); + verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate + .postForEntity(relativeUri, "hello", String.class)); } @Test public void postForLocationHandlesRelativeUris() throws IOException { - verifyRelativeUriHandling(new TestRestTemplateCallback() { - - @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { - testRestTemplate.postForLocation(relativeUri, "hello"); - } - - }); + verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate + .postForLocation(relativeUri, "hello")); } @Test public void postForObjectHandlesRelativeUris() throws IOException { - verifyRelativeUriHandling(new TestRestTemplateCallback() { - - @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { - testRestTemplate.postForObject(relativeUri, "hello", String.class); - } - - }); + verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate + .postForObject(relativeUri, "hello", String.class)); } @Test public void putHandlesRelativeUris() throws IOException { - verifyRelativeUriHandling(new TestRestTemplateCallback() { - - @Override - public void doWithTestRestTemplate(TestRestTemplate testRestTemplate, - URI relativeUri) { - testRestTemplate.put(relativeUri, "hello"); - } - - }); + verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate + .put(relativeUri, "hello")); } private void verifyRelativeUriHandling(TestRestTemplateCallback callback) diff --git a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/FieldValuesParser.java b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/FieldValuesParser.java index e2552825c6..7e741a6cc8 100644 --- a/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/FieldValuesParser.java +++ b/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/fieldvalues/FieldValuesParser.java @@ -36,14 +36,7 @@ public interface FieldValuesParser { /** * Implementation of {@link FieldValuesParser} that always returns an empty result. */ - FieldValuesParser NONE = new FieldValuesParser() { - - @Override - public Map getFieldValues(TypeElement element) { - return Collections.emptyMap(); - } - - }; + FieldValuesParser NONE = (element) -> Collections.emptyMap(); /** * Return the field values for the given element. 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 3cdc2b930a..34c0554ef2 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 @@ -110,12 +110,7 @@ public class JarWriter implements LoaderClassesWriter, AutoCloseable { */ public void writeManifest(final Manifest manifest) throws IOException { JarArchiveEntry entry = new JarArchiveEntry("META-INF/MANIFEST.MF"); - writeEntry(entry, new EntryWriter() { - @Override - public void write(OutputStream outputStream) throws IOException { - manifest.write(outputStream); - } - }); + writeEntry(entry, manifest::write); } /** diff --git a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Libraries.java b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Libraries.java index a32f59a23c..5681ca3246 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Libraries.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Libraries.java @@ -29,10 +29,7 @@ public interface Libraries { /** * Represents no libraries. */ - Libraries NONE = new Libraries() { - @Override - public void doWithLibraries(LibraryCallback callback) throws IOException { - } + Libraries NONE = (callback) -> { }; /** 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 984bfde51d..053d2d78a7 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 @@ -61,19 +61,17 @@ public abstract class MainClassFinder { private static final String MAIN_METHOD_NAME = "main"; - private static final FileFilter CLASS_FILE_FILTER = new FileFilter() { - @Override - public boolean accept(File file) { - return (file.isFile() && file.getName().endsWith(DOT_CLASS)); - } - }; + private static final FileFilter CLASS_FILE_FILTER = MainClassFinder::isClassFile; - private static final FileFilter PACKAGE_FOLDER_FILTER = new FileFilter() { - @Override - public boolean accept(File file) { - return file.isDirectory() && !file.getName().startsWith("."); - } - }; + private static final FileFilter PACKAGE_FOLDER_FILTER = MainClassFinder::isPackageFolder; + + private static boolean isClassFile(File file) { + return file.isFile() && file.getName().endsWith(DOT_CLASS); + } + + private static boolean isPackageFolder(File file) { + return file.isDirectory() && !file.getName().startsWith("."); + } /** * Find the main class from a given folder. @@ -82,12 +80,7 @@ public abstract class MainClassFinder { * @throws IOException if the folder cannot be read */ public static String findMainClass(File rootFolder) throws IOException { - return doWithMainClasses(rootFolder, new MainClassCallback() { - @Override - public String doWith(MainClass mainClass) { - return mainClass.getName(); - } - }); + return doWithMainClasses(rootFolder, MainClass::getName); } /** @@ -163,12 +156,7 @@ public abstract class MainClassFinder { } private static void pushAllSorted(Deque stack, File[] files) { - Arrays.sort(files, new Comparator() { - @Override - public int compare(File o1, File o2) { - return o1.getName().compareTo(o2.getName()); - } - }); + Arrays.sort(files, Comparator.comparing(File::getName)); for (File file : files) { stack.push(file); } @@ -183,13 +171,7 @@ public abstract class MainClassFinder { */ public static String findMainClass(JarFile jarFile, String classesLocation) throws IOException { - return doWithMainClasses(jarFile, classesLocation, - new MainClassCallback() { - @Override - public String doWith(MainClass mainClass) { - return mainClass.getName(); - } - }); + return doWithMainClasses(jarFile, classesLocation, MainClass::getName); } /** 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 f3e26bb6b8..247187a44f 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 @@ -230,21 +230,16 @@ public class Repackager { try (JarWriter writer = new JarWriter(destination, launchScript)) { final List unpackLibraries = new ArrayList<>(); final List standardLibraries = new ArrayList<>(); - libraries.doWithLibraries(new LibraryCallback() { - - @Override - public void library(Library library) throws IOException { - File file = library.getFile(); - if (isZip(file)) { - if (library.isUnpackRequired()) { - unpackLibraries.add(library); - } - else { - standardLibraries.add(library); - } + libraries.doWithLibraries((library) -> { + File file = library.getFile(); + if (isZip(file)) { + if (library.isUnpackRequired()) { + unpackLibraries.add(library); + } + else { + standardLibraries.add(library); } } - }); repackage(sourceJar, writer, unpackLibraries, standardLibraries); } diff --git a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/RunProcess.java b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/RunProcess.java index c6a4cc7c65..29b84b07f7 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/RunProcess.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/RunProcess.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. @@ -87,12 +87,7 @@ public class RunProcess { if (!inheritedIO) { redirectOutput(process); } - SignalUtils.attachSignalHandler(new Runnable() { - @Override - public void run() { - handleSigInt(); - } - }); + SignalUtils.attachSignalHandler(this::handleSigInt); if (waitForProcess) { try { return process.waitFor(); @@ -154,25 +149,20 @@ public class RunProcess { private void redirectOutput(Process process) { final BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream())); - new Thread() { - - @Override - public void run() { - try { - String line = reader.readLine(); - while (line != null) { - System.out.println(line); - line = reader.readLine(); - System.out.flush(); - } - reader.close(); - } - catch (Exception ex) { - // Ignore + new Thread(() -> { + try { + String line = reader.readLine(); + while (line != null) { + System.out.println(line); + line = reader.readLine(); + System.out.flush(); } + reader.close(); } - - }.start(); + catch (Exception ex) { + // Ignore + } + }).start(); } /** diff --git a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/SignalUtils.java b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/SignalUtils.java index cd7f52ce96..953524a1be 100644 --- a/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/SignalUtils.java +++ b/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/SignalUtils.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. @@ -17,7 +17,6 @@ package org.springframework.boot.loader.tools; import sun.misc.Signal; -import sun.misc.SignalHandler; /** * Utilities for working with signal handling. @@ -39,12 +38,7 @@ public final class SignalUtils { * @param runnable the runnable to call on SIGINT. */ public static void attachSignalHandler(final Runnable runnable) { - Signal.handle(SIG_INT, new SignalHandler() { - @Override - public void handle(Signal signal) { - runnable.run(); - } - }); + Signal.handle(SIG_INT, (signal) -> runnable.run()); } } 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 3758ee4546..2c97b447be 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 @@ -56,10 +56,7 @@ import static org.mockito.Mockito.mock; */ public class RepackagerTests { - private static final Libraries NO_LIBRARIES = new Libraries() { - @Override - public void doWithLibraries(LibraryCallback callback) throws IOException { - } + private static final Libraries NO_LIBRARIES = (callback) -> { }; private static final long JAN_1_1980; @@ -301,14 +298,10 @@ public class RepackagerTests { File file = this.testJarFile.getFile(); libJarFile.setLastModified(JAN_1_1980); Repackager repackager = new Repackager(file); - repackager.repackage(new Libraries() { - @Override - public void doWithLibraries(LibraryCallback callback) throws IOException { - callback.library(new Library(libJarFile, LibraryScope.COMPILE)); - callback.library( - new Library(libJarFileToUnpack, LibraryScope.COMPILE, true)); - callback.library(new Library(libNonJarFile, LibraryScope.COMPILE)); - } + repackager.repackage((callback) -> { + callback.library(new Library(libJarFile, LibraryScope.COMPILE)); + callback.library(new Library(libJarFileToUnpack, LibraryScope.COMPILE, true)); + callback.library(new Library(libNonJarFile, LibraryScope.COMPILE)); }); assertThat(hasEntry(file, "BOOT-INF/lib/" + libJarFile.getName())).isTrue(); assertThat(hasEntry(file, "BOOT-INF/lib/" + libJarFileToUnpack.getName())) @@ -331,12 +324,9 @@ public class RepackagerTests { Repackager repackager = new Repackager(file); this.thrown.expect(IllegalStateException.class); this.thrown.expectMessage("Duplicate library"); - repackager.repackage(new Libraries() { - @Override - public void doWithLibraries(LibraryCallback callback) throws IOException { - callback.library(new Library(libJarFile, LibraryScope.COMPILE, false)); - callback.library(new Library(libJarFile, LibraryScope.COMPILE, false)); - } + repackager.repackage((callback) -> { + callback.library(new Library(libJarFile, LibraryScope.COMPILE, false)); + callback.library(new Library(libJarFile, LibraryScope.COMPILE, false)); }); } @@ -355,14 +345,8 @@ public class RepackagerTests { given(layout.getLibraryDestination(anyString(), eq(LibraryScope.COMPILE))) .willReturn("test-lib/"); repackager.setLayout(layout); - repackager.repackage(new Libraries() { - - @Override - public void doWithLibraries(LibraryCallback callback) throws IOException { - callback.library(new Library(libJarFile, scope)); - } - - }); + repackager.repackage( + (callback) -> callback.library(new Library(libJarFile, scope))); assertThat(hasEntry(file, "test/" + libJarFile.getName())).isTrue(); assertThat(getManifest(file).getMainAttributes().getValue("Spring-Boot-Lib")) .isEqualTo("test-lib/"); @@ -382,14 +366,8 @@ public class RepackagerTests { final LibraryScope scope = mock(LibraryScope.class); given(layout.getLauncherClassName()).willReturn("testLauncher"); repackager.setLayout(layout); - repackager.repackage(new Libraries() { - - @Override - public void doWithLibraries(LibraryCallback callback) throws IOException { - callback.library(new Library(libJarFile, scope)); - } - - }); + repackager.repackage( + (callback) -> callback.library(new Library(libJarFile, scope))); assertThat(getManifest(file).getMainAttributes().getValue("Spring-Boot-Lib")) .isNull(); assertThat(getManifest(file).getMainAttributes().getValue("Main-Class")) @@ -447,17 +425,13 @@ public class RepackagerTests { public void dontRecompressZips() throws Exception { TestJarFile nested = new TestJarFile(this.temporaryFolder); nested.addClass("a/b/C.class", ClassWithoutMainMethod.class); - final File nestedFile = nested.getFile(); + File nestedFile = nested.getFile(); this.testJarFile.addFile("test/nested.jar", nestedFile); this.testJarFile.addClass("A.class", ClassWithMainMethod.class); File file = this.testJarFile.getFile(); Repackager repackager = new Repackager(file); - repackager.repackage(new Libraries() { - @Override - public void doWithLibraries(LibraryCallback callback) throws IOException { - callback.library(new Library(nestedFile, LibraryScope.COMPILE)); - } - }); + repackager.repackage((callback) -> callback + .library(new Library(nestedFile, LibraryScope.COMPILE))); try (JarFile jarFile = new JarFile(file)) { assertThat( @@ -494,25 +468,16 @@ public class RepackagerTests { throws Exception { TestJarFile nested = new TestJarFile(this.temporaryFolder); nested.addClass("a/b/C.class", ClassWithoutMainMethod.class); - final File nestedFile = nested.getFile(); - this.testJarFile.addFile("BOOT-INF/lib/" + nestedFile.getName(), - nested.getFile()); + File nestedFile = nested.getFile(); + String name = "BOOT-INF/lib/" + nestedFile.getName(); + this.testJarFile.addFile(name, nested.getFile()); this.testJarFile.addClass("A.class", ClassWithMainMethod.class); File file = this.testJarFile.getFile(); Repackager repackager = new Repackager(file); - repackager.repackage(new Libraries() { - - @Override - public void doWithLibraries(LibraryCallback callback) throws IOException { - callback.library(new Library(nestedFile, LibraryScope.COMPILE, true)); - } - - }); - + repackager.repackage((callback) -> callback + .library(new Library(nestedFile, LibraryScope.COMPILE, true))); try (JarFile jarFile = new JarFile(file)) { - assertThat( - jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getComment()) - .startsWith("UNPACK:"); + assertThat(jarFile.getEntry(name).getComment()).startsWith("UNPACK:"); } } @@ -521,23 +486,18 @@ public class RepackagerTests { throws Exception { TestJarFile nested = new TestJarFile(this.temporaryFolder); nested.addClass("a/b/C.class", ClassWithoutMainMethod.class); - final File nestedFile = nested.getFile(); + File nestedFile = nested.getFile(); this.testJarFile.addFile("BOOT-INF/lib/" + nestedFile.getName(), nested.getFile()); this.testJarFile.addClass("A.class", ClassWithMainMethod.class); File file = this.testJarFile.getFile(); Repackager repackager = new Repackager(file); long sourceLength = nestedFile.length(); - repackager.repackage(new Libraries() { - - @Override - public void doWithLibraries(LibraryCallback callback) throws IOException { - nestedFile.delete(); - File toZip = RepackagerTests.this.temporaryFolder.newFile(); - ZipUtil.packEntry(toZip, nestedFile); - callback.library(new Library(nestedFile, LibraryScope.COMPILE)); - } - + repackager.repackage((callback) -> { + nestedFile.delete(); + File toZip = RepackagerTests.this.temporaryFolder.newFile(); + ZipUtil.packEntry(toZip, nestedFile); + callback.library(new Library(nestedFile, LibraryScope.COMPILE)); }); try (JarFile jarFile = new JarFile(file)) { assertThat(jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getSize()) diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/ExecutableArchiveLauncher.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/ExecutableArchiveLauncher.java index c65fbfcbae..cbe6341f04 100644 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/ExecutableArchiveLauncher.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/ExecutableArchiveLauncher.java @@ -22,8 +22,6 @@ import java.util.jar.JarEntry; import java.util.jar.Manifest; import org.springframework.boot.loader.archive.Archive; -import org.springframework.boot.loader.archive.Archive.Entry; -import org.springframework.boot.loader.archive.Archive.EntryFilter; /** * Base class for executable archive {@link Launcher}s. @@ -69,14 +67,7 @@ public abstract class ExecutableArchiveLauncher extends Launcher { @Override protected List getClassPathArchives() throws Exception { List archives = new ArrayList<>( - this.archive.getNestedArchives(new EntryFilter() { - - @Override - public boolean matches(Entry entry) { - return isNestedArchive(entry); - } - - })); + this.archive.getNestedArchives(this::isNestedArchive)); postProcessClassPathArchives(archives); return archives; } diff --git a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/LaunchedURLClassLoader.java b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/LaunchedURLClassLoader.java index 9ff3c966cd..b941c736a5 100644 --- a/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/LaunchedURLClassLoader.java +++ b/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/LaunchedURLClassLoader.java @@ -128,32 +128,28 @@ public class LaunchedURLClassLoader extends URLClassLoader { private void definePackage(final String className, final String packageName) { try { - AccessController.doPrivileged(new PrivilegedExceptionAction() { - @Override - public Object run() throws ClassNotFoundException { - String packageEntryName = packageName.replace('.', '/') + "/"; - String classEntryName = className.replace('.', '/') + ".class"; - for (URL url : getURLs()) { - try { - URLConnection connection = url.openConnection(); - if (connection instanceof JarURLConnection) { - JarFile jarFile = ((JarURLConnection) connection) - .getJarFile(); - if (jarFile.getEntry(classEntryName) != null - && jarFile.getEntry(packageEntryName) != null - && jarFile.getManifest() != null) { - definePackage(packageName, jarFile.getManifest(), - url); - return null; - } + AccessController.doPrivileged((PrivilegedExceptionAction) () -> { + String packageEntryName = packageName.replace('.', '/') + "/"; + String classEntryName = className.replace('.', '/') + ".class"; + for (URL url : getURLs()) { + try { + URLConnection connection = url.openConnection(); + if (connection instanceof JarURLConnection) { + JarFile jarFile = ((JarURLConnection) connection) + .getJarFile(); + if (jarFile.getEntry(classEntryName) != null + && jarFile.getEntry(packageEntryName) != null + && jarFile.getManifest() != null) { + definePackage(packageName, jarFile.getManifest(), url); + return null; } } - catch (IOException ex) { - // Ignore - } } - return null; + catch (IOException ex) { + // Ignore + } } + return null; }, AccessController.getContext()); } catch (java.security.PrivilegedActionException ex) { 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 a79d23256e..6e98d7910c 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 @@ -537,16 +537,11 @@ public class PropertiesLauncher extends Launcher { // directories, meaning we are running from an executable JAR. We add nested // entries from there with low priority (i.e. at end). try { - lib.addAll(this.parent.getNestedArchives(new EntryFilter() { - - @Override - public boolean matches(Entry entry) { - if (entry.isDirectory()) { - return entry.getName().equals(JarLauncher.BOOT_INF_CLASSES); - } - return entry.getName().startsWith(JarLauncher.BOOT_INF_LIB); + lib.addAll(this.parent.getNestedArchives((entry) -> { + if (entry.isDirectory()) { + return entry.getName().equals(JarLauncher.BOOT_INF_CLASSES); } - + return entry.getName().startsWith(JarLauncher.BOOT_INF_LIB); })); } catch (IOException ex) { 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 a22661f359..8676f28424 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 @@ -258,16 +258,11 @@ public class JarFile extends java.util.jar.JarFile { private JarFile createJarFileFromDirectoryEntry(JarEntry entry) throws IOException { final AsciiBytes sourceName = new AsciiBytes(entry.getName()); - JarEntryFilter filter = new JarEntryFilter() { - - @Override - public AsciiBytes apply(AsciiBytes name) { - if (name.startsWith(sourceName) && !name.equals(sourceName)) { - return name.substring(sourceName.length()); - } - return null; + JarEntryFilter filter = (name) -> { + if (name.startsWith(sourceName) && !name.equals(sourceName)) { + return name.substring(sourceName.length()); } - + return null; }; return new JarFile(this.rootFile, this.pathFromRoot + "!/" diff --git a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java index 2caf95cf4e..840872e86e 100644 --- a/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java +++ b/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java @@ -26,7 +26,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Queue; -import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; @@ -38,8 +37,6 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.springframework.boot.loader.data.RandomAccessData.ResourceAccess; import org.springframework.boot.loader.data.RandomAccessDataFile.FilePool; @@ -290,17 +287,12 @@ public class RandomAccessDataFileTests { ExecutorService executorService = Executors.newFixedThreadPool(20); List> results = new ArrayList<>(); for (int i = 0; i < 100; i++) { - results.add(executorService.submit(new Callable() { - - @Override - public Boolean call() throws Exception { - InputStream subsectionInputStream = RandomAccessDataFileTests.this.file - .getSubsection(0, 256) - .getInputStream(ResourceAccess.PER_READ); - byte[] b = new byte[256]; - subsectionInputStream.read(b); - return Arrays.equals(b, BYTES); - } + results.add(executorService.submit(() -> { + InputStream subsectionInputStream = RandomAccessDataFileTests.this.file + .getSubsection(0, 256).getInputStream(ResourceAccess.PER_READ); + byte[] b = new byte[256]; + subsectionInputStream.read(b); + return Arrays.equals(b, BYTES); })); } for (Future future : results) { @@ -327,21 +319,15 @@ public class RandomAccessDataFileTests { "filePool"); FilePool spiedPool = spy(filePool); ReflectionTestUtils.setField(this.file, "filePool", spiedPool); - willAnswer(new Answer() { - - @Override - public RandomAccessFile answer(InvocationOnMock invocation) throws Throwable { - RandomAccessFile originalFile = (RandomAccessFile) invocation - .callRealMethod(); - if (Mockito.mockingDetails(originalFile).isSpy()) { - return originalFile; - } - RandomAccessFile spiedFile = spy(originalFile); - willThrow(new IOException("Seek failed")).given(spiedFile) - .seek(anyLong()); - return spiedFile; + willAnswer((invocation) -> { + RandomAccessFile originalFile = (RandomAccessFile) invocation + .callRealMethod(); + if (Mockito.mockingDetails(originalFile).isSpy()) { + return originalFile; } - + RandomAccessFile spiedFile = spy(originalFile); + willThrow(new IOException("Seek failed")).given(spiedFile).seek(anyLong()); + return spiedFile; }).given(spiedPool).acquire(); for (int i = 0; i < 5; i++) { 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 549ca05c3b..3043923201 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 @@ -228,14 +228,7 @@ public class StartMojo extends AbstractRunMojo { final SpringApplicationAdminClient client = new SpringApplicationAdminClient( connection, this.jmxName); try { - execute(this.wait, this.maxAttempts, new Callable() { - - @Override - public Boolean call() throws Exception { - return (client.isReady() ? true : null); - } - - }); + execute(this.wait, this.maxAttempts, () -> (client.isReady() ? true : null)); } catch (ReflectionException ex) { throw new MojoExecutionException("Unable to retrieve 'ready' attribute", diff --git a/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunner.java b/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunner.java index d09fcd5411..8f63774afe 100644 --- a/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunner.java +++ b/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunner.java @@ -83,13 +83,7 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { protected Object createTest() throws Exception { ModifiedClassPathTestClass testClass = (ModifiedClassPathTestClass) getTestClass(); return testClass.doWithModifiedClassPathThreadContextClassLoader( - new ModifiedClassPathTestClass.ModifiedClassPathTcclAction() { - - @Override - public Object perform() throws Exception { - return ModifiedClassPathRunner.super.createTest(); - } - }); + () -> ModifiedClassPathRunner.super.createTest()); } private URLClassLoader createTestClassLoader(Class testClass) throws Exception { @@ -299,15 +293,8 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { public Object invokeExplosively(final Object target, final Object... params) throws Throwable { return doWithModifiedClassPathThreadContextClassLoader( - new ModifiedClassPathTcclAction() { - - @Override - public Object perform() throws Throwable { - return ModifiedClassPathFrameworkMethod.super.invokeExplosively( - target, params); - } - - }); + () -> ModifiedClassPathFrameworkMethod.super.invokeExplosively( + target, params)); } } diff --git a/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/MockServletWebServer.java b/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/MockServletWebServer.java index 4916c1471e..75df408649 100644 --- a/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/MockServletWebServer.java +++ b/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/MockServletWebServer.java @@ -32,9 +32,6 @@ import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; @@ -70,50 +67,31 @@ public abstract class MockServletWebServer { try { this.servletContext = mock(ServletContext.class); given(this.servletContext.addServlet(anyString(), (Servlet) any())) - .willAnswer(new Answer() { - @Override - public ServletRegistration.Dynamic answer( - InvocationOnMock invocation) throws Throwable { - RegisteredServlet registeredServlet = new RegisteredServlet( - (Servlet) invocation.getArguments()[1]); - MockServletWebServer.this.registeredServlets - .add(registeredServlet); - return registeredServlet.getRegistration(); - } + .willAnswer((invocation) -> { + RegisteredServlet registeredServlet = new RegisteredServlet( + (Servlet) invocation.getArguments()[1]); + MockServletWebServer.this.registeredServlets + .add(registeredServlet); + return registeredServlet.getRegistration(); }); given(this.servletContext.addFilter(anyString(), (Filter) any())) - .willAnswer(new Answer() { - @Override - public FilterRegistration.Dynamic answer( - InvocationOnMock invocation) throws Throwable { - RegisteredFilter registeredFilter = new RegisteredFilter( - (Filter) invocation.getArguments()[1]); - MockServletWebServer.this.registeredFilters - .add(registeredFilter); - return registeredFilter.getRegistration(); - } + .willAnswer((invocation) -> { + RegisteredFilter registeredFilter = new RegisteredFilter( + (Filter) invocation.getArguments()[1]); + MockServletWebServer.this.registeredFilters.add(registeredFilter); + return registeredFilter.getRegistration(); }); final Map initParameters = new HashMap<>(); given(this.servletContext.setInitParameter(anyString(), anyString())) - .will(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - initParameters.put(invocation.getArgument(0), - invocation.getArgument(1)); - return null; - } - + .will((invocation) -> { + initParameters.put(invocation.getArgument(0), + invocation.getArgument(1)); + return null; }); given(this.servletContext.getInitParameterNames()) .willReturn(Collections.enumeration(initParameters.keySet())); - given(this.servletContext.getInitParameter(anyString())) - .willAnswer(new Answer() { - @Override - public String answer(InvocationOnMock invocation) - throws Throwable { - return initParameters.get(invocation.getArgument(0)); - } - }); + given(this.servletContext.getInitParameter(anyString())).willAnswer( + (invocation) -> initParameters.get(invocation.getArgument(0))); given(this.servletContext.getAttributeNames()) .willReturn(MockServletWebServer.emptyEnumeration()); given(this.servletContext.getNamedDispatcher("default")) diff --git a/spring-boot/src/main/java/org/springframework/boot/StartupInfoLogger.java b/spring-boot/src/main/java/org/springframework/boot/StartupInfoLogger.java index ddc995a392..9ebf9580c8 100644 --- a/spring-boot/src/main/java/org/springframework/boot/StartupInfoLogger.java +++ b/spring-boot/src/main/java/org/springframework/boot/StartupInfoLogger.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 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. @@ -100,45 +100,20 @@ class StartupInfoLogger { } private String getVersion(final Class source) { - return getValue(" v", new Callable() { - @Override - public Object call() throws Exception { - return source.getPackage().getImplementationVersion(); - } - }, ""); + return getValue(" v", () -> source.getPackage().getImplementationVersion(), ""); } private String getOn() { - return getValue(" on ", new Callable() { - @Override - public Object call() throws Exception { - return InetAddress.getLocalHost().getHostName(); - } - }); + return getValue(" on ", () -> InetAddress.getLocalHost().getHostName()); } private String getPid() { - return getValue(" with PID ", new Callable() { - @Override - public Object call() throws Exception { - return System.getProperty("PID"); - } - }); + return getValue(" with PID ", () -> System.getProperty("PID")); } private String getContext() { - String startedBy = getValue("started by ", new Callable() { - @Override - public Object call() throws Exception { - return System.getProperty("user.name"); - } - }); - String in = getValue("in ", new Callable() { - @Override - public Object call() throws Exception { - return System.getProperty("user.dir"); - } - }); + String startedBy = getValue("started by ", () -> System.getProperty("user.name")); + String in = getValue("in ", () -> System.getProperty("user.dir")); ApplicationHome home = new ApplicationHome(this.sourceClass); String path = (home.getSource() == null ? "" : home.getSource().getAbsolutePath()); diff --git a/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationBeanFactoryMetaData.java b/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationBeanFactoryMetaData.java index 32f0bff7b4..42cc0b4b96 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationBeanFactoryMetaData.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationBeanFactoryMetaData.java @@ -28,7 +28,6 @@ import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.util.ReflectionUtils; -import org.springframework.util.ReflectionUtils.MethodCallback; /** * Utility class to memorize {@code @Bean} definition meta data during initialization of @@ -82,13 +81,9 @@ public class ConfigurationBeanFactoryMetaData implements BeanFactoryPostProcesso MetaData meta = this.beans.get(beanName); final String factory = meta.getMethod(); Class type = this.beanFactory.getType(meta.getBean()); - ReflectionUtils.doWithMethods(type, new MethodCallback() { - @Override - public void doWith(Method method) - throws IllegalArgumentException, IllegalAccessException { - if (method.getName().equals(factory)) { - found.compareAndSet(null, method); - } + ReflectionUtils.doWithMethods(type, (method) -> { + if (method.getName().equals(factory)) { + found.compareAndSet(null, method); } }); return found.get(); diff --git a/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Binder.java b/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Binder.java index 1cdceca65d..e258563429 100644 --- a/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Binder.java +++ b/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Binder.java @@ -267,8 +267,8 @@ public class Binder { private Object bindAggregate(ConfigurationPropertyName name, Bindable target, BindHandler handler, Context context, AggregateBinder aggregateBinder) { AggregateElementBinder elementBinder = (itemName, itemTarget, source) -> { - return context.withSource(source, - () -> Binder.this.bind(itemName, itemTarget, handler, context)); + Supplier supplier = () -> bind(itemName, itemTarget, handler, context); + return context.withSource(source, supplier); }; return context.withIncreasedDepth( () -> aggregateBinder.bind(name, target, elementBinder)); diff --git a/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedYamlLoader.java b/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedYamlLoader.java index a11aa76ad2..d5415e18e8 100644 --- a/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedYamlLoader.java +++ b/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedYamlLoader.java @@ -79,9 +79,7 @@ class OriginTrackedYamlLoader extends YamlProcessor { public Map load() { final Map result = new LinkedHashMap<>(); - process((properties, map) -> { - result.putAll(getFlattenedMap(map)); - }); + process((properties, map) -> result.putAll(getFlattenedMap(map))); return result; } diff --git a/spring-boot/src/main/java/org/springframework/boot/web/context/ServerPortInfoApplicationContextInitializer.java b/spring-boot/src/main/java/org/springframework/boot/web/context/ServerPortInfoApplicationContextInitializer.java index 5d2555eb42..33445c8d81 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/context/ServerPortInfoApplicationContextInitializer.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/context/ServerPortInfoApplicationContextInitializer.java @@ -23,7 +23,6 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.server.WebServer; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextInitializer; -import org.springframework.context.ApplicationListener; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; @@ -54,15 +53,7 @@ public class ServerPortInfoApplicationContextInitializer @Override public void initialize(ConfigurableApplicationContext applicationContext) { applicationContext.addApplicationListener( - new ApplicationListener() { - - @Override - public void onApplicationEvent(WebServerInitializedEvent event) { - ServerPortInfoApplicationContextInitializer.this - .onApplicationEvent(event); - } - - }); + (WebServerInitializedEvent event) -> onApplicationEvent(event)); } protected void onApplicationEvent(WebServerInitializedEvent event) { diff --git a/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactory.java b/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactory.java index 9674e3ab7f..1d231f8513 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactory.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactory.java @@ -50,7 +50,6 @@ import javax.servlet.ServletException; import io.undertow.Undertow; import io.undertow.Undertow.Builder; -import io.undertow.server.HandlerWrapper; import io.undertow.server.HttpHandler; import io.undertow.server.handlers.accesslog.AccessLogHandler; import io.undertow.server.handlers.accesslog.AccessLogReceiver; @@ -418,14 +417,7 @@ public class UndertowServletWebServerFactory extends AbstractServletWebServerFac } private void configureAccessLog(DeploymentInfo deploymentInfo) { - deploymentInfo.addInitialHandlerChainWrapper(new HandlerWrapper() { - - @Override - public HttpHandler wrap(HttpHandler handler) { - return createAccessLogHandler(handler); - } - - }); + deploymentInfo.addInitialHandlerChainWrapper(this::createAccessLogHandler); } private AccessLogHandler createAccessLogHandler(HttpHandler handler) { diff --git a/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java b/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java index 15a467a82d..ee02b375c3 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java @@ -218,15 +218,9 @@ public class ServletContextInitializerBeans private List> getOrderedBeansOfType( ListableBeanFactory beanFactory, Class type, Set excludes) { List> beans = new ArrayList<>(); - Comparator> comparator = new Comparator>() { - - @Override - public int compare(Entry o1, Entry o2) { - return AnnotationAwareOrderComparator.INSTANCE.compare(o1.getValue(), + Comparator> comparator = (o1, + o2) -> AnnotationAwareOrderComparator.INSTANCE.compare(o1.getValue(), o2.getValue()); - } - - }; String[] names = beanFactory.getBeanNamesForType(type, true, false); Map map = new LinkedHashMap<>(); for (String name : names) { diff --git a/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContext.java b/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContext.java index d24099ebc9..6f7202eee7 100644 --- a/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContext.java +++ b/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContext.java @@ -203,12 +203,7 @@ public class ServletWebServerApplicationContext extends GenericWebApplicationCon * @see #prepareWebApplicationContext(ServletContext) */ private org.springframework.boot.web.servlet.ServletContextInitializer getSelfInitializer() { - return new ServletContextInitializer() { - @Override - public void onStartup(ServletContext servletContext) throws ServletException { - selfInitialize(servletContext); - } - }; + return this::selfInitialize; } private void selfInitialize(ServletContext servletContext) throws ServletException { diff --git a/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java b/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java index bbed22a8a8..c24732b6f0 100644 --- a/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.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. @@ -103,16 +103,11 @@ public class ExitCodeGeneratorsTests { private ExitCodeExceptionMapper mockMapper(final Class exceptionType, final int exitCode) { - return new ExitCodeExceptionMapper() { - - @Override - public int getExitCode(Throwable exception) { - if (exceptionType.isInstance(exception)) { - return exitCode; - } - return 0; + return (exception) -> { + if (exceptionType.isInstance(exception)) { + return exitCode; } - + return 0; }; } diff --git a/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java b/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java index 5b2923fd8e..16f9b3d5f9 100644 --- a/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java @@ -30,6 +30,7 @@ import java.util.concurrent.atomic.AtomicReference; import javax.annotation.PostConstruct; +import org.assertj.core.api.Assertions; import org.assertj.core.api.Condition; import org.junit.After; import org.junit.Before; @@ -313,12 +314,7 @@ public class SpringApplicationTests { application.setWebApplicationType(WebApplicationType.NONE); final AtomicReference reference = new AtomicReference<>(); application.setInitializers(Arrays.asList( - new ApplicationContextInitializer() { - @Override - public void initialize(ConfigurableApplicationContext context) { - reference.set(context); - } - })); + (ApplicationContextInitializer) reference::set)); this.context = application.run("--foo=bar"); assertThat(this.context).isSameAs(reference.get()); // Custom initializers do not switch off the defaults @@ -638,14 +634,8 @@ public class SpringApplicationTests { application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run(); assertThat(this.context).isNotNull(); - assertThat(SpringApplication.exit(this.context, new ExitCodeGenerator() { - - @Override - public int getExitCode() { - return 2; - } - - })).isEqualTo(2); + assertThat(SpringApplication.exit(this.context, (ExitCodeGenerator) () -> 2)) + .isEqualTo(2); assertThat(listener.getExitCode()).isEqualTo(2); } @@ -764,14 +754,7 @@ public class SpringApplicationTests { ListenerConfig.class); application.setApplicationContextClass(SpyApplicationContext.class); final LinkedHashSet events = new LinkedHashSet<>(); - application.addListeners(new ApplicationListener() { - - @Override - public void onApplicationEvent(ApplicationEvent event) { - events.add(event); - } - - }); + application.addListeners((ApplicationListener) events::add); this.context = application.run(); assertThat(events).hasAtLeastOneElementOfType(ApplicationPreparedEvent.class); assertThat(events).hasAtLeastOneElementOfType(ContextRefreshedEvent.class); @@ -784,14 +767,7 @@ public class SpringApplicationTests { ListenerConfig.class, Multicaster.class); application.setApplicationContextClass(SpyApplicationContext.class); final LinkedHashSet events = new LinkedHashSet<>(); - application.addListeners(new ApplicationListener() { - - @Override - public void onApplicationEvent(ApplicationEvent event) { - events.add(event); - } - - }); + application.addListeners((ApplicationListener) events::add); this.context = application.run(); assertThat(events).hasAtLeastOneElementOfType(ApplicationPreparedEvent.class); assertThat(events).hasAtLeastOneElementOfType(ContextRefreshedEvent.class); @@ -857,9 +833,8 @@ public class SpringApplicationTests { final ApplicationListener listener = mock( ApplicationListener.class); SpringApplication application = new SpringApplication(ExampleConfig.class); - application.addInitializers((applicationContext) -> { - applicationContext.addApplicationListener(listener); - }); + application.addInitializers((applicationContext) -> applicationContext + .addApplicationListener(listener)); try { application.run(); fail("Run should have failed with an ApplicationContextException"); @@ -876,9 +851,8 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication( BrokenPostConstructConfig.class); application.setWebApplicationType(WebApplicationType.NONE); - application.addInitializers((applicationContext) -> { - applicationContext.addApplicationListener(listener); - }); + application.addInitializers((applicationContext) -> applicationContext + .addApplicationListener(listener)); try { application.run(); fail("Run should have failed with a BeanCreationException"); @@ -944,19 +918,13 @@ public class SpringApplicationTests { TestSpringApplication application = new TestSpringApplication( ExampleConfig.class); application.addListeners( - new ApplicationListener() { - - @Override - public void onApplicationEvent( - ApplicationEnvironmentPreparedEvent event) { - assertThat(event.getEnvironment()) - .isInstanceOf(StandardServletEnvironment.class); - TestPropertySourceUtils.addInlinedPropertiesToEnvironment( - event.getEnvironment(), "foo=bar"); - event.getSpringApplication() - .setWebApplicationType(WebApplicationType.NONE); - } - + (ApplicationListener) (event) -> { + Assertions.assertThat(event.getEnvironment()) + .isInstanceOf(StandardServletEnvironment.class); + TestPropertySourceUtils.addInlinedPropertiesToEnvironment( + event.getEnvironment(), "foo=bar"); + event.getSpringApplication() + .setWebApplicationType(WebApplicationType.NONE); }); this.context = application.run(); assertThat(this.context.getEnvironment()) @@ -1210,13 +1178,8 @@ public class SpringApplicationTests { @Bean public CommandLineRunner runner() { - return new CommandLineRunner() { - - @Override - public void run(String... args) throws Exception { - throw new IllegalStateException(new ExitStatusException()); - } - + return (args) -> { + throw new IllegalStateException(new ExitStatusException()); }; } @@ -1227,28 +1190,18 @@ public class SpringApplicationTests { @Bean public CommandLineRunner runner() { - return new CommandLineRunner() { - - @Override - public void run(String... args) throws Exception { - throw new IllegalStateException(); - } - + return (args) -> { + throw new IllegalStateException(); }; } @Bean public ExitCodeExceptionMapper exceptionMapper() { - return new ExitCodeExceptionMapper() { - - @Override - public int getExitCode(Throwable exception) { - if (exception instanceof IllegalStateException) { - return 11; - } - return 0; + return (exception) -> { + if (exception instanceof IllegalStateException) { + return 11; } - + return 0; }; } diff --git a/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java b/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java index 9651b0fdb2..34f85679bf 100644 --- a/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java @@ -32,7 +32,6 @@ import org.junit.rules.ExpectedException; import org.springframework.boot.SpringApplication; import org.springframework.boot.WebApplicationType; import org.springframework.boot.context.event.ApplicationReadyEvent; -import org.springframework.context.ApplicationListener; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -76,16 +75,13 @@ public class SpringApplicationAdminMXBeanRegistrarTests { final ObjectName objectName = createObjectName(OBJECT_NAME); SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); - application.addListeners(new ApplicationListener() { - @Override - public void onApplicationEvent(ContextRefreshedEvent event) { - try { - assertThat(isApplicationReady(objectName)).isFalse(); - } - catch (Exception ex) { - throw new IllegalStateException( - "Could not contact spring application admin bean", ex); - } + application.addListeners((ContextRefreshedEvent event) -> { + try { + assertThat(isApplicationReady(objectName)).isFalse(); + } + catch (Exception ex) { + throw new IllegalStateException( + "Could not contact spring application admin bean", ex); } }); this.context = application.run(); diff --git a/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java b/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java index ae8fa65f9c..e364aedc68 100644 --- a/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java @@ -26,7 +26,6 @@ import org.junit.Test; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.WebApplicationType; import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Configuration; @@ -294,11 +293,7 @@ public class SpringApplicationBuilderTests { public void initializersIncludeDefaults() throws Exception { SpringApplicationBuilder application = new SpringApplicationBuilder( ExampleConfig.class).web(WebApplicationType.NONE).initializers( - new ApplicationContextInitializer() { - @Override - public void initialize( - ConfigurableApplicationContext applicationContext) { - } + (ConfigurableApplicationContext applicationContext) -> { }); this.context = application.run(); assertThat(application.application().getInitializers()).hasSize(5); 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 366e266aa6..3c8f189be0 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 @@ -427,9 +427,7 @@ public class ConfigFileApplicationListenerTests { ApplicationPreparedEvent event = new ApplicationPreparedEvent( new SpringApplication(), new String[0], new AnnotationConfigApplicationContext()); - withDebugLogging(() -> { - this.initializer.onApplicationEvent(event); - }); + withDebugLogging(() -> this.initializer.onApplicationEvent(event)); String log = this.out.toString(); // First make sure that each profile got processed only once diff --git a/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java b/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java index 397229e1dd..ac18cad9d3 100644 --- a/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java @@ -602,14 +602,7 @@ public class LoggingApplicationListenerTests { @Override public Runnable getShutdownHandler() { - return new Runnable() { - - @Override - public void run() { - TestShutdownHandlerLoggingSystem.shutdownLatch.countDown(); - } - - }; + return () -> TestShutdownHandlerLoggingSystem.shutdownLatch.countDown(); } } diff --git a/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java index d56e516455..4f9b6f36ab 100644 --- a/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java @@ -49,14 +49,8 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { - private static final FileFilter SPRING_LOG_FILTER = new FileFilter() { - - @Override - public boolean accept(File pathname) { - return pathname.getName().startsWith("spring.log"); - } - - }; + private static final FileFilter SPRING_LOG_FILTER = (pathname) -> pathname.getName() + .startsWith("spring.log"); private final JavaLoggingSystem loggingSystem = new JavaLoggingSystem( getClass().getClassLoader()); diff --git a/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java b/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java index a2036f6ce7..96dd829596 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java @@ -361,14 +361,8 @@ public class RestTemplateBuilderTests { @Test public void customizersShouldBeAppliedLast() throws Exception { RestTemplate template = spy(new RestTemplate()); - this.builder.additionalCustomizers(new RestTemplateCustomizer() { - - @Override - public void customize(RestTemplate restTemplate) { - verify(restTemplate).setRequestFactory((ClientHttpRequestFactory) any()); - } - - }); + this.builder.additionalCustomizers((restTemplate) -> verify(restTemplate) + .setRequestFactory((ClientHttpRequestFactory) any())); this.builder.configure(template); } diff --git a/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactoryTests.java b/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactoryTests.java index 3b164ebb60..4ac283b561 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactoryTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactoryTests.java @@ -146,17 +146,11 @@ public class JettyServletWebServerFactoryTests @Override protected void addConnector(int port, AbstractServletWebServerFactory factory) { - ((JettyServletWebServerFactory) factory) - .addServerCustomizers(new JettyServerCustomizer() { - - @Override - public void customize(Server server) { - ServerConnector connector = new ServerConnector(server); - connector.setPort(port); - server.addConnector(connector); - } - - }); + ((JettyServletWebServerFactory) factory).addServerCustomizers((server) -> { + ServerConnector connector = new ServerConnector(server); + connector.setPort(port); + server.addConnector(connector); + }); } @Test @@ -222,16 +216,13 @@ public class JettyServletWebServerFactoryTests @Test public void wrappedHandlers() throws Exception { JettyServletWebServerFactory factory = getFactory(); - factory.setServerCustomizers(Arrays.asList(new JettyServerCustomizer() { - @Override - public void customize(Server server) { - Handler handler = server.getHandler(); - HandlerWrapper wrapper = new HandlerWrapper(); - wrapper.setHandler(handler); - HandlerCollection collection = new HandlerCollection(); - collection.addHandler(wrapper); - server.setHandler(collection); - } + factory.setServerCustomizers(Arrays.asList((server) -> { + Handler handler = server.getHandler(); + HandlerWrapper wrapper = new HandlerWrapper(); + wrapper.setHandler(handler); + HandlerCollection collection = new HandlerCollection(); + collection.addHandler(wrapper); + server.setHandler(collection); })); this.webServer = factory.getWebServer(exampleServletRegistration()); this.webServer.start(); @@ -273,15 +264,10 @@ public class JettyServletWebServerFactoryTests @Test public void startFailsWhenThreadPoolIsTooSmall() throws Exception { JettyServletWebServerFactory factory = getFactory(); - factory.addServerCustomizers(new JettyServerCustomizer() { - - @Override - public void customize(Server server) { - QueuedThreadPool threadPool = server.getBean(QueuedThreadPool.class); - threadPool.setMaxThreads(2); - threadPool.setMinThreads(2); - } - + factory.addServerCustomizers((server) -> { + QueuedThreadPool threadPool = server.getBean(QueuedThreadPool.class); + threadPool.setMaxThreads(2); + threadPool.setMinThreads(2); }); this.thrown.expectCause(isA(IllegalStateException.class)); factory.getWebServer().start(); diff --git a/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactoryTests.java b/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactoryTests.java index 1b32b6af26..917bbe2cf7 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactoryTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactoryTests.java @@ -316,24 +316,17 @@ public class TomcatServletWebServerFactoryTests @Test public void primaryConnectorPortClashThrowsIllegalStateException() throws InterruptedException, IOException { - doWithBlockedPort(new BlockedPortAction() { - - @Override - public void run(int port) { - TomcatServletWebServerFactory factory = getFactory(); - factory.setPort(port); - - try { - TomcatServletWebServerFactoryTests.this.webServer = factory - .getWebServer(); - TomcatServletWebServerFactoryTests.this.webServer.start(); - fail(); - } - catch (WebServerException ex) { - // Ignore - } + doWithBlockedPort((port) -> { + TomcatServletWebServerFactory factory = getFactory(); + factory.setPort(port); + try { + this.webServer = factory.getWebServer(); + this.webServer.start(); + fail(); + } + catch (WebServerException ex) { + // Ignore } - }); } diff --git a/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactoryTests.java b/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactoryTests.java index 16f08e53a2..c3e90a0078 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactoryTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactoryTests.java @@ -154,13 +154,8 @@ public class UndertowServletWebServerFactoryTests public void defaultContextPath() throws Exception { UndertowServletWebServerFactory factory = getFactory(); final AtomicReference contextPath = new AtomicReference<>(); - factory.addDeploymentInfoCustomizers(new UndertowDeploymentInfoCustomizer() { - - @Override - public void customize(DeploymentInfo deploymentInfo) { - contextPath.set(deploymentInfo.getContextPath()); - } - }); + factory.addDeploymentInfoCustomizers( + (deploymentInfo) -> contextPath.set(deploymentInfo.getContextPath())); this.webServer = factory.getWebServer(); assertThat(contextPath.get()).isEqualTo("/"); } @@ -210,14 +205,8 @@ public class UndertowServletWebServerFactoryTests @Override protected void addConnector(final int port, AbstractServletWebServerFactory factory) { - ((UndertowServletWebServerFactory) factory) - .addBuilderCustomizers(new UndertowBuilderCustomizer() { - - @Override - public void customize(Builder builder) { - builder.addHttpListener(port, "0.0.0.0"); - } - }); + ((UndertowServletWebServerFactory) factory).addBuilderCustomizers( + (builder) -> builder.addHttpListener(port, "0.0.0.0")); } @Test(expected = SSLHandshakeException.class) 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 0e06654aab..6b52395c56 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 @@ -19,7 +19,6 @@ package org.springframework.boot.web.servlet.server; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; -import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; @@ -219,16 +218,13 @@ public abstract class AbstractServletWebServerFactoryTests { public void startBlocksUntilReadyToServe() throws Exception { AbstractServletWebServerFactory factory = getFactory(); final Date[] date = new Date[1]; - this.webServer = factory.getWebServer(new ServletContextInitializer() { - @Override - public void onStartup(ServletContext servletContext) throws ServletException { - try { - Thread.sleep(500); - date[0] = new Date(); - } - catch (InterruptedException ex) { - throw new ServletException(ex); - } + this.webServer = factory.getWebServer((servletContext) -> { + try { + Thread.sleep(500); + date[0] = new Date(); + } + catch (InterruptedException ex) { + throw new ServletException(ex); } }); this.webServer.start(); @@ -239,12 +235,8 @@ public abstract class AbstractServletWebServerFactoryTests { public void loadOnStartAfterContextIsInitialized() throws Exception { AbstractServletWebServerFactory factory = getFactory(); final InitCountingServlet servlet = new InitCountingServlet(); - this.webServer = factory.getWebServer(new ServletContextInitializer() { - @Override - public void onStartup(ServletContext servletContext) throws ServletException { - servletContext.addServlet("test", servlet).setLoadOnStartup(1); - } - }); + this.webServer = factory.getWebServer((servletContext) -> servletContext + .addServlet("test", servlet).setLoadOnStartup(1)); assertThat(servlet.getInitCount()).isEqualTo(0); this.webServer.start(); assertThat(servlet.getInitCount()).isEqualTo(1); @@ -739,14 +731,8 @@ public abstract class AbstractServletWebServerFactoryTests { this.webServer.start(); getResponse(getLocalUrl("/session")); this.webServer.stop(); - File[] dirContents = sessionStoreDir.listFiles(new FilenameFilter() { - - @Override - public boolean accept(File dir, String name) { - return !(".".equals(name) || "..".equals(name)); - } - - }); + File[] dirContents = sessionStoreDir + .listFiles((dir, name) -> !(".".equals(name) || "..".equals(name))); assertThat(dirContents.length).isGreaterThan(0); } @@ -843,15 +829,12 @@ public abstract class AbstractServletWebServerFactoryTests { public void rootServletContextResource() throws Exception { AbstractServletWebServerFactory factory = getFactory(); final AtomicReference rootResource = new AtomicReference<>(); - this.webServer = factory.getWebServer(new ServletContextInitializer() { - @Override - public void onStartup(ServletContext servletContext) throws ServletException { - try { - rootResource.set(servletContext.getResource("/")); - } - catch (MalformedURLException ex) { - throw new ServletException(ex); - } + this.webServer = factory.getWebServer((servletContext) -> { + try { + rootResource.set(servletContext.getResource("/")); + } + catch (MalformedURLException ex) { + throw new ServletException(ex); } }); this.webServer.start(); @@ -880,47 +863,37 @@ public abstract class AbstractServletWebServerFactoryTests { @Test public void portClashOfPrimaryConnectorResultsInPortInUseException() throws IOException { - doWithBlockedPort(new BlockedPortAction() { - - @Override - public void run(int port) { - try { - AbstractServletWebServerFactory factory = getFactory(); - factory.setPort(port); - AbstractServletWebServerFactoryTests.this.webServer = factory - .getWebServer(); - AbstractServletWebServerFactoryTests.this.webServer.start(); - fail(); - } - catch (RuntimeException ex) { - handleExceptionCausedByBlockedPort(ex, port); - } + doWithBlockedPort((port) -> { + try { + AbstractServletWebServerFactory factory = getFactory(); + factory.setPort(port); + AbstractServletWebServerFactoryTests.this.webServer = factory + .getWebServer(); + AbstractServletWebServerFactoryTests.this.webServer.start(); + fail(); + } + catch (RuntimeException ex) { + handleExceptionCausedByBlockedPort(ex, port); } - }); } @Test public void portClashOfSecondaryConnectorResultsInPortInUseException() throws IOException { - doWithBlockedPort(new BlockedPortAction() { - - @Override - public void run(int port) { - try { - AbstractServletWebServerFactory factory = getFactory(); - factory.setPort(SocketUtils.findAvailableTcpPort(40000)); - addConnector(port, factory); - AbstractServletWebServerFactoryTests.this.webServer = factory - .getWebServer(); - AbstractServletWebServerFactoryTests.this.webServer.start(); - fail(); - } - catch (RuntimeException ex) { - handleExceptionCausedByBlockedPort(ex, port); - } + doWithBlockedPort((port) -> { + try { + AbstractServletWebServerFactory factory = getFactory(); + factory.setPort(SocketUtils.findAvailableTcpPort(40000)); + addConnector(port, factory); + AbstractServletWebServerFactoryTests.this.webServer = factory + .getWebServer(); + AbstractServletWebServerFactoryTests.this.webServer.start(); + fail(); + } + catch (RuntimeException ex) { + handleExceptionCausedByBlockedPort(ex, port); } - }); } @@ -961,11 +934,8 @@ public abstract class AbstractServletWebServerFactoryTests { @Test public void faultyFilterCausesStartFailure() throws Exception { AbstractServletWebServerFactory factory = getFactory(); - factory.addInitializers(new ServletContextInitializer() { - - @Override - public void onStartup(ServletContext servletContext) throws ServletException { - servletContext.addFilter("faulty", new Filter() { + factory.addInitializers( + (servletContext) -> servletContext.addFilter("faulty", new Filter() { @Override public void init(FilterConfig filterConfig) throws ServletException { @@ -982,10 +952,7 @@ public abstract class AbstractServletWebServerFactoryTests { public void destroy() { } - }); - } - - }); + })); this.thrown.expect(WebServerException.class); factory.getWebServer().start(); } diff --git a/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/MockServletWebServerFactory.java b/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/MockServletWebServerFactory.java index 0adaaa4452..a6cb6a05aa 100644 --- a/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/MockServletWebServerFactory.java +++ b/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/MockServletWebServerFactory.java @@ -67,7 +67,7 @@ public class MockServletWebServerFactory extends AbstractServletWebServerFactory public MockServletWebServer(ServletContextInitializer[] initializers, int port) { super(Arrays.stream(initializers) - .map((i) -> (Initializer) (s) -> i.onStartup(s)) + .map((initializer) -> (Initializer) initializer::onStartup) .toArray(Initializer[]::new), port); } 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 8094a14346..ba8473488a 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 @@ -17,7 +17,6 @@ package org.springframework.boot.web.servlet.support; import javax.servlet.ServletContext; -import javax.servlet.ServletException; import org.junit.Rule; import org.junit.Test; @@ -28,7 +27,6 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory; import org.springframework.boot.web.server.WebServer; -import org.springframework.boot.web.servlet.ServletContextInitializer; import org.springframework.boot.web.servlet.server.ServletWebServerFactory; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; @@ -97,16 +95,11 @@ public class SpringBootServletInitializerTests { @Test public void errorPageFilterRegistrationCanBeDisabled() throws Exception { WebServer webServer = new UndertowServletWebServerFactory(0) - .getWebServer(new ServletContextInitializer() { - - @Override - public void onStartup(ServletContext servletContext) - throws ServletException { - try (AbstractApplicationContext context = (AbstractApplicationContext) new WithErrorPageFilterNotRegistered() - .createRootApplicationContext(servletContext)) { - assertThat(context.getBeansOfType(ErrorPageFilter.class)) - .hasSize(0); - } + .getWebServer((servletContext) -> { + try (AbstractApplicationContext context = (AbstractApplicationContext) new WithErrorPageFilterNotRegistered() + .createRootApplicationContext(servletContext)) { + assertThat(context.getBeansOfType(ErrorPageFilter.class)) + .hasSize(0); } }); try { From 687464e9823911b502186b61032239f90adf8d5d Mon Sep 17 00:00:00 2001 From: Emanuel Campolo Date: Tue, 18 Jul 2017 13:52:42 -0300 Subject: [PATCH 6/6] Simplify comparator implementation See gh-9781 --- .../boot/cli/command/options/OptionHandler.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java index 677b8ee7a8..29d1972d15 100644 --- a/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java +++ b/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java @@ -130,8 +130,8 @@ public class OptionHandler { @Override public String format(Map options) { - Comparator comparator = (first, second) -> first.options() - .iterator().next().compareTo(second.options().iterator().next()); + Comparator comparator = Comparator.comparing( + (optionDescriptor) -> optionDescriptor.options().iterator().next()); Set sorted = new TreeSet<>(comparator); sorted.addAll(options.values()); for (OptionDescriptor descriptor : sorted) {