Use lambdas when possible

Replace anonymous inner classes with lambda declarations (when possible
using method references).

See gh-9781
This commit is contained in:
Emanuel Campolo
2017-07-24 23:11:47 -07:00
committed by Phillip Webb
parent d16af43664
commit 2626a3a795
150 changed files with 983 additions and 2596 deletions

View File

@@ -249,15 +249,7 @@ public class AutoConfigurationImportSelectorTests {
@Override
protected List<AutoConfigurationImportListener> getAutoConfigurationImportListeners() {
return Collections.<AutoConfigurationImportListener>singletonList(
new AutoConfigurationImportListener() {
@Override
public void onAutoConfigurationImportEvent(
AutoConfigurationImportEvent event) {
TestAutoConfigurationImportSelector.this.lastEvent = event;
}
});
(event) -> this.lastEvent = event);
}
public AutoConfigurationImportEvent getLastEvent() {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,7 +23,6 @@ import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.BatchConfigurer;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
@@ -35,9 +34,7 @@ import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.batch.support.transaction.ResourcelessTransactionManager;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
@@ -80,13 +77,8 @@ public class JobLauncherCommandLineRunnerTests {
PlatformTransactionManager transactionManager = this.context
.getBean(PlatformTransactionManager.class);
this.steps = new StepBuilderFactory(jobRepository, transactionManager);
this.step = this.steps.get("step").tasklet(new Tasklet() {
@Override
public RepeatStatus execute(StepContribution contribution,
ChunkContext chunkContext) throws Exception {
return null;
}
}).build();
Tasklet tasklet = (contribution, chunkContext) -> null;
this.step = this.steps.get("step").tasklet(tasklet).build();
this.job = this.jobs.get("job").start(this.step).build();
this.jobExplorer = this.context.getBean(JobExplorer.class);
this.runner = new JobLauncherCommandLineRunner(this.jobLauncher,
@@ -115,13 +107,8 @@ public class JobLauncherCommandLineRunnerTests {
@Test
public void retryFailedExecution() throws Exception {
this.job = this.jobs.get("job")
.start(this.steps.get("step").tasklet(new Tasklet() {
@Override
public RepeatStatus execute(StepContribution contribution,
ChunkContext chunkContext) throws Exception {
throw new RuntimeException("Planned");
}
}).build()).incrementer(new RunIdIncrementer()).build();
.start(this.steps.get("step").tasklet(throwingTasklet()).build())
.incrementer(new RunIdIncrementer()).build();
this.runner.execute(this.job, new JobParameters());
this.runner.execute(this.job, new JobParameters());
assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(1);
@@ -130,13 +117,8 @@ public class JobLauncherCommandLineRunnerTests {
@Test
public void retryFailedExecutionOnNonRestartableJob() throws Exception {
this.job = this.jobs.get("job").preventRestart()
.start(this.steps.get("step").tasklet(new Tasklet() {
@Override
public RepeatStatus execute(StepContribution contribution,
ChunkContext chunkContext) throws Exception {
throw new RuntimeException("Planned");
}
}).build()).incrementer(new RunIdIncrementer()).build();
.start(this.steps.get("step").tasklet(throwingTasklet()).build())
.incrementer(new RunIdIncrementer()).build();
this.runner.execute(this.job, new JobParameters());
this.runner.execute(this.job, new JobParameters());
// A failed job that is not restartable does not re-use the job params of
@@ -147,13 +129,8 @@ public class JobLauncherCommandLineRunnerTests {
@Test
public void retryFailedExecutionWithNonIdentifyingParameters() throws Exception {
this.job = this.jobs.get("job")
.start(this.steps.get("step").tasklet(new Tasklet() {
@Override
public RepeatStatus execute(StepContribution contribution,
ChunkContext chunkContext) throws Exception {
throw new RuntimeException("Planned");
}
}).build()).incrementer(new RunIdIncrementer()).build();
.start(this.steps.get("step").tasklet(throwingTasklet()).build())
.incrementer(new RunIdIncrementer()).build();
JobParameters jobParameters = new JobParametersBuilder().addLong("id", 1L, false)
.addLong("foo", 2L, false).toJobParameters();
this.runner.execute(this.job, jobParameters);
@@ -161,6 +138,12 @@ public class JobLauncherCommandLineRunnerTests {
assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(1);
}
private Tasklet throwingTasklet() {
return (contribution, chunkContext) -> {
throw new RuntimeException("Planned");
};
}
@Configuration
@EnableBatchProcessing
protected static class BatchConfiguration implements BatchConfigurer {

View File

@@ -19,7 +19,6 @@ package org.springframework.boot.autoconfigure.cache;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@@ -69,7 +68,6 @@ import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.interceptor.CacheOperationInvocationContext;
import org.springframework.cache.interceptor.CacheResolver;
import org.springframework.cache.jcache.JCacheCacheManager;
import org.springframework.cache.support.NoOpCacheManager;
@@ -965,16 +963,13 @@ public class CacheAutoConfigurationTests {
@Bean
JCacheManagerCustomizer myCustomizer() {
return new JCacheManagerCustomizer() {
@Override
public void customize(javax.cache.CacheManager cacheManager) {
MutableConfiguration<?, ?> config = new MutableConfiguration<>();
config.setExpiryPolicyFactory(
CreatedExpiryPolicy.factoryOf(Duration.TEN_MINUTES));
config.setStatisticsEnabled(true);
cacheManager.createCache("custom1", config);
cacheManager.destroyCache("bar");
}
return (cacheManager) -> {
MutableConfiguration<?, ?> config = new MutableConfiguration<>();
config.setExpiryPolicyFactory(
CreatedExpiryPolicy.factoryOf(Duration.TEN_MINUTES));
config.setStatisticsEnabled(true);
cacheManager.createCache("custom1", config);
cacheManager.destroyCache("bar");
};
}
@@ -1053,15 +1048,7 @@ public class CacheAutoConfigurationTests {
@Bean
// The @Bean annotation is important, see CachingConfigurerSupport Javadoc
public CacheResolver cacheResolver() {
return new CacheResolver() {
@Override
public Collection<? extends Cache> resolveCaches(
CacheOperationInvocationContext<?> context) {
return Collections.singleton(mock(Cache.class));
}
};
return (context) -> Collections.singleton(mock(Cache.class));
}

View File

@@ -27,9 +27,6 @@ import javax.cache.configuration.Configuration;
import javax.cache.configuration.OptionalFeature;
import javax.cache.spi.CachingProvider;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
@@ -52,24 +49,17 @@ public class MockCachingProvider implements CachingProvider {
given(cacheManager.getClassLoader()).willReturn(classLoader);
final Map<String, Cache> caches = new HashMap<>();
given(cacheManager.getCacheNames()).willReturn(caches.keySet());
given(cacheManager.getCache(anyString())).willAnswer(new Answer<Cache>() {
@Override
public Cache answer(InvocationOnMock invocationOnMock) throws Throwable {
String cacheName = (String) invocationOnMock.getArguments()[0];
return caches.get(cacheName);
}
given(cacheManager.getCache(anyString())).willAnswer((invocation) -> {
String cacheName = (String) invocation.getArguments()[0];
return caches.get(cacheName);
});
given(cacheManager.createCache(anyString(), any(Configuration.class)))
.will(new Answer<Cache>() {
@Override
public Cache answer(InvocationOnMock invocationOnMock)
throws Throwable {
String cacheName = (String) invocationOnMock.getArguments()[0];
Cache cache = mock(Cache.class);
given(cache.getName()).willReturn(cacheName);
caches.put(cacheName, cache);
return cache;
}
.will((invocation) -> {
String cacheName = (String) invocation.getArguments()[0];
Cache cache = mock(Cache.class);
given(cache.getName()).willReturn(cacheName);
caches.put(cacheName, cache);
return cache;
});
return cacheManager;
}

View File

@@ -143,12 +143,7 @@ public class CassandraAutoConfigurationTests {
@Bean
public ClusterBuilderCustomizer customizer() {
return new ClusterBuilderCustomizer() {
@Override
public void customize(Cluster.Builder clusterBuilder) {
clusterBuilder.withClusterName("overridden-name");
}
};
return (clusterBuilder) -> clusterBuilder.withClusterName("overridden-name");
}
}

View File

@@ -24,7 +24,6 @@ import com.google.gson.Gson;
import io.searchbox.action.Action;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.client.config.HttpClientConfig;
import io.searchbox.client.http.JestHttpClient;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
@@ -183,14 +182,7 @@ public class JestAutoConfigurationTests {
@Bean
public HttpClientConfigBuilderCustomizer customizer() {
return new HttpClientConfigBuilderCustomizer() {
@Override
public void customize(HttpClientConfig.Builder builder) {
builder.gson(BuilderCustomizer.this.gson);
}
};
return (builder) -> builder.gson(BuilderCustomizer.this.gson);
}
Gson getGson() {

View File

@@ -533,13 +533,7 @@ public class JacksonAutoConfigurationTests {
@Bean
public Jackson2ObjectMapperBuilderCustomizer customDateFormat() {
return new Jackson2ObjectMapperBuilderCustomizer() {
@Override
public void customize(
Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder) {
jackson2ObjectMapperBuilder.dateFormat(new MyDateFormat());
}
};
return (builder) -> builder.dateFormat(new MyDateFormat());
}
}

View File

@@ -350,14 +350,8 @@ public class DataSourceInitializerTests {
@Override
public Resource[] getResources(String locationPattern) throws IOException {
Resource[] resources = this.resolver.getResources(locationPattern);
Arrays.sort(resources, new Comparator<Resource>() {
@Override
public int compare(Resource r1, Resource r2) {
return r2.getFilename().compareTo(r1.getFilename());
}
});
Arrays.sort(resources,
Comparator.comparing(Resource::getFilename).reversed());
return resources;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,13 +16,9 @@
package org.springframework.boot.autoconfigure.jdbc.metadata;
import java.sql.Connection;
import java.sql.SQLException;
import org.junit.Test;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ConnectionCallback;
import org.springframework.jdbc.core.JdbcTemplate;
@@ -57,13 +53,7 @@ public abstract class AbstractDataSourcePoolMetadataTests<D extends AbstractData
// Make sure the pool is initialized
JdbcTemplate jdbcTemplate = new JdbcTemplate(
getDataSourceMetadata().getDataSource());
jdbcTemplate.execute(new ConnectionCallback<Void>() {
@Override
public Void doInConnection(Connection connection)
throws SQLException, DataAccessException {
return null;
}
});
jdbcTemplate.execute((ConnectionCallback<Void>) (connection) -> null);
assertThat(getDataSourceMetadata().getActive()).isEqualTo(Integer.valueOf(0));
assertThat(getDataSourceMetadata().getUsage()).isEqualTo(Float.valueOf(0));
}
@@ -72,16 +62,10 @@ public abstract class AbstractDataSourcePoolMetadataTests<D extends AbstractData
public void getPoolSizeOneConnection() {
JdbcTemplate jdbcTemplate = new JdbcTemplate(
getDataSourceMetadata().getDataSource());
jdbcTemplate.execute(new ConnectionCallback<Void>() {
@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<Void>) (connection) -> {
assertThat(getDataSourceMetadata().getActive()).isEqualTo(Integer.valueOf(1));
assertThat(getDataSourceMetadata().getUsage()).isEqualTo(Float.valueOf(0.5F));
return null;
});
}
@@ -89,25 +73,13 @@ public abstract class AbstractDataSourcePoolMetadataTests<D extends AbstractData
public void getPoolSizeTwoConnections() {
final JdbcTemplate jdbcTemplate = new JdbcTemplate(
getDataSourceMetadata().getDataSource());
jdbcTemplate.execute(new ConnectionCallback<Void>() {
@Override
public Void doInConnection(Connection connection)
throws SQLException, DataAccessException {
jdbcTemplate.execute(new ConnectionCallback<Void>() {
@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<Void>) (connection) -> {
jdbcTemplate.execute((ConnectionCallback<Void>) connection1 -> {
assertThat(getDataSourceMetadata().getActive()).isEqualTo(2);
assertThat(getDataSourceMetadata().getUsage()).isEqualTo(1.0f);
return null;
}
});
return null;
});
}

View File

@@ -23,7 +23,6 @@ import java.util.UUID;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.artemis.api.core.TransportConfiguration;
@@ -336,25 +335,22 @@ public class ArtemisAutoConfigurationTests {
public void checkDestination(final String name, final boolean pubSub,
final boolean shouldExist) {
this.jmsTemplate.execute(new SessionCallback<Void>() {
@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<Void>) (session) -> {
try {
Destination destination = this.destinationResolver
.resolveDestinationName(session, name, pubSub);
if (!shouldExist) {
throw new IllegalStateException("Destination '" + name
+ "' was not expected but got " + destination);
}
catch (JMSException e) {
if (shouldExist) {
throw new IllegalStateException("Destination '" + name
+ "' was expected but got " + e.getMessage());
}
}
return null;
}
catch (JMSException ex) {
if (shouldExist) {
throw new IllegalStateException("Destination '" + name
+ "' was expected but got " + ex.getMessage());
}
}
return null;
});
}
@@ -408,13 +404,9 @@ public class ArtemisAutoConfigurationTests {
@Bean
public ArtemisConfigurationCustomizer myArtemisCustomize() {
return new ArtemisConfigurationCustomizer() {
@Override
public void customize(
org.apache.activemq.artemis.core.config.Configuration configuration) {
configuration.setClusterPassword("Foobar");
configuration.setName("customFooBar");
}
return (configuration) -> {
configuration.setClusterPassword("Foobar");
configuration.setName("customFooBar");
};
}

View File

@@ -62,9 +62,8 @@ public class AutoConfigurationReportLoggingInitializerTests {
this.initializer.initialize(context);
context.register(Config.class);
context.refresh();
withDebugLogging(() -> {
this.initializer.onApplicationEvent(new ContextRefreshedEvent(context));
});
withDebugLogging(() -> this.initializer
.onApplicationEvent(new ContextRefreshedEvent(context)));
assertThat(this.outputCapture.toString()).contains("AUTO-CONFIGURATION REPORT");
}
@@ -78,10 +77,9 @@ public class AutoConfigurationReportLoggingInitializerTests {
fail("Did not error");
}
catch (Exception ex) {
withDebugLogging(() -> {
this.initializer.onApplicationEvent(new ApplicationFailedEvent(
new SpringApplication(), new String[0], context, ex));
});
withDebugLogging(
() -> this.initializer.onApplicationEvent(new ApplicationFailedEvent(
new SpringApplication(), new String[0], context, ex)));
}
assertThat(this.outputCapture.toString()).contains("AUTO-CONFIGURATION REPORT");
}
@@ -112,9 +110,8 @@ public class AutoConfigurationReportLoggingInitializerTests {
ConditionEvaluationReport.get(context.getBeanFactory())
.recordExclusions(Arrays.asList("com.foo.Bar"));
context.refresh();
withDebugLogging(() -> {
this.initializer.onApplicationEvent(new ContextRefreshedEvent(context));
});
withDebugLogging(() -> this.initializer
.onApplicationEvent(new ContextRefreshedEvent(context)));
assertThat(this.outputCapture.toString())
.contains("not a servlet web application (OnWebApplicationCondition)");
}

View File

@@ -50,7 +50,6 @@ import org.springframework.security.config.annotation.authentication.configurers
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetailsService;
@@ -407,14 +406,8 @@ public class SecurityAutoConfigurationTests {
@Bean
public AuthenticationManager myAuthenticationManager() {
this.authenticationManager = new AuthenticationManager() {
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
return new TestingAuthenticationToken("foo", "bar");
}
};
this.authenticationManager = (
authentication) -> new TestingAuthenticationToken("foo", "bar");
return this.authenticationManager;
}
@@ -446,14 +439,8 @@ public class SecurityAutoConfigurationTests {
@Override
protected void configure(HttpSecurity http) throws Exception {
this.authenticationManager = new AuthenticationManager() {
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
return WorkaroundSecurityCustomizer.this.builder.getOrBuild()
.authenticate(authentication);
}
};
this.authenticationManager = (authentication) -> this.builder.getOrBuild()
.authenticate(authentication);
}
}

View File

@@ -16,10 +16,6 @@
package org.springframework.boot.autoconfigure.security.oauth2.resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
@@ -45,14 +41,9 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.mock.http.client.MockClientHttpResponse;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails;
@@ -299,16 +290,8 @@ public class ResourceServerTokenServicesConfigurationTests {
@Bean
AuthoritiesExtractor authoritiesExtractor() {
return new AuthoritiesExtractor() {
@Override
public List<GrantedAuthority> extractAuthorities(
Map<String, Object> map) {
return AuthorityUtils
.commaSeparatedStringToAuthorityList("ROLE_ADMIN");
}
};
return (map) -> AuthorityUtils
.commaSeparatedStringToAuthorityList("ROLE_ADMIN");
}
}
@@ -318,14 +301,7 @@ public class ResourceServerTokenServicesConfigurationTests {
@Bean
PrincipalExtractor principalExtractor() {
return new PrincipalExtractor() {
@Override
public Object extractPrincipal(Map<String, Object> map) {
return "boot";
}
};
return (map) -> "boot";
}
}
@@ -372,15 +348,8 @@ public class ResourceServerTokenServicesConfigurationTests {
@Override
public void customize(OAuth2RestTemplate template) {
template.getInterceptors().add(new ClientHttpRequestInterceptor() {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
return execution.execute(request, body);
}
});
template.getInterceptors()
.add((request, body, execution) -> execution.execute(request, body));
}
}
@@ -434,18 +403,12 @@ public class ResourceServerTokenServicesConfigurationTests {
@Override
public void customize(RestTemplate template) {
template.getInterceptors().add(new ClientHttpRequestInterceptor() {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
String payload = "{\"value\":\"FOO\"}";
MockClientHttpResponse response = new MockClientHttpResponse(
payload.getBytes(), HttpStatus.OK);
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
return response;
}
template.getInterceptors().add((request, body, execution) -> {
String payload = "{\"value\":\"FOO\"}";
MockClientHttpResponse response = new MockClientHttpResponse(
payload.getBytes(), HttpStatus.OK);
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
return response;
});
}

View File

@@ -154,13 +154,8 @@ public class RestTemplateAutoConfigurationTests {
}
private void breakBuilderOnNextCall(RestTemplateBuilder builder) {
builder.additionalCustomizers(new RestTemplateCustomizer() {
@Override
public void customize(RestTemplate restTemplate) {
throw new IllegalStateException();
}
builder.additionalCustomizers((restTemplate) -> {
throw new IllegalStateException();
});
}

View File

@@ -69,7 +69,7 @@ public class MockServletWebServerFactory extends AbstractServletWebServerFactory
public MockServletWebServer(ServletContextInitializer[] initializers, int port) {
super(Arrays.stream(initializers)
.map((i) -> (Initializer) (s) -> i.onStartup(s))
.map((initializer) -> (Initializer) initializer::onStartup)
.toArray(Initializer[]::new), port);
}