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 bd452e2cca21..421b442416cc 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 @@ -175,15 +175,10 @@ public void endpoints() throws Exception { .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); - } - + .andDo(mvcResult -> { + EndpointDoc endpoint1 = new EndpointDoc(docs, + endpointPath); + endpoints.add(endpoint1); }); } } @@ -199,12 +194,8 @@ public void handle(MvcResult mvcResult) throws Exception { private Collection getEndpoints() { List endpoints = new ArrayList<>( this.mvcEndpoints.getEndpoints()); - Collections.sort(endpoints, new Comparator() { - @Override - public int compare(MvcEndpoint o1, MvcEndpoint o2) { - return o1.getPath().compareTo(o2.getPath()); - } - }); + endpoints.sort( + (Comparator.comparing(MvcEndpoint::getPath))); return endpoints; } 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 71e1a276de17..881b1e00f269 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 @@ -137,15 +137,11 @@ static class NoOpCacheStatisticsConfiguration { @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/EndpointAutoConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointAutoConfiguration.java index 357dacd43367..aed327ccab50 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 MetricsEndpoint metricsEndpoint() { 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/autoconfigure/EndpointWebMvcAutoConfiguration.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfiguration.java index 84b84fdd42a4..ec81ef731edc 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 ManagementContextResolver managementContextResolver() { @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 1aca690d5c5a..2e839e831998 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/autoconfigure/ManagementServerProperties.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/autoconfigure/ManagementServerProperties.java index b8b101697454..2ec0b4910cf2 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 static class Security { /** * 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/cache/AbstractJmxCacheStatisticsProvider.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/AbstractJmxCacheStatisticsProvider.java index 418ce193ff86..d922a8ef1121 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 @@ protected T getAttribute(ObjectName objectName, String attributeName, 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-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 3a8c4cac00a0..d34455cf52e1 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 PropertyResolver getResolver() { } 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/endpoint/ShutdownEndpoint.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/ShutdownEndpoint.java index a64c7a42b6ee..949aa76e07ff 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 @@ -62,17 +62,14 @@ public Map invoke() { 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(() -> { + try { + Thread.sleep(500L); } + catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } + ShutdownEndpoint.this.context.close(); }); thread.setContextClassLoader(getClass().getClassLoader()); thread.start(); 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 7018ad18cf74..5e5f4c2cbb1b 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/health/DataSourceHealthIndicator.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/DataSourceHealthIndicator.java index 51b6e3353a3d..033ad39177e9 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 @@ -16,7 +16,6 @@ package org.springframework.boot.actuate.health; -import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; @@ -26,7 +25,6 @@ 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 +118,8 @@ private void doDataSourceHealthCheck(Health.Builder builder) throws Exception { } 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) connection -> connection.getMetaData().getDatabaseProductName()); } protected String getValidationQuery(String product) { 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 cb1b52ade3fb..9a05319486e8 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 @@ import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; import java.util.Comparator; import java.util.List; @@ -80,7 +79,7 @@ protected Status aggregateStatus(List candidates) { 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-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 cf6d4935b7a4..e5f16231eb8a 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 @@ -18,9 +18,6 @@ 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,13 +43,10 @@ protected void doHealthCheck(Health.Builder builder) throws Exception { } 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 -> { + Map serverProperties = channel.getConnection() + .getServerProperties(); + return serverProperties.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 5ea7b957b2ee..15275cfee9c9 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 @@ 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; @@ -81,14 +80,7 @@ private Iterable> findAll(Predicate predicate) { 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) { 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 29cacda9357f..44dbf5b811fa 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 @@ 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; /** @@ -35,15 +34,10 @@ abstract class Buffers> { 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); - } + this.buffers.forEach((name, value) -> { + if (predicate.test(name)) { + consumer.accept(name, value); } - }); } @@ -58,12 +52,7 @@ public int count() { protected final void doWith(final String name, final 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, name1 -> 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 ef7b3855d486..ba5b8bc0ee16 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 @@ -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}. * @@ -27,26 +25,16 @@ 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); - } - + 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(); - } - + 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 d3302a924f42..6291105b1cf9 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 @@ -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}. * @@ -27,12 +25,9 @@ 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); - } + 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 2d7f79871b16..51d23687021c 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 ae7f04d15162..76a9da69883e 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 @@ 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 Metric findOne(String metricName) { @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 d4e8d66a33ad..f0c4d300d95a 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 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 void increment(Delta delta) { 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 b1aff342a5c7..284fff8226c3 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 @@ 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; @@ -37,18 +36,13 @@ public class InMemoryRichGaugeRepository implements RichGaugeRepository { @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; + 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 RichGauge modify(RichGauge current) { 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/main/java/org/springframework/boot/actuate/trace/WebRequestTraceFilter.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/trace/WebRequestTraceFilter.java index 78cf2b563067..f8066711a701 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 @@ private Object getHeaderValue(HttpServletRequest request, String name) { } 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/autoconfigure/EndpointAutoConfigurationTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointAutoConfigurationTests.java index 668167341f49..895f77860c3f 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 @@ static class CustomPublicMetricsConfig { @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 @@ static class CustomInfoContributorsConfig { @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 cf56833f0167..84d6e99d6f3a 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.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 HttpMessageConverters messageConverters() { @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 118a3e1ac087..fbcec538144e 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 static class DifferentPortConfig { @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 b7573c4f1776..3dcf2eb25caa 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 @@ -418,12 +418,7 @@ protected static class CustomHealthIndicator { @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 a9c8c953e036..96b12b04f33c 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 @@ static class CustomInfoContributorConfiguration { @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 65646e782c11..36dfb6fd189e 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.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,7 @@ protected static class TestConfiguration { @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 ac29bd75e3bf..3ac9f8c3df72 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.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 static class MessageChannelConfiguration { @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 4b6ce78750bc..d599f6670e22 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.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 void recordsHttpInteractions() throws Exception { "/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 void additionallyRecordsMetricsWithHttpMethodNameIfConfigured() "/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 void doesNotRecordRolledUpMetricsIfConfigured() throws Exception { "/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 void whenExceptionIsThrownResponseStatusIsUsedWhenResponseHasBeenCommitte "/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,13 @@ public String testException() { @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 +506,13 @@ public void run() { @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 f4d31386366d..19ce5848db6d 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.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; @@ -144,13 +142,7 @@ public void multipleDataSources() { // 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", 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 77f61c24c95a..8c9dc714c944 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 @@ -26,7 +26,6 @@ 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 @@ private static class TestMvcEndpoint extends EndpointMvcAdapter { 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/CachePublicMetricsTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/CachePublicMetricsTests.java index 9986fbbe4fc7..fbeaac45d1ff 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 @@ */ public class CachePublicMetricsTests { - private Map cacheManagers = new HashMap(); + private Map cacheManagers = new HashMap<>(); @Before public void setup() { @@ -98,7 +98,7 @@ public void cacheMetricsWithTransactionAwareCacheDecorator() { 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 b4a8bdae6a02..37f8da43b567 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 void setAddress(InetAddress address) { 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 72ec5333fc0b..9577dadc2672 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 void propertyWithTypeOtherThanStringShouldNotFail() throws Exception { this.context = new AnnotationConfigApplicationContext(); MutablePropertySources propertySources = 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.context.register(Config.class); 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 84c40c73f9cb..eb5884a7630c 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 @@ -61,13 +61,7 @@ public HealthEndpoint endpoint(HealthAggregator healthAggregator, @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 20dafc229d38..05a5bfcf0f85 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 @@ -21,7 +21,6 @@ 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 static class Config { @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 200d8a3d6303..dae5e524508f 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 @@ -101,12 +101,7 @@ public static class Config { @Bean public MetricsEndpoint endpoint() { final Metric metric = new Metric<>("a", 0.5f); - PublicMetrics metrics = new PublicMetrics() { - @Override - public Collection> metrics() { - return Collections.>singleton(metric); - } - }; + PublicMetrics metrics = () -> Collections.>singleton(metric); return new MetricsEndpoint(metrics); } 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 93d6f24577b6..9ad36d6aa473 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 @@ -88,15 +88,10 @@ public ShutdownEndpoint endpoint() { @Bean public ApplicationListener listener() { - return new ApplicationListener() { - - @Override - public void onApplicationEvent(ContextClosedEvent event) { - Config.this.threadContextClassLoader = Thread.currentThread() - .getContextClassLoader(); - Config.this.latch.countDown(); - } - + return event -> { + Config.this.threadContextClassLoader = Thread.currentThread() + .getContextClassLoader(); + Config.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 256f8ab29a4b..33bdb0763c90 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 ShutdownEndpoint endpoint() { @Bean public ApplicationListener listener() { - return new ApplicationListener() { - @Override - public void onApplicationEvent(ContextClosedEvent event) { - Config.this.latch.countDown(); - } - }; + return event -> Config.this.latch.countDown(); } 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 fe22fdbc6ae3..12572e9f778c 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 void regex() throws Exception { @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 void nestedPathWhenPlaceholderCannotBeResolvedShouldReturnUnresolvedPrope @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 void nestedPathWithSensitivePlaceholderShouldSanitize() throws Exception 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/endpoint/mvc/HeapdumpMvcEndpointSecureOptionsTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HeapdumpMvcEndpointSecureOptionsTests.java index bb496b6119ea..138e7ce3b7a2 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,18 @@ public void reset() { @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(TestHeapdumpMvcEndpoint.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 3f20a25220a7..e482d341581c 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,18 @@ public void reset() { @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(TestHeapdumpMvcEndpoint.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 d23a817d39e5..27be43bb28b8 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.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 InfoEndpoint endpoint() { @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 7e4e21d863fe..c59af65e2e72 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.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 static class TestConfiguration { @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 122a7d039e04..49dacc3185d1 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.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 void healthDetailPresent() throws Exception { } 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 @@ static class TestConfiguration { @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 908c73f70453..d6caa79e9d50 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 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 void setApplicationContext(ApplicationContext context) 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 322f1d97b0b7..58b9fd734230 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.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.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; @@ -98,21 +95,11 @@ public void raw(String input) throws Exception { 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); - } - }); + (name1, value) -> err.println(name1 + "=" + value)); } final 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 void reader(String input) throws Exception { 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); - } - }); + this.reader.findAll().forEach(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(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 void accept(Metric value) { 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 0722c5f67e20..9063797c16a9 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 @@ -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 f309fabd044e..0802d5581b7b 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.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.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; @@ -97,21 +94,11 @@ public void raw(String input) throws Exception { 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); - } - }); + (name1, value) -> err.println(name1 + "=" + value)); } final 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 void reader(String input) throws Exception { 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); - } - }); + this.reader.findAll().forEach(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(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 void accept(Metric value) { 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 4b9720705ba4..4fa74e5c4895 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.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.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 static void prime() throws FileNotFoundException { 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 void run() { 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); - } - }); + this.reader.findAll().forEach(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(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 bc869573af64..06f59aaf31a7 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.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.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; @@ -87,14 +85,11 @@ public static void prime() throws FileNotFoundException { 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 +103,9 @@ public void run() { 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); - } - }); + this.reader.findAll().forEach(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(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 3b547b2ca706..9c643bac4c16 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.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.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; @@ -89,14 +87,11 @@ public static void prime() throws FileNotFoundException { 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 +105,9 @@ public void run() { 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); - } - }); + this.reader.findAll().forEach(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(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 b409551aa42e..c69eee736f00 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 Set getValue() { @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/statsd/StatsdMetricWriterTests.java b/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/statsd/StatsdMetricWriterTests.java index 4bd5295825a7..936d4586f86a 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 void periodPrefix() throws Exception { @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 void incrementMetricWithInvalidCharsInName() throws Exception { @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-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 049a606dd49a..7b7fa33b478e 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 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 void setAndGet() { @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 @@ private static class RepositoryUpdate implements Callable { @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 be497c13c5f1..df3aebfc0de7 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.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 d2b9c8bdace0..9078f33c51cd 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 static class MockServletWebServer public MockServletWebServer(ServletContextInitializer[] initializers, int port) { super(Arrays.stream(initializers) - .map((i) -> (Initializer) (s) -> i.onStartup(s)) + .map((i) -> (Initializer) i::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 4f5c552b5d94..2a421b2c8a78 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.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 void filterAddsTraceWithCustomIncludes() throws IOException, ServletExcep 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, (request1, response1) -> { + BufferedReader bufferedReader = request1.getReader(); + while (bufferedReader.readLine() != null) { + // read the contents as normal (forces cache to fill up) } - + response1.getWriter().println("Goodbye, World!"); }); assertThat(this.repository.findAll()).hasSize(1); Map trace = this.repository.findAll().iterator().next().getInfo(); @@ -146,11 +130,7 @@ public void filterDoesNotAddResponseHeadersWithoutResponseHeadersInclude() 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, (request1, response1) -> { }); Map info = this.repository.findAll().iterator().next().getInfo(); Map headers = (Map) info.get("headers"); @@ -177,13 +157,7 @@ public void filterDoesNotAddAuthorizationHeaderWithoutAuthorizationHeaderInclude 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, (request1, response1) -> { }); Map info = this.repository.findAll().iterator().next().getInfo(); Map headers = (Map) info.get("headers"); @@ -199,13 +173,7 @@ public void filterAddsAuthorizationHeaderWhenAuthorizationHeaderIncluded() 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, (request1, response1) -> { }); Map info = this.repository.findAll().iterator().next().getInfo(); Map headers = (Map) info.get("headers"); @@ -279,14 +247,8 @@ public void filterHas500ResponseStatusWhenExceptionIsThrown() 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, (request1, response1) -> { + 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 2842a80419d9..22a4bc96cc8a 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.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 @@ public List getInPriorityOrder(Collection classNames) { // Initially sort alphabetically Collections.sort(orderedClassNames); // Then sort by order - Collections.sort(orderedClassNames, 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/ImportAutoConfigurationImportSelector.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelector.java index 539a7df92978..c3d3ce0675d8 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 @@ protected final Map, List> getAnnotations( 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/condition/OnBeanCondition.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnBeanCondition.java index b03dd47d0620..6e307d66827c 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 @@ private Collection getBeanNamesForType(ListableBeanFactory beanFactory, 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/condition/OnClassCondition.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnClassCondition.java index 6a3a42e556dd..eadc332b8daa 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 @@ private static final class ThreadedOutcomesResolver implements OutcomesResolver 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(() -> ThreadedOutcomesResolver.this.outcomes = outcomesResolver + .resolveOutcomes()); this.thread.start(); } 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 f4797969c784..2fe572e3d9d3 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 5423847ba067..407dac29ed2d 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 55849cf9ceb3..c917f8633f4e 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 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 fbc55fe7f5a2..90d39ccea74e 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 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/http/HttpMessageConverters.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/HttpMessageConverters.java index 69815b553ea5..44cef8b71365 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 @@ private static void addClassIfExists(List> list, String className) { 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/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 526c9994107d..dcd2950f0220 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 @@ -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 @@ static class TomcatDataSourcePoolMetadataProviderConfiguration { @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 @@ static class HikariPoolDataSourceMetadataProviderConfiguration { @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 @@ static class CommonsDbcp2PoolDataSourceMetadataProviderConfiguration { @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 c85d5f426f26..29b202af6b80 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 @@ static class JacksonResourceConfigCustomizer { 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/ldap/embedded/EmbeddedLdapAutoConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfiguration.java index e43fd0bf921b..c4605e9c101d 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 @@ private void setPortProperty(ApplicationContext context, int port) { 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 77d1eef6742c..725be1bd52a2 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 @@ private void setPortProperty(ApplicationContext currentContext, int port) { 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/main/java/org/springframework/boot/autoconfigure/security/SpringBootWebSecurityConfiguration.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/SpringBootWebSecurityConfiguration.java index cd243eaf034d..0439bb0e598e 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.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 @@ protected static class ApplicationNoWebSecurityConfigurerAdapter @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 45adb754d2c2..47c509cdac91 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 @@ protected static class AnonymousUserIdSourceConfig extends SocialConfigurerAdapt @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/reactive/function/client/WebClientCodecCustomizer.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/WebClientCodecCustomizer.java index d19647089918..153baf5b2a2f 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/WebClientCodecCustomizer.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/WebClientCodecCustomizer.java @@ -40,10 +40,8 @@ public WebClientCodecCustomizer(List codecCustomizers) { @Override public void customize(WebClient.Builder webClientBuilder) { webClientBuilder - .exchangeStrategies(ExchangeStrategies.builder().codecs(codecs -> { - this.codecCustomizers - .forEach((customizer) -> customizer.customize(codecs)); - }).build()); + .exchangeStrategies(ExchangeStrategies.builder().codecs(codecs -> this.codecCustomizers + .forEach((customizer) -> customizer.customize(codecs))).build()); } } 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 d7fe68ced3fe..f3c23dfbb32f 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.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; @@ -269,49 +266,34 @@ public static void customizeTomcat(ServerProperties serverProperties, 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((TomcatConnectorCustomizer) 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((TomcatConnectorCustomizer) 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((TomcatConnectorCustomizer) connector -> { + ProtocolHandler handler = connector.getProtocolHandler(); + if (handler instanceof AbstractProtocol) { + AbstractProtocol protocol = (AbstractProtocol) handler; + protocol.setConnectionTimeout(connectionTimeout); } - }); } @@ -342,64 +324,47 @@ private static void customizeRemoteIpValve(ServerProperties properties, @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((TomcatConnectorCustomizer) connector -> { + ProtocolHandler handler = connector.getProtocolHandler(); + if (handler instanceof AbstractProtocol) { + AbstractProtocol protocol = (AbstractProtocol) handler; + protocol.setMaxThreads(maxThreads); } + }); } @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((TomcatConnectorCustomizer) connector -> { + ProtocolHandler handler = connector.getProtocolHandler(); + if (handler instanceof AbstractProtocol) { + AbstractProtocol protocol = (AbstractProtocol) handler; + protocol.setMinSpareThreads(minSpareThreads); } + }); } @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((TomcatConnectorCustomizer) 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( + (TomcatConnectorCustomizer) connector -> connector.setMaxPostSize(maxHttpPostSize)); } private static void customizeAccessLog(ServerProperties.Tomcat tomcatProperties, @@ -422,14 +387,8 @@ private static void customizeAccessLog(ServerProperties.Tomcat tomcatProperties, private static void customizeRedirectContextRoot( TomcatServletWebServerFactory factory, final boolean redirectContextRoot) { - factory.addContextCustomizers(new TomcatContextCustomizer() { - - @Override - public void customize(Context context) { - context.setMapperContextRootRedirectEnabled(redirectContextRoot); - } - - }); + factory.addContextCustomizers( + (TomcatContextCustomizer) context -> context.setMapperContextRootRedirectEnabled(redirectContextRoot)); } } @@ -482,39 +441,20 @@ protected static void customizeUndertow(final ServerProperties serverProperties, 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((UndertowBuilderCustomizer) 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((UndertowBuilderCustomizer) 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((UndertowBuilderCustomizer) builder -> builder.setServerOption(UndertowOptions.MAX_ENTITY_SIZE, + maxHttpPostSize)); } } @@ -551,19 +491,14 @@ public static void customizeJetty(final ServerProperties serverProperties, 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((JettyServerCustomizer) 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 b1fe9465ebbe..4662535e62ca 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,7 +16,6 @@ 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; @@ -35,14 +34,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( + (TomcatContextCustomizer) 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 0c8804055b0c..a251da11f0fe 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 @@ protected List getAutoConfigurationImportFilters( @Override protected List getAutoConfigurationImportListeners() { return Collections.singletonList( - new AutoConfigurationImportListener() { - - @Override - public void onAutoConfigurationImportEvent( - AutoConfigurationImportEvent event) { - TestAutoConfigurationImportSelector.this.lastEvent = event; - } - - }); + event -> TestAutoConfigurationImportSelector.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 adad8fbb1ae9..dec590b34b32 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 @@ -23,7 +23,6 @@ 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,6 @@ 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 +76,7 @@ public void init() throws Exception { 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(); + this.step = this.steps.get("step").tasklet((contribution, chunkContext) -> null).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,12 +105,8 @@ public void incrementExistingExecution() throws Exception { @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"); - } + .start(this.steps.get("step").tasklet((contribution, chunkContext) -> { + throw new RuntimeException("Planned"); }).build()).incrementer(new RunIdIncrementer()).build(); this.runner.execute(this.job, new JobParameters()); this.runner.execute(this.job, new JobParameters()); @@ -130,12 +116,8 @@ public RepeatStatus execute(StepContribution contribution, @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"); - } + .start(this.steps.get("step").tasklet((contribution, chunkContext) -> { + throw new RuntimeException("Planned"); }).build()).incrementer(new RunIdIncrementer()).build(); this.runner.execute(this.job, new JobParameters()); this.runner.execute(this.job, new JobParameters()); @@ -147,12 +129,8 @@ public RepeatStatus execute(StepContribution contribution, @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"); - } + .start(this.steps.get("step").tasklet((contribution, chunkContext) -> { + throw new RuntimeException("Planned"); }).build()).incrementer(new RunIdIncrementer()).build(); JobParameters jobParameters = new JobParametersBuilder().addLong("id", 1L, false) .addLong("foo", 2L, false).toJobParameters(); 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 aa18a6fbb3b2..5fba495a8ce1 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 @@ 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; @@ -67,7 +66,6 @@ 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; @@ -937,16 +935,13 @@ static class JCacheWithCustomizerConfiguration { @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"); }; } @@ -1025,15 +1020,7 @@ static class CustomCacheResolverFromSupportConfiguration @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 63d9b500de05..3b1aa95fe646 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,7 +27,6 @@ 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; @@ -52,24 +51,17 @@ public CacheManager getCacheManager(URI uri, ClassLoader classLoader, 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(invocationOnMock -> { + String cacheName = (String) invocationOnMock.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((Answer) invocationOnMock -> { + String cacheName = (String) invocationOnMock.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 54cad5ae897e..46dba92b2dd9 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 @@ static class SimpleCustomizerConfig { @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/data/mongo/MongoDataAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java index 264aa0d326a7..3e133911dc4a 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.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 void interfaceFieldNamingStrategy() { 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-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 1296709c354e..ae1753b7320b 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 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 @@ static class BuilderCustomizer { @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 41ffc0fcbdef..f69807d4b7d8 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 @@ protected static class ObjectMapperBuilderCustomConfig { @Bean public Jackson2ObjectMapperBuilderCustomizer customDateFormat() { - return new Jackson2ObjectMapperBuilderCustomizer() { - @Override - public void customize( - Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder) { - jackson2ObjectMapperBuilder.dateFormat(new MyDateFormat()); - } - }; + return jackson2ObjectMapperBuilder -> jackson2ObjectMapperBuilder.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 9e3c49d9167a..71e923b47314 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 @@ -19,7 +19,6 @@ import java.io.IOException; import java.sql.SQLException; import java.util.Arrays; -import java.util.Comparator; import java.util.Random; import javax.sql.DataSource; @@ -350,14 +349,8 @@ public ClassLoader getClassLoader() { @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, + (r1, r2) -> r2.getFilename().compareTo(r1.getFilename())); 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 934d8150deb9..1a5d0ba4809d 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 @@ -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 void getPoolSizeNoConnection() { // Make sure the pool is initialized JdbcTemplate jdbcTemplate = new JdbcTemplate( getDataSourceMetadata().getDataSource()); - jdbcTemplate.execute(new ConnectionCallback() { - @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,12 @@ public Void doInConnection(Connection connection) public void getPoolSizeOneConnection() { JdbcTemplate jdbcTemplate = new JdbcTemplate( getDataSourceMetadata().getDataSource()); - jdbcTemplate.execute(new ConnectionCallback() { - @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 +75,13 @@ public Void doInConnection(Connection connection) public void getPoolSizeTwoConnections() { final JdbcTemplate jdbcTemplate = new JdbcTemplate( getDataSourceMetadata().getDataSource()); - jdbcTemplate.execute(new ConnectionCallback() { - - @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 99aea2468a7d..6a88b831232f 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 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; @@ -47,7 +46,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jms.core.JmsTemplate; -import org.springframework.jms.core.MessageCreator; import org.springframework.jms.core.SessionCallback; import org.springframework.jms.support.destination.DestinationResolver; import org.springframework.jms.support.destination.DynamicDestinationResolver; @@ -232,13 +230,8 @@ public void embeddedWithPersistentMode() throws IOException, JMSException { .load(context -> { JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - jmsTemplate.send("TestQueue", new MessageCreator() { - @Override - public Message createMessage(Session session) - throws JMSException { - return session.createTextMessage(msgId); - } - }); + jmsTemplate.send("TestQueue", + session -> session.createTextMessage(msgId)); }); // Start the server again and check if our message is still here @@ -255,26 +248,24 @@ public Message createMessage(Session session) @Test public void severalEmbeddedBrokers() { this.contextLoader.config(EmptyConfiguration.class) - .env("spring.artemis.embedded.queues=Queue1").load(rootContext -> { - this.contextLoader.env("spring.artemis.embedded.queues=Queue2") - .load(anotherContext -> { - ArtemisProperties properties = rootContext - .getBean(ArtemisProperties.class); - ArtemisProperties anotherProperties = anotherContext - .getBean(ArtemisProperties.class); - assertThat( - properties.getEmbedded().getServerId() < anotherProperties - .getEmbedded().getServerId()).isTrue(); - DestinationChecker checker = new DestinationChecker( - anotherContext); - checker.checkQueue("Queue1", true); - checker.checkQueue("Queue2", true); - DestinationChecker anotherChecker = new DestinationChecker( - anotherContext); - anotherChecker.checkQueue("Queue2", true); - anotherChecker.checkQueue("Queue1", true); - }); - }); + .env("spring.artemis.embedded.queues=Queue1").load(rootContext -> this.contextLoader.env("spring.artemis.embedded.queues=Queue2") + .load(anotherContext -> { + ArtemisProperties properties = rootContext + .getBean(ArtemisProperties.class); + ArtemisProperties anotherProperties = anotherContext + .getBean(ArtemisProperties.class); + assertThat( + properties.getEmbedded().getServerId() < anotherProperties + .getEmbedded().getServerId()).isTrue(); + DestinationChecker checker = new DestinationChecker( + anotherContext); + checker.checkQueue("Queue1", true); + checker.checkQueue("Queue2", true); + DestinationChecker anotherChecker = new DestinationChecker( + anotherContext); + anotherChecker.checkQueue("Queue2", true); + anotherChecker.checkQueue("Queue1", true); + })); } @Test @@ -282,26 +273,24 @@ public void connectToASpecificEmbeddedBroker() { this.contextLoader.config(EmptyConfiguration.class) .env("spring.artemis.embedded.serverId=93", "spring.artemis.embedded.queues=Queue1") - .load(context -> { - this.contextLoader.config(EmptyConfiguration.class).env( - "spring.artemis.mode=embedded", - "spring.artemis.embedded.serverId=93", /* - * Connect to the - * "main" broker - */ - "spring.artemis.embedded.enabled=false" /* - * do not start a - * specific one - */) - .load(anotherContext -> { - DestinationChecker checker = new DestinationChecker(context); - checker.checkQueue("Queue1", true); - - DestinationChecker anotherChecker = new DestinationChecker( - anotherContext); - anotherChecker.checkQueue("Queue1", true); - }); - }); + .load(context -> this.contextLoader.config(EmptyConfiguration.class).env( + "spring.artemis.mode=embedded", + "spring.artemis.embedded.serverId=93", /* + * Connect to the + * "main" broker + */ + "spring.artemis.embedded.enabled=false" /* + * do not start a + * specific one + */) + .load(anotherContext -> { + DestinationChecker checker = new DestinationChecker(context); + checker.checkQueue("Queue1", true); + + DestinationChecker anotherChecker = new DestinationChecker( + anotherContext); + anotherChecker.checkQueue("Queue1", true); + })); } private TransportConfiguration assertInVmConnectionFactory( @@ -353,25 +342,22 @@ public void checkTopic(String name, boolean shouldExist) { 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 = DestinationChecker.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()); - } + } + catch (JMSException e) { + if (shouldExist) { + throw new IllegalStateException("Destination '" + name + + "' was expected but got " + e.getMessage()); } - return null; } + return null; }); } @@ -425,13 +411,9 @@ protected static class CustomArtemisConfiguration { @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 bbd09ee9b0c8..a012370ca55c 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,7 @@ public void logsDebugOnContextRefresh() { 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 +76,8 @@ public void logsDebugOnError() { 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 +108,7 @@ public void logsOutput() throws Exception { 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 fd27e1d16cbd..7fa8c5a74070 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.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,7 @@ protected static class TestAuthenticationConfiguration { @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 +438,8 @@ protected WorkaroundSecurityCustomizer(AuthenticationManagerBuilder builder) { @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 -> WorkaroundSecurityCustomizer.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 0b8dffdd199c..87bac3439b5a 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.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 @@ protected static class AuthoritiesConfiguration extends ResourceConfiguration { @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 @@ protected static class PrincipalConfiguration extends ResourceConfiguration { @Bean PrincipalExtractor principalExtractor() { - return new PrincipalExtractor() { - - @Override - public Object extractPrincipal(Map map) { - return "boot"; - } - - }; + return map -> "boot"; } } @@ -372,15 +348,8 @@ protected static class Customizer implements UserInfoRestTemplateCustomizer { @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 @@ private static class MockRestCallCustomizer @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/security/oauth2/resource/UserInfoTokenServicesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServicesTests.java index 4ac1457cb949..a286fb363e46 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 fc8ea5439a8b..95c67693e07a 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 void testTomcatBinding() throws Exception { @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 void testCustomizeJettySelectors() throws Exception { @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/client/RestTemplateAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfigurationTests.java index f3d4bd73d037..5f59853bdabf 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 RestTemplate restTemplateTwo(RestTemplateBuilder builder) { } private void breakBuilderOnNextCall(RestTemplateBuilder builder) { - builder.additionalCustomizers(new RestTemplateCustomizer() { - - @Override - public void customize(RestTemplate restTemplate) { - throw new IllegalStateException(); - } - + builder.additionalCustomizers((RestTemplateCustomizer) restTemplate -> { + throw new IllegalStateException(); }); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfigurationTests.java index bc5f5c520e70..d60d8dd4429e 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfigurationTests.java @@ -53,9 +53,7 @@ public void shouldNotProcessIfExistingHttpHandler() { @Test public void shouldConfigureHttpHandlerAnnotation() { - this.contextLoader.autoConfig(WebFluxAutoConfiguration.class).load(context -> { - assertThat(context.getBeansOfType(HttpHandler.class).size()).isEqualTo(1); - }); + this.contextLoader.autoConfig(WebFluxAutoConfiguration.class).load(context -> assertThat(context.getBeansOfType(HttpHandler.class).size()).isEqualTo(1)); } @Configuration 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 ff31665c2345..b4372cc5e85e 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 void tomcatAccessLogCanBeEnabled() { @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 void tomcatAccessLogFileDateFormatByDefault() { @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 void customTomcatMaxHttpPostSize() { @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-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 b6df5760360c..c7291afafdd4 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 static class MockServletWebServer public MockServletWebServer(ServletContextInitializer[] initializers, int port) { super(Arrays.stream(initializers) - .map((i) -> (Initializer) (s) -> i.onStartup(s)) + .map((i) -> (Initializer) i::onStartup) .toArray(Initializer[]::new), port); } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfigurationTests.java index 66d71c4c4575..d79d53d1272e 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfigurationTests.java @@ -133,10 +133,8 @@ public void handlerAdaptersCreated() { @Test public void handlerMappingsCreated() { - this.contextLoader.load(context -> { - assertThat(context.getBeanNamesForType(HandlerMapping.class).length) - .isEqualTo(7); - }); + this.contextLoader.load(context -> assertThat(context.getBeanNamesForType(HandlerMapping.class).length) + .isEqualTo(7)); } @Test @@ -296,9 +294,7 @@ public void resourceHandlerChainCustomized() { @Test public void noLocaleResolver() throws Exception { - this.contextLoader.load(context -> { - assertThat(context.getBeansOfType(LocaleResolver.class)).isEmpty(); - }); + this.contextLoader.load(context -> assertThat(context.getBeansOfType(LocaleResolver.class)).isEmpty()); } @Test @@ -371,20 +367,16 @@ public void overrideDateFormat() { @Test public void noMessageCodesResolver() { - this.contextLoader.load(context -> { - assertThat(context.getBean(WebMvcAutoConfigurationAdapter.class) - .getMessageCodesResolver()).isNull(); - }); + this.contextLoader.load(context -> assertThat(context.getBean(WebMvcAutoConfigurationAdapter.class) + .getMessageCodesResolver()).isNull()); } @Test public void overrideMessageCodesFormat() { this.contextLoader .env("spring.mvc.messageCodesResolverFormat:POSTFIX_ERROR_CODE"); - this.contextLoader.load(context -> { - assertThat(context.getBean(WebMvcAutoConfigurationAdapter.class) - .getMessageCodesResolver()).isNotNull(); - }); + this.contextLoader.load(context -> assertThat(context.getBean(WebMvcAutoConfigurationAdapter.class) + .getMessageCodesResolver()).isNotNull()); } @Test @@ -410,10 +402,8 @@ public void overrideIgnoreDefaultModelOnRedirect() { @Test public void customViewResolver() { - this.contextLoader.config(CustomViewResolver.class).load(context -> { - assertThat(context.getBean("viewResolver")) - .isInstanceOf(MyViewResolver.class); - }); + this.contextLoader.config(CustomViewResolver.class).load(context -> assertThat(context.getBean("viewResolver")) + .isInstanceOf(MyViewResolver.class)); } @Test @@ -443,10 +433,8 @@ public void faviconMapping() { @Test public void faviconMappingUsesStaticLocations() { this.contextLoader.env("spring.resources.static-locations=classpath:/static"); - this.contextLoader.load(context -> { - assertThat(getFaviconMappingLocations(context).get("/**/favicon.ico")) - .hasSize(2); - }); + this.contextLoader.load(context -> assertThat(getFaviconMappingLocations(context).get("/**/favicon.ico")) + .hasSize(2)); } @Test @@ -492,10 +480,8 @@ public void customMediaTypes() throws Exception { @Test public void httpPutFormContentFilterIsAutoConfigured() { - this.contextLoader.load(context -> { - assertThat(context.getBeansOfType(OrderedHttpPutFormContentFilter.class)) - .hasSize(1); - }); + this.contextLoader.load(context -> assertThat(context.getBeansOfType(OrderedHttpPutFormContentFilter.class)) + .hasSize(1)); } @Test @@ -510,37 +496,29 @@ public void httpPutFormContentFilterCanBeOverridden() { @Test public void httpPutFormContentFilterCanBeDisabled() throws Exception { this.contextLoader.env("spring.mvc.formcontent.putfilter.enabled=false"); - this.contextLoader.load(context -> { - assertThat(context.getBeansOfType(HttpPutFormContentFilter.class)).isEmpty(); - }); + this.contextLoader.load(context -> assertThat(context.getBeansOfType(HttpPutFormContentFilter.class)).isEmpty()); } @Test public void customConfigurableWebBindingInitializer() { this.contextLoader.config(CustomConfigurableWebBindingInitializer.class); - this.contextLoader.load(context -> { - assertThat(context.getBean(RequestMappingHandlerAdapter.class) - .getWebBindingInitializer()) - .isInstanceOf(CustomWebBindingInitializer.class); - }); + this.contextLoader.load(context -> assertThat(context.getBean(RequestMappingHandlerAdapter.class) + .getWebBindingInitializer()) + .isInstanceOf(CustomWebBindingInitializer.class)); } @Test public void customRequestMappingHandlerMapping() { this.contextLoader.config(CustomRequestMappingHandlerMapping.class); - this.contextLoader.load(context -> { - assertThat(context.getBean(RequestMappingHandlerMapping.class)) - .isInstanceOf(MyRequestMappingHandlerMapping.class); - }); + this.contextLoader.load(context -> assertThat(context.getBean(RequestMappingHandlerMapping.class)) + .isInstanceOf(MyRequestMappingHandlerMapping.class)); } @Test public void customRequestMappingHandlerAdapter() { this.contextLoader.config(CustomRequestMappingHandlerAdapter.class); - this.contextLoader.load(context -> { - assertThat(context.getBean(RequestMappingHandlerAdapter.class)) - .isInstanceOf(MyRequestMappingHandlerAdapter.class); - }); + this.contextLoader.load(context -> assertThat(context.getBean(RequestMappingHandlerAdapter.class)) + .isInstanceOf(MyRequestMappingHandlerAdapter.class)); } @Test @@ -555,18 +533,14 @@ public void multipleWebMvcRegistrations() { @Test public void defaultLogResolvedException() { - this.contextLoader.load(context -> { - assertExceptionResolverWarnLoggers(context, - warnLogger -> assertThat(warnLogger).isNull()); - }); + this.contextLoader.load(context -> assertExceptionResolverWarnLoggers(context, + warnLogger -> assertThat(warnLogger).isNull())); } @Test public void customLogResolvedException() { - this.contextLoader.env("spring.mvc.log-resolved-exception:true").load(context -> { - assertExceptionResolverWarnLoggers(context, - warnLogger -> assertThat(warnLogger).isNotNull()); - }); + this.contextLoader.env("spring.mvc.log-resolved-exception:true").load(context -> assertExceptionResolverWarnLoggers(context, + warnLogger -> assertThat(warnLogger).isNotNull())); } @Test @@ -843,10 +817,8 @@ protected List getResourceTransformers( protected Map> getMappingLocations(HandlerMapping mapping) { Map> mappingLocations = new LinkedHashMap<>(); if (mapping instanceof SimpleUrlHandlerMapping) { - ((SimpleUrlHandlerMapping) mapping).getHandlerMap().forEach((key, value) -> { - mappingLocations.put(key, (List) ReflectionTestUtils - .getField(value, "locations")); - }); + ((SimpleUrlHandlerMapping) mapping).getHandlerMap().forEach((key, value) -> mappingLocations.put(key, (List) ReflectionTestUtils + .getField(value, "locations"))); } return mappingLocations; } diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java index c1cd76bde881..6a26cb4e3c28 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java @@ -45,9 +45,7 @@ public class WebServicesAutoConfigurationTests { @Test public void defaultConfiguration() { - this.contextLoader.load(context -> { - assertThat(context.getBeansOfType(ServletRegistrationBean.class)).hasSize(1); - }); + this.contextLoader.load(context -> assertThat(context.getBeansOfType(ServletRegistrationBean.class)).hasSize(1)); } @Test diff --git a/spring-boot-cli/src/it/java/org/springframework/boot/cli/infrastructure/CommandLineInvoker.java b/spring-boot-cli/src/it/java/org/springframework/boot/cli/infrastructure/CommandLineInvoker.java index 3d1dc546ae91..ff5a31a5a81e 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 @@ 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 @@ private Process runCliProcess(String... args) throws IOException { 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 c37709e6c1c5..df2cae92d28b 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.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 @@ private void writeJar(File file, Class[] compiledClasses, 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 0e1f7762658d..d31ea7f87f7e 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,12 +94,7 @@ private void reportAvailableDependencies(InitializrServiceMetadata metadata, private List getSortedDependencies(InitializrServiceMetadata metadata) { ArrayList dependencies = new ArrayList<>(metadata.getDependencies()); - Collections.sort(dependencies, new Comparator() { - @Override - public int compare(Dependency o1, Dependency o2) { - return o1.getId().compareTo(o2.getId()); - } - }); + dependencies.sort(Comparator.comparing(Dependency::getId)); return dependencies; } @@ -108,15 +103,7 @@ private void reportAvailableProjectTypes(InitializrServiceMetadata metadata, 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 b3f6c004c19f..880adddca090 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,13 +130,8 @@ private static class OptionHelpFormatter implements HelpFormatter { @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 = Comparator.comparing( + optionDescriptor -> optionDescriptor.options().iterator().next()); Set sorted = new TreeSet<>(comparator); sorted.addAll(options.values()); 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 b2745217e5ff..1edac65ab45b 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 @@ private void initializeConsoleReader() { } 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 b1e5be1daba7..116047b2525b 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 @@ -123,17 +123,12 @@ public InputStream getResourceAsStream(String name) { @Override public ClassCollector createCollector(CompilationUnit unit, SourceUnit su) { InnerLoader loader = AccessController - .doPrivileged(new PrivilegedAction() { + .doPrivileged((PrivilegedAction) () -> 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 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; - } - }; + public URL[] getURLs() { + return NO_URLS; } }); return new ExtendedClassCollector(loader, unit, su); 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 9f9172455d15..fdac83bb42e0 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 GroovyCompiler(final GroovyCompilerConfiguration configuration) { .load(SpringBootAstTransformation.class)) { this.transformations.add(transformation); } - Collections.sort(this.transformations, AnnotationAwareOrderComparator.INSTANCE); + this.transformations.sort(AnnotationAwareOrderComparator.INSTANCE); } /** 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 976473a45077..8b631b4d530d 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 @@ -101,12 +101,7 @@ private ProgressReporter getProgressReporter(DefaultRepositorySystemSession sess return new DetailedProgressReporter(session, System.out); } else if ("none".equals(progressReporter)) { - return new ProgressReporter() { - - @Override - public void finished() { - - } + return () -> { }; } @@ -131,10 +126,7 @@ public Object grab(Map args, Map... dependencyMaps) { 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-cli/src/test/java/org/springframework/boot/cli/CliTester.java b/spring-boot-cli/src/test/java/org/springframework/boot/cli/CliTester.java index f25765d8b792..bde1ec0cd031 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.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 @@ private Future submitCommand(final T command 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 dc1db57cd90f..0f5ba1a0430d 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,54 @@ 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 543102fed2d6..f3e87b9d8bac 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,39 @@ public void dependencyResolution() { @Test public void proxySelector() { - doWithCustomUserHome(new Runnable() { + doWithCustomUserHome(() -> { + AetherGrapeEngine grapeEngine = createGrapeEngine(); - @Override - public void run() { - AetherGrapeEngine grapeEngine = createGrapeEngine(); - - DefaultRepositorySystemSession session = (DefaultRepositorySystemSession) ReflectionTestUtils - .getField(grapeEngine, "session"); - - assertThat(session.getProxySelector() instanceof CompositeProxySelector) - .isTrue(); - } + 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(() -> { + AetherGrapeEngine grapeEngine = createGrapeEngine(); + + List repositories = (List) ReflectionTestUtils + .getField(grapeEngine, "repositories"); + 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(() -> { + AetherGrapeEngine grapeEngine = createGrapeEngine(); + + List repositories = (List) ReflectionTestUtils + .getField(grapeEngine, "repositories"); + assertThat(repositories).hasSize(1); + Authentication authentication = repositories.get(0).getAuthentication(); + assertThat(authentication).isNotNull(); }); } 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 7bfb5cc96a33..0d93c11e6a8c 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 @@ -60,19 +60,13 @@ public void setup() { 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); - } - + .willAnswer(invocation -> { + LocalRepository localRepository = invocation + .getArgument(1); + return new SimpleLocalRepositoryManagerFactory() + .newInstance( + GrapeRootRepositorySystemSessionAutoConfigurationTests.this.session, + localRepository); }); new GrapeRootRepositorySystemSessionAutoConfiguration().apply(this.session, this.repositorySystem); 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 9edc8ae347c9..17d22ca02364 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.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.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; @@ -79,25 +76,15 @@ public void propertyInterpolation() throws SettingsBuildingException { .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); - } + .willAnswer(invocation -> { + 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", + 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()) @@ -107,13 +94,8 @@ public void run() { 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(); 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 8ecf52b1bd49..218592072eca 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 @@ private enum InMemoryDatabase { 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-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 f5bdc16b1868..e52799806def 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 HateoasObjenesisCacheDisabler hateoasObjenesisCacheDisabler() { @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 d14fc81aad31..d3a5e60af418 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 LiveReloadServer(ThreadFactory threadFactory) { * @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 int start() throws IOException { 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/ClassPathChangeUploader.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploader.java index 6c1bf7909674..5bf05c841c7c 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 ClassPathChangeUploader(String url, ClientHttpRequestFactory requestFacto 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/remote/client/RemoteClientConfiguration.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/RemoteClientConfiguration.java index ad7ae524bdc4..6cd93ade9a28 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 @@ -201,14 +201,7 @@ public ClassPathFileSystemWatcher classPathFileSystemWatcher() { @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 494d2817947c..353cdd03be36 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 7ad9af798a9c..f00eb267e394 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 384b711cc47b..db5de2ac7e76 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 4da7159670b4..38a5d9f6a75e 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 @@ protected void initialize(boolean restartOnInitialize) { private void immediateRestart() { try { - getLeakSafeThread().callAndWait(new Callable() { - - @Override - public Void call() throws Exception { - start(FailureHandler.NONE); - cleanupCaches(); - return null; - } - + getLeakSafeThread().callAndWait((Callable) () -> { + start(FailureHandler.NONE); + cleanupCaches(); + return null; }); } catch (Exception ex) { @@ -251,15 +246,10 @@ public void restart(final FailureHandler failureHandler) { 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 @@ private class LeakSafeThreadFactory implements ThreadFactory { @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 6692079430d2..9f336b5a5c0b 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 bad78dd338f2..475b665ed04b 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 URL findResource(final String name) { 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 @@ protected Class findClass(final String name) throws ClassNotFoundException { 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/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 9014fb757ce2..268c3275a556 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 @@ protected HttpTunnelConnection(String url, ClientHttpRequestFactory requestFacto 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/TunnelClient.java b/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/TunnelClient.java index 2289af9c54d6..a611b3d4fdd6 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,12 +170,11 @@ public void run() { 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 { - logger.trace("Accepted connection to tunnel client from " - + socketChannel.socket().getRemoteSocketAddress()); + try (WritableByteChannel outputChannel = TunnelClient.this.tunnelConnection + .open(socketChannel, closeable)) { + logger.trace("Accepted connection to tunnel client from " + socketChannel + .socket().getRemoteSocketAddress()); while (true) { ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); int amountRead = socketChannel.read(buffer); @@ -189,9 +188,6 @@ private void handleConnection(SocketChannel socketChannel) throws Exception { } } } - finally { - outputChannel.close(); - } } protected void stopAcceptingConnections() { 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 e2d1c4d89697..f168550ebf36 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.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 ClassPathFileSystemWatcher watcher() { @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 03ceb3c2158a..c1594e4b54c1 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 void multipleListeners() throws Exception { 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,7 @@ public void withTriggerFilter() throws Exception { 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(file1 -> file1.getName().equals("trigger.txt")); this.watcher.start(); FileCopyUtils.copy("abc".getBytes(), file); Thread.sleep(100); @@ -285,12 +272,8 @@ public boolean accept(File file) { 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 4bd5c0c0b15f..ec5d06acf549 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 void threadMustNotBeNull() throws Exception { @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 void run() { 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 c315b762ac52..282fb1910992 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 @@ 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,18 @@ private void setup() { 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 c8aef1fba059..b52ca2638892 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 void noInitialization() throws Exception { @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 193daf4d9a97..7ff3e1cfa430 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.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 void cantGetInstanceBeforeInitialize() throws Exception { @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 void addClassLoaderFiles() throws Exception { @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 String getObject() throws BeansException { 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 7cc1fc2c4c10..131f5a057aa6 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 @@ -81,12 +81,7 @@ private static abstract class TestThread extends Thread { private Throwable thrown; TestThread() { - setUncaughtExceptionHandler(new UncaughtExceptionHandler() { - @Override - public void uncaughtException(Thread t, Throwable e) { - TestThread.this.thrown = e; - } - }); + setUncaughtExceptionHandler((t, e) -> TestThread.this.thrown = e); } public Throwable getThrown() { @@ -119,21 +114,16 @@ protected void preventNonZeroExitCode() { @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 e8a7d17931b3..764ba7717955 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.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 @@ private void testHttpConnectionNonAsync(long sleepBeforeResponse) .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-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 70fb93d2bf93..183490b191af 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 static Object[] parameters(String packaging, 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 f5a87f5b42ed..3eb6033d15c9 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 @@ protected List getArguments(File archive) { 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 4bb64855725d..949c8cb145aa 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 @@ protected List getArguments(File archive) { 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-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 5dd798ff2c28..47e917928c6c 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 @@ -449,15 +449,9 @@ private static final class SpringBootDockerCmdExecFactory 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((ClientRequestFilter) 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 79f7ace6caf7..dd732147b9f1 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.core.ResolvableType; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.util.ReflectionUtils; -import org.springframework.util.ReflectionUtils.FieldCallback; /** * Auto-configuration for Json testers. @@ -153,15 +152,8 @@ private static class JsonMarshalTestersBeanPostProcessor public Object postProcessAfterInitialization(final 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/properties/AnnotationsPropertySource.java b/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySource.java index eaba4fc3bf03..bd6696cf8f84 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 AnnotationsPropertySource(String name, Class source) { 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-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 1f8bbb807ea0..3d14f23f98ba 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 @@ -56,10 +56,8 @@ private void customizeWebTestClientCodecs(WebTestClient.Builder builder, Collection codecCustomizers = applicationContext .getBeansOfType(CodecCustomizer.class).values(); if (!CollectionUtils.isEmpty(codecCustomizers)) { - builder.exchangeStrategies(ExchangeStrategies.builder().codecs((codecs) -> { - codecCustomizers - .forEach((codecCustomizer) -> codecCustomizer.customize(codecs)); - }).build()); + builder.exchangeStrategies(ExchangeStrategies.builder().codecs((codecs) -> codecCustomizers + .forEach((codecCustomizer) -> codecCustomizer.customize(codecs))).build()); } } 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 9b8637242e3b..6af3e3e91327 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 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,23 +114,17 @@ public static void registerWith(ConfigurableApplicationContext context) { if (beanFactory.getRegisteredScope(NAME) == null) { beanFactory.registerScope(NAME, new WebDriverScope()); } - context.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() { - - @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); - } + context.addBeanFactoryPostProcessor(beanFactory1 -> { + for (String beanClass : BEAN_CLASSES) { + for (String beanName : beanFactory1.getBeanNamesForType( + ClassUtils.resolveClassName(beanClass, null))) { + BeanDefinition definition = beanFactory1 + .getBeanDefinition(beanName); + if (!StringUtils.hasLength(definition.getScope())) { + definition.setScope(NAME); } } } - }); } diff --git a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java index aedc5e09e544..f2ee479ff4e9 100644 --- a/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java +++ b/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java @@ -42,9 +42,7 @@ public class TestDatabaseAutoConfigurationTests { @Test public void replaceWithNoDataSourceAvailable() { - this.contextLoader.load(context -> { - assertThat(context.getBeansOfType(DataSource.class)).isEmpty(); - }); + this.contextLoader.load(context -> assertThat(context.getBeansOfType(DataSource.class)).isEmpty()); } @Test 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 c44951548c0f..ba3e0a47f8ec 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 @@ -16,7 +16,6 @@ package org.springframework.boot.test.context; -import java.lang.reflect.Method; import java.util.List; import org.springframework.context.annotation.Bean; @@ -27,7 +26,6 @@ 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,15 +47,9 @@ public ContextCustomizer createContextCustomizer(Class testClass, } 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, + 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/context/SpringBootTestContextBootstrapper.java b/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextBootstrapper.java index 3ce6e5f1c6bd..88e601b9a6eb 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 @@ private boolean isFromConfiguration(MergedContextConfiguration candidateConfig, 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/AbstractJsonMarshalTester.java b/spring-boot-test/src/main/java/org/springframework/boot/test/json/AbstractJsonMarshalTester.java index dd528babf729..8ea3f986b97e 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 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.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 @@ protected FieldInitializer( 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/json/DuplicateJsonObjectContextCustomizerFactory.java b/spring-boot-test/src/main/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactory.java index b6abcdc20d15..d83c3e9cf439 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 @@ public void customizeContext(ConfigurableApplicationContext context, } 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 91c79a1e5a15..ffc6e0df60f9 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 static void initFields(Object testInstance, * @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-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 e0f4dce8794b..99348cb18867 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.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 fab7081390df..11a22e9a8a46 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.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 @@ protected Object createSpyIfNecessary(Object bean, String beanName) 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/main/java/org/springframework/boot/test/web/reactive/WebTestClientContextCustomizer.java b/spring-boot-test/src/main/java/org/springframework/boot/test/web/reactive/WebTestClientContextCustomizer.java index 5e3f45b8b1db..1b83e7866824 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/web/reactive/WebTestClientContextCustomizer.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/web/reactive/WebTestClientContextCustomizer.java @@ -139,10 +139,8 @@ private void customizeWebTestClientCodecs(WebTestClient.Builder clientBuilder, .getBeansOfType(CodecCustomizer.class).values(); if (!CollectionUtils.isEmpty(codecCustomizers)) { clientBuilder.exchangeStrategies( - ExchangeStrategies.builder().codecs(codecs -> { - codecCustomizers.forEach( - codecCustomizer -> codecCustomizer.customize(codecs)); - }).build()); + ExchangeStrategies.builder().codecs(codecs -> codecCustomizers.forEach( + codecCustomizer -> codecCustomizer.customize(codecs))).build()); } } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/context/StandardContextLoaderTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/context/StandardContextLoaderTests.java index bd91cf6e4b05..c6e68d3c3e3f 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/context/StandardContextLoaderTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/context/StandardContextLoaderTests.java @@ -73,9 +73,7 @@ public void systemPropertyIsRestoredToItsOriginalValue() { System.setProperty(key, "value"); try { assertThat(System.getProperties().getProperty(key)).isEqualTo("value"); - this.contextLoader.systemProperty(key, "newValue").load(context -> { - assertThat(System.getProperties().getProperty(key)).isEqualTo("newValue"); - }); + this.contextLoader.systemProperty(key, "newValue").load(context -> assertThat(System.getProperties().getProperty(key)).isEqualTo("newValue")); assertThat(System.getProperties().getProperty(key)).isEqualTo("value"); } finally { @@ -88,9 +86,7 @@ public void systemPropertyCanBeSetToNullValue() { String key = "test." + UUID.randomUUID().toString(); assertThat(System.getProperties().containsKey(key)).isFalse(); this.contextLoader.systemProperty(key, "value").systemProperty(key, null) - .load(context -> { - assertThat(System.getProperties().containsKey(key)).isFalse(); - }); + .load(context -> assertThat(System.getProperties().containsKey(key)).isFalse()); } @Test @@ -197,9 +193,7 @@ public void classLoaderIsUsed() { @Test public void assertionErrorsAreAvailableAsIs() { try { - this.contextLoader.load(context -> { - fail("This is expected"); - }); + this.contextLoader.load(context -> fail("This is expected")); } catch (AssertionError ex) { assertThat(ex.getMessage()).isEqualTo("This is expected"); 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 c8226051af82..133d7b2efcd4 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 @@ -1306,14 +1306,7 @@ private static String loadJson(String path) { } 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 be83982f242c..bec199d4f9d1 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 void asMapForNonMapShouldFail() throws Exception { } 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 c0783da16798..26c949805658 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 @@ -71,14 +71,7 @@ static class TestFactoryBean implements FactoryBean { @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 dda6492c7036..8163fc3392f0 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 @@ -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 @@ protected String getResourceLocation(String path) { 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 94fea8df7f69..b3211445a049 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 @@ private Object mockArgument(Class type) throws Exception { 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,89 @@ public void withBasicAuthDoesNotResetErrorHandler() throws Exception { @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), - new ParameterizedTypeReference() { - }); - } - - }); + 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]), - new ParameterizedTypeReference() { - }); - } - - }); + 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 e2552825c66f..64a3ca0016c9 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-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 a49511364461..991e91658721 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 @@ void setExcludeDevtools(boolean excludeDevtools) { } 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 71dd5b8e1dac..9ce874dfc3da 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 @@ private Spec writeLoaderClassesIfNecessary( 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 40ee454fb5ad..8aa4cae905e4 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 b3d8f293a667..c991ebe04b2e 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 3f06851ffee0..67f819ce5d6d 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 GradleRunner prepareRunner(String... arguments) throws IOException { 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-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 4cf1d45f8aef..34c0554ef2f6 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 @@ private void setExecutableFilePermission(File file) { */ 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); } /** @@ -186,8 +181,7 @@ public void writeNestedLibrary(String destination, Library library) 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 +190,6 @@ private long getNestedLibraryTime(File file) { } } } - finally { - jarFile.close(); - } } catch (Exception ex) { // Ignore and just use the source file timestamp @@ -381,13 +372,9 @@ private static class CrcAndSize { 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 { 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 a32f59a23c1b..8610f3f563bb 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 e02525e69177..f4c83f70f8cc 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,9 @@ 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 = file -> (file.isFile() && file.getName().endsWith(DOT_CLASS)); - 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 = file -> file.isDirectory() && !file.getName().startsWith("."); /** * Find the main class from a given folder. @@ -82,12 +72,7 @@ public boolean accept(File file) { * @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 +148,7 @@ static T doWithMainClasses(File rootFolder, MainClassCallback callback) } 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 +163,7 @@ public int compare(File o1, File o2) { */ 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); } /** @@ -234,7 +208,7 @@ public static String findSingleMainClass(JarFile jarFile, String classesLocation 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-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 f3e26bb6b88b..f88be521fa29 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 @@ private void repackage(JarFile sourceJar, File destination, Libraries libraries, 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 c6a4cc7c65ab..3efe5647a4a0 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 @@ -87,12 +87,7 @@ protected int run(boolean waitForProcess, Collection args) 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 @@ private static boolean isInheritIOBroken() { 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 cd7f52ce9621..6b0c2805394e 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 @@ -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 @@ private 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 3758ee4546ff..329e487ba964 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 @@ */ 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,11 @@ public void libraries() throws Exception { 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 +325,9 @@ public void duplicateLibraries() throws Exception { 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 +346,7 @@ public void customLayout() throws Exception { 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,7 @@ public void customLayoutNoBootLib() throws Exception { 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")) @@ -452,12 +429,8 @@ public void dontRecompressZips() throws Exception { 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( @@ -500,14 +473,8 @@ public void unpackLibrariesTakePrecedenceOverExistingSourceEntries() 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( @@ -528,16 +495,11 @@ public void existingSourceEntriesTakePrecedenceOverStandardLibraries() 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 c65fbfcbae40..cbe6341f04c0 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.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 @@ protected String getMainClass() throws Exception { @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 9ff3c966cd16..0b50ad5f0bcd 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,29 @@ private void definePackageIfNecessary(String className) { 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 b361c7ee5264..9e7304f42f9f 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 @@ protected String getMainClass() throws Exception { @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 @@ private List getNestedArchives(String path) throws Exception { 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 @@ -537,16 +537,11 @@ private void addNestedEntries(List lib) { // 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 a22661f3590a..225ec7dfaa80 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 @@ private JarFile createJarFileFromEntry(JarEntry entry) throws IOException { 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/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 2bbfa8bf0fe0..42cc44ade2f9 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 static String resolvePlaceholders(String text) { if (text == null) { return text; } - return parseStringValue(null, text, text, new HashSet()); + return parseStringValue(null, text, text, new HashSet<>()); } /** @@ -83,7 +83,7 @@ public static String resolvePlaceholders(Properties properties, String text) { 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 c62bd797bcb6..b1a3059a5361 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 void testCustomClassLoaderCreation() throws Exception { } 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-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 2caf95cf4e62..9166ceb839fd 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.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.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,13 @@ public void concurrentReads() throws Exception { 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 +320,16 @@ public void seekFailuresDoNotPreventSubsequentReads() throws Exception { "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/AbstractRunMojo.java b/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractRunMojo.java index c5d00d30d38e..f098542ac2f4 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 @@ protected URL[] getClassPathUrls() throws MojoExecutionException { 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 066423e676ed..8400115dd4b0 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 @@ -73,10 +73,7 @@ public boolean isReady() throws MojoExecutionException { 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 7661cbaf2f45..304392320138 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 @@ protected void runWithForkedJvm(File workingDirectory, List args) try { waitForSpringApplication(); } - catch (MojoExecutionException ex) { - runProcess.kill(); - throw ex; - } - catch (MojoFailureException ex) { + catch (MojoExecutionException | MojoFailureException ex) { runProcess.kill(); throw ex; } @@ -232,14 +228,7 @@ private void doWaitForSpringApplication(MBeanServerConnection connection) 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 6a6198146902..8f63774afe4d 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 @@ protected TestClass createTestClass(Class testClass) { 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 { @@ -100,7 +94,7 @@ private URLClassLoader createTestClassLoader(Class testClass) throws Exceptio } 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 +111,7 @@ private boolean isSurefireBooterJar(URL url) { } 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 +127,7 @@ private String[] getClassPath(URL booterJar) throws Exception { 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 +167,7 @@ private List resolveCoordinates(String[] coordinates) throws Exception { 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 +175,7 @@ private List resolveCoordinates(String[] coordinates) throws Exception { } 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 +248,7 @@ private List getAnnotatedMethods(String annotationClassName) 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())); @@ -300,15 +293,8 @@ private ModifiedClassPathFrameworkMethod(Method method) { 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 4916c1471e55..1ff9288fdab2 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.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,33 @@ private void initialize() { 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)); - } - }); + .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/BeanDefinitionLoader.java b/spring-boot/src/main/java/org/springframework/boot/BeanDefinitionLoader.java index edf7db91598f..6453c60b9adb 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 @@ private int load(CharSequence source) { 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/EnvironmentConverter.java b/spring-boot/src/main/java/org/springframework/boot/EnvironmentConverter.java index d99ca1cf1d8a..8087f70fe8fd 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 @@ private void copyNonServletPropertySources(ConfigurableEnvironment source, } 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/SpringApplication.java b/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java index ba0767e68ce5..8bb0e2936ac6 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 @@ private static void close(ApplicationContext context) { 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/StartupInfoLogger.java b/spring-boot/src/main/java/org/springframework/boot/StartupInfoLogger.java index ddc995a3925c..540738b9afb2 100644 --- a/spring-boot/src/main/java/org/springframework/boot/StartupInfoLogger.java +++ b/spring-boot/src/main/java/org/springframework/boot/StartupInfoLogger.java @@ -100,45 +100,20 @@ private String getApplicationName() { } 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/config/DelegatingApplicationContextInitializer.java b/spring-boot/src/main/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializer.java index 5d2fa55ad0dd..800d605fd8fe 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 @@ private ApplicationContextInitializer instantiateInitializer(Class context @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/context/properties/ConfigurationBeanFactoryMetaData.java b/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationBeanFactoryMetaData.java index 32f0bff7b48d..00c2a4ee8ae5 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.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 @@ private Method findFactoryMethod(String beanName) { 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 1cdceca65df9..0e1c4b706fa2 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 @@ -266,10 +266,8 @@ private AggregateBinder getAggregateBinder(Bindable target, Context contex 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)); - }; + AggregateElementBinder elementBinder = (itemName, itemTarget, source) -> context.withSource(source, + () -> Binder.this.bind(itemName, itemTarget, handler, context)); return context.withIncreasedDepth( () -> aggregateBinder.bind(name, target, elementBinder)); } 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 8516461a70dc..f621665692ea 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 static ConfigurationPropertyName of(CharSequence name) { 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 @@ static ConfigurationPropertyName adapt(CharSequence name, char separator, 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 5e8a3996f3e5..d5415e18e815 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,10 +78,8 @@ protected Yaml createYaml() { } public Map load() { - final Map result = new LinkedHashMap(); - process((properties, map) -> { - result.putAll(getFlattenedMap(map)); - }); + final Map result = new LinkedHashMap<>(); + process((properties, map) -> result.putAll(getFlattenedMap(map))); return result; } 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 22dd96db3fe7..c3b9cbdde5cc 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 @@ private String[] getBeanNamesForType(ConfigurableListableBeanFactory beanFactory 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 d2b097e32468..afdd35b8ab13 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 @@ -67,10 +67,7 @@ private String[] getBeanNamesForType(ConfigurableListableBeanFactory beanFactory 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 7ca2ca5b538a..b8f61353d350 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 @@ -70,10 +70,7 @@ private String[] getBeanNamesForType(ConfigurableListableBeanFactory beanFactory 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/NarayanaProperties.java b/spring-boot/src/main/java/org/springframework/boot/jta/narayana/NarayanaProperties.java index e09c52782157..96a8cd5cee30 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/liquibase/SpringPackageScanClassResolver.java b/spring-boot/src/main/java/org/springframework/boot/liquibase/SpringPackageScanClassResolver.java index c19e6bb15547..cae7565db7da 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 @@ -78,11 +78,7 @@ private Class loadClass(ClassLoader loader, MetadataReaderFactory readerFacto 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/logging/java/JavaLoggingSystem.java b/spring-boot/src/main/java/org/springframework/boot/logging/java/JavaLoggingSystem.java index 779e5a352985..b5a566551d52 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 List getLoggerConfigurations() { 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 b78142cc1a4b..231111d4560f 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 List getLoggerConfigurations() { 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 8633366b8d57..7547b51afefb 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.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 List getLoggerConfigurations() { 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/context/ServerPortInfoApplicationContextInitializer.java b/spring-boot/src/main/java/org/springframework/boot/web/context/ServerPortInfoApplicationContextInitializer.java index ee13f5bddf3b..c6b5494bc86c 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 @@ -54,15 +54,8 @@ public class ServerPortInfoApplicationContextInitializer @Override public void initialize(ConfigurableApplicationContext applicationContext) { applicationContext.addApplicationListener( - new ApplicationListener() { - - @Override - public void onApplicationEvent(WebServerInitializedEvent event) { - ServerPortInfoApplicationContextInitializer.this - .onApplicationEvent(event); - } - - }); + (ApplicationListener) ServerPortInfoApplicationContextInitializer + .this::onApplicationEvent); } protected void onApplicationEvent(WebServerInitializedEvent event) { @@ -88,7 +81,7 @@ private void setPortProperty(ConfigurableEnvironment environment, String propert 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/tomcat/TomcatErrorPage.java b/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatErrorPage.java index 89415986941f..93d25fb2a053 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 @@ private Object createNativePage(ErrorPage errorPage) { .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/embedded/undertow/UndertowServletWebServerFactory.java b/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactory.java index 61c2cd3f78fb..911f4b3f89fe 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 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; @@ -279,10 +278,7 @@ private void configureSsl(Ssl ssl, int port, Builder builder) { Sequence.of(ssl.getCiphers())); } } - catch (NoSuchAlgorithmException ex) { - throw new IllegalStateException(ex); - } - catch (KeyManagementException ex) { + catch (NoSuchAlgorithmException | KeyManagementException ex) { throw new IllegalStateException(ex); } } @@ -418,14 +414,7 @@ private DeploymentManager createDeploymentManager( } 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) { @@ -488,8 +477,8 @@ private ClassLoader getServletClassLoader() { private ResourceManager getDocumentRootResourceManager() { File root = getCanonicalDocumentRoot(); List metaInfResourceUrls = getUrlsOfJarsWithMetaInfResources(); - List resourceJarUrls = new ArrayList(); - List resourceManagers = new ArrayList(); + List resourceJarUrls = new ArrayList<>(); + List resourceManagers = new ArrayList<>(); ResourceManager rootResourceManager = root.isDirectory() ? new FileResourceManager(root, 0) : new JarResourceManager(root); resourceManagers.add(rootResourceManager); 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 186b3d660477..4c0a4e6d4360 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 @@ private Collection getRegistrars() { // 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 0f65be6c8a2d..9cbb8bc6f546 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 @@ private Collection> getCustomizers() { 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 450199aa366f..0e074842c238 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,8 @@ private List> getOrderedBeansOfType( 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(), - o2.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) { @@ -238,7 +231,7 @@ public int compare(Entry o1, Entry o2) { } } beans.addAll(map.entrySet()); - Collections.sort(beans, comparator); + beans.sort(comparator); return beans; } 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 aaab11648935..6f7202eee729 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 @@ protected ServletWebServerFactory getWebServerFactory() { * @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 { @@ -273,13 +268,7 @@ protected void prepareWebApplicationContext(ServletContext servletContext) { + 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); 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 bbed22a8a866..dd88c2a639f3 100644 --- a/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java +++ b/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java @@ -103,16 +103,11 @@ private ExitCodeGenerator mockGenerator(int exitCode) { 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 5b2923fd8ecc..40e1e43c6be1 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 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 void specificApplicationContextInitializer() throws Exception { 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,7 @@ public void exitWithExplicitCode() throws Exception { 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 +753,8 @@ public void registerListener() throws Exception { 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,8 @@ public void registerListenerWithCustomMulticaster() throws Exception { 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 +834,7 @@ public void applicationListenerFromContextIsCalledWhenContextFailsRefreshBeforeL 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,7 @@ public void applicationListenerFromContextIsCalledWhenContextFailsRefreshAfterLi 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 +917,13 @@ public void webApplicationSwitchedOffInListener() throws Exception { 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 +1177,8 @@ static class ExitCodeCommandLineRunConfig { @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 +1189,18 @@ static class MappedExitCodeCommandLineRunConfig { @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 9651b0fdb246..b40914a982e7 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 @@ -76,16 +76,13 @@ public void validateReadyFlag() { 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((ApplicationListener) 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 ae8fa65f9cad..584e0f03c767 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 @@ -294,12 +294,8 @@ public void initializersCreatedOnceForChild() throws Exception { public void initializersIncludeDefaults() throws Exception { SpringApplicationBuilder application = new SpringApplicationBuilder( ExampleConfig.class).web(WebApplicationType.NONE).initializers( - new ApplicationContextInitializer() { - @Override - public void initialize( - ConfigurableApplicationContext applicationContext) { - } - }); + (ApplicationContextInitializer) 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 366e266aa6e7..3c8f189be0b1 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 @@ private void validateProfilePrecedence(String... profiles) { 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 397229e1dde1..ac18cad9d3d6 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 LoggerConfiguration getLoggerConfiguration(String loggerName) { @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/context/properties/ConfigurationPropertiesBindingPostProcessorTests.java b/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessorTests.java index ef2353950274..66305fbe4186 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 @@ -441,7 +441,7 @@ public void rebindableConfigurationProperties() throws Exception { 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/logging/java/JavaLoggingSystemTests.java b/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java index d56e516455f4..505cec769ebc 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,7 @@ */ 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 a2036f6ce76d..82abee934a95 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 void customizersShouldApply() throws Exception { @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 f1d7af42a576..a076d1f23a31 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 @@ -156,15 +156,10 @@ public void stopCalledWithoutStart() throws Exception { @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); - } - + .addServerCustomizers((JettyServerCustomizer) server -> { + ServerConnector connector = new ServerConnector(server); + connector.setPort(port); + server.addConnector(connector); }); } @@ -231,16 +226,13 @@ private void assertTimeout(JettyServletWebServerFactory factory, int expected) { @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((JettyServerCustomizer) 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(); @@ -282,15 +274,10 @@ public void customThreadPool() throws Exception { @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((JettyServerCustomizer) 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 1b32b6af26dc..1086da6a4c2e 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,19 @@ public void sslEnabledProtocolsConfiguration() throws Exception { @Test public void primaryConnectorPortClashThrowsIllegalStateException() throws InterruptedException, IOException { - doWithBlockedPort(new BlockedPortAction() { + doWithBlockedPort(port -> { + TomcatServletWebServerFactory factory = getFactory(); + factory.setPort(port); - @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 - } + try { + TomcatServletWebServerFactoryTests.this.webServer = factory + .getWebServer(); + TomcatServletWebServerFactoryTests.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 16f08e53a243..177957b74594 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 void basicSslClasspathKeyStore() throws Exception { 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( + (UndertowDeploymentInfoCustomizer) deploymentInfo -> contextPath.set(deploymentInfo.getContextPath())); this.webServer = factory.getWebServer(); assertThat(contextPath.get()).isEqualTo("/"); } @@ -211,13 +206,7 @@ private void testAccessLog(String prefix, String suffix, String expectedFile) @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"); - } - }); + .addBuilderCustomizers((UndertowBuilderCustomizer) builder -> builder.addHttpListener(port, "0.0.0.0")); } @Test(expected = SSLHandshakeException.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 f1abc115bba8..94a3908015a8 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 @@ private void addLambdaBeans(List called) { 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); 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 5d712a4a5904..4823bbffd1f1 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 @@ 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; @@ -217,18 +216,16 @@ public void startServletAndFilter() throws Exception { 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( + (ServletContextInitializer) servletContext -> { + try { + Thread.sleep(500); + date[0] = new Date(); + } + catch (InterruptedException ex) { + throw new ServletException(ex); + } + }); this.webServer.start(); assertThat(date[0]).isNotNull(); } @@ -237,12 +234,8 @@ public void onStartup(ServletContext servletContext) throws ServletException { 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( + (ServletContextInitializer) servletContext -> servletContext.addServlet("test", servlet).setLoadOnStartup(1)); assertThat(servlet.getInitCount()).isEqualTo(0); this.webServer.start(); assertThat(servlet.getInitCount()).isEqualTo(1); @@ -737,14 +730,8 @@ public void persistSessionInSpecificSessionStoreDir() throws Exception { 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); } @@ -836,17 +823,15 @@ public void mimeMappingsAreCorrectlyConfigured() throws Exception { 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( + (ServletContextInitializer) servletContext -> { + try { + rootResource.set(servletContext.getResource("/")); + } + catch (MalformedURLException ex) { + throw new ServletException(ex); + } + }); this.webServer.start(); assertThat(rootResource.get()).isNotNull(); } @@ -873,47 +858,37 @@ public void serverHeaderIsDisabledByDefault() throws Exception { @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); } - }); } @@ -954,11 +929,8 @@ public void jspServletIsNotInDevelopmentModeByDefault() throws Exception { @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( + (ServletContextInitializer) servletContext -> servletContext.addFilter("faulty", new Filter() { @Override public void init(FilterConfig filterConfig) throws ServletException { @@ -975,10 +947,7 @@ public void doFilter(ServletRequest request, ServletResponse response, 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 0adaaa44520f..f4a166fbd339 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 static class MockServletWebServer public MockServletWebServer(ServletContextInitializer[] initializers, int port) { super(Arrays.stream(initializers) - .map((i) -> (Initializer) (s) -> i.onStartup(s)) + .map((i) -> (Initializer) i::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 8094a1434602..1d69fbe00bdd 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.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 void mainClassHasSensibleDefault() throws Exception { @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 servletContext) -> { + try (AbstractApplicationContext context = (AbstractApplicationContext) new WithErrorPageFilterNotRegistered() + .createRootApplicationContext(servletContext)) { + assertThat(context.getBeansOfType(ErrorPageFilter.class)) + .hasSize(0); } }); try {