Skip to content

Replace lambda with method reference #40974

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,12 @@ public enum UpgradePolicy implements BiPredicate<DependencyVersion, DependencyVe
/**
* Minor versions of the current major version.
*/
SAME_MAJOR_VERSION((candidate, current) -> candidate.isSameMajor(current)),
SAME_MAJOR_VERSION(DependencyVersion::isSameMajor),

/**
* Patch versions of the current minor version.
*/
SAME_MINOR_VERSION((candidate, current) -> candidate.isSameMinor(current));
SAME_MINOR_VERSION(DependencyVersion::isSameMinor);

private final BiPredicate<DependencyVersion, DependencyVersion> delegate;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
import org.quartz.Trigger.TriggerState;
import org.quartz.TriggerKey;
import org.quartz.impl.matchers.GroupMatcher;
import org.quartz.utils.Key;

import org.springframework.boot.actuate.endpoint.OperationResponseBody;
import org.springframework.boot.actuate.endpoint.SanitizableData;
Expand Down Expand Up @@ -100,7 +101,7 @@ public QuartzGroupsDescriptor quartzJobGroups() throws SchedulerException {
for (String groupName : this.scheduler.getJobGroupNames()) {
List<String> jobs = this.scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))
.stream()
.map((key) -> key.getName())
.map(Key::getName)
.toList();
result.put(groupName, Collections.singletonMap("jobs", jobs));
}
Expand All @@ -121,7 +122,7 @@ public QuartzGroupsDescriptor quartzTriggerGroups() throws SchedulerException {
groupDetails.put("triggers",
this.scheduler.getTriggerKeys(GroupMatcher.triggerGroupEquals(groupName))
.stream()
.map((key) -> key.getName())
.map(Key::getName)
.toList());
result.put(groupName, groupDetails);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,9 +148,9 @@ public void setPhysicalStrategy(String physicalStrategy) {

private void applyNamingStrategies(Map<String, Object> properties) {
applyNamingStrategy(properties, AvailableSettings.IMPLICIT_NAMING_STRATEGY, this.implicitStrategy,
() -> SpringImplicitNamingStrategy.class.getName());
SpringImplicitNamingStrategy.class::getName);
applyNamingStrategy(properties, AvailableSettings.PHYSICAL_NAMING_STRATEGY, this.physicalStrategy,
() -> CamelCaseToUnderscoresNamingStrategy.class.getName());
CamelCaseToUnderscoresNamingStrategy.class::getName);
}

private void applyNamingStrategy(Map<String, Object> properties, String key, Object strategy,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity.CsrfSpec;
import org.springframework.security.core.userdetails.MapReactiveUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
Expand Down Expand Up @@ -161,7 +162,7 @@ static class SecurityConfig {

@Bean
SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) {
return http.csrf((spec) -> spec.disable())
return http.csrf(CsrfSpec::disable)
// Demonstrate that method security works
// Best practice to use both for defense in depth
.authorizeExchange((requests) -> requests.anyExchange().permitAll())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
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.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
Expand Down Expand Up @@ -154,7 +155,7 @@ static class SecurityConfig {

@Bean
DefaultSecurityFilterChain springWebFilterChain(HttpSecurity http) throws Exception {
return http.csrf((c) -> c.disable())
return http.csrf(AbstractHttpConfigurer::disable)
// Demonstrate that method security works
// Best practice to use both for defense in depth
.authorizeHttpRequests((requests) -> requests.anyRequest().permitAll())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ void logsDebugOnContextRefresh(CapturedOutput output) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
this.initializer.initialize(context);
context.register(Config.class);
withDebugLogging(() -> context.refresh());
withDebugLogging(context::refresh);
assertThat(output).contains("CONDITIONS EVALUATION REPORT");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

Expand All @@ -49,7 +50,7 @@ class RemoteDevtoolsSecurityConfiguration {
SecurityFilterChain devtoolsSecurityFilterChain(HttpSecurity http) throws Exception {
http.securityMatcher(new AntPathRequestMatcher(this.url));
http.authorizeHttpRequests((requests) -> requests.anyRequest().anonymous());
http.csrf((csrf) -> csrf.disable());
http.csrf(AbstractHttpConfigurer::disable);
return http.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ private void setupWatcher(long pollingInterval, long quietPeriod) {
private void setupWatcher(long pollingInterval, long quietPeriod, SnapshotStateRepository snapshotStateRepository) {
this.watcher = new FileSystemWatcher(false, Duration.ofMillis(pollingInterval), Duration.ofMillis(quietPeriod),
snapshotStateRepository);
this.watcher.addListener((changeSet) -> FileSystemWatcherTests.this.changes.add(changeSet));
this.watcher.addListener(FileSystemWatcherTests.this.changes::add);
}

private File startWithNewDirectory() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ void toStringReturnsServiceName() {
}

private DefaultRunningService createRunningService(boolean psResponseHasImage) {
DockerHost host = DockerHost.get("192.168.1.1", () -> Collections.emptyList());
DockerHost host = DockerHost.get("192.168.1.1", Collections::emptyList);
String id = "123";
String name = "my-service";
String image = "redis";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ class DockerHostTests {

private static final Function<String, String> NO_SYSTEM_ENV = (key) -> null;

private static final Supplier<List<DockerCliContextResponse>> NO_CONTEXT = () -> Collections.emptyList();
private static final Supplier<List<DockerCliContextResponse>> NO_CONTEXT = Collections::emptyList;

@Test
void getWhenHasHost() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,14 @@ void setup() {

@Test
void checkWhenServerWritesData() throws Exception {
withServer((socket) -> socket.getOutputStream().write('!'), (port) -> check(port));
withServer((socket) -> socket.getOutputStream().write('!'), this::check);
}

@Test
void checkWhenNoSocketOutput() throws Exception {
// Simulate waiting for traffic from client to server. The sleep duration must
// be longer than the read timeout of the ready check!
withServer((socket) -> sleep(Duration.ofSeconds(10)), (port) -> check(port));
withServer((socket) -> sleep(Duration.ofSeconds(10)), this::check);
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
import org.springframework.core.annotation.Order;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer.FrameOptionsConfig;
import org.springframework.security.web.SecurityFilterChain;

@Profile("dev")
Expand All @@ -35,8 +37,8 @@ public class DevProfileSecurityConfiguration {
SecurityFilterChain h2ConsoleSecurityFilterChain(HttpSecurity http) throws Exception {
http.securityMatcher(PathRequest.toH2Console());
http.authorizeHttpRequests(yourCustomAuthorization());
http.csrf((csrf) -> csrf.disable());
http.headers((headers) -> headers.frameOptions((frame) -> frame.sameOrigin()));
http.csrf(AbstractHttpConfigurer::disable);
http.headers((headers) -> headers.frameOptions(FrameOptionsConfig::sameOrigin));
return http.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class ExcludeFilterApplicationContextInitializerTests {
void testConfigurationIsExcluded() {
SpringApplication application = new SpringApplication(TestApplication.class);
application.setWebApplicationType(WebApplicationType.NONE);
AssertableApplicationContext applicationContext = AssertableApplicationContext.get(() -> application.run());
AssertableApplicationContext applicationContext = AssertableApplicationContext.get(application::run);
assertThat(applicationContext).hasSingleBean(TestApplication.class);
assertThat(applicationContext).doesNotHaveBean(ExcludedTestConfiguration.class);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ void getConnectionDetailsHasOrigin() {
void getContainerWhenNotInitializedThrowsException() {
TestContainerConnectionDetailsFactory factory = new TestContainerConnectionDetailsFactory();
TestContainerConnectionDetails connectionDetails = getConnectionDetails(factory, this.source);
assertThatIllegalStateException().isThrownBy(() -> connectionDetails.callGetContainer())
assertThatIllegalStateException().isThrownBy(connectionDetails::callGetContainer)
.withMessage("Container cannot be obtained before the connection details bean has been initialized");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ void randomWherePrefixIsNullThrowsException() {
void inTaggedFormWhenHasDigestThrowsException() {
ImageReference reference = ImageReference
.of("ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d");
assertThatIllegalStateException().isThrownBy(() -> reference.inTaggedForm())
assertThatIllegalStateException().isThrownBy(reference::inTaggedForm)
.withMessage(
"Image reference 'docker.io/library/ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d' cannot contain a digest");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ public void buildInfo(Action<BuildInfo> configurer) {
tasks.named(JavaPlugin.CLASSES_TASK_NAME).configure((task) -> task.dependsOn(bootBuildInfo));
bootBuildInfo.configure((buildInfo) -> buildInfo.getProperties()
.getArtifact()
.convention(this.project.provider(() -> determineArtifactBaseName())));
.convention(this.project.provider(this::determineArtifactBaseName)));
});
if (configurer != null) {
bootBuildInfo.configure(configurer);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ private void configureAotTask(Project project, SourceSet sourceSet, AbstractAot
task.getClassesOutput()
.set(project.getLayout().getBuildDirectory().dir("generated/" + sourceSet.getName() + "Classes"));
task.getGroupId().set(project.provider(() -> String.valueOf(project.getGroup())));
task.getArtifactId().set(project.provider(() -> project.getName()));
task.getArtifactId().set(project.provider(project::getName));
configureToolchainConvention(project, task);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -719,7 +719,7 @@ void iteratorWhenClosedLater() throws IOException {
Iterator<JarEntry> iterator = this.jarFile.iterator();
iterator.next();
this.jarFile.close();
assertThatZipFileClosedIsThrownBy(() -> iterator.hasNext());
assertThatZipFileClosedIsThrownBy(iterator::hasNext);
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ void getCommentReturnsComment() throws IOException {
void getCommentWhenClosedThrowsException() throws IOException {
try (NestedJarFile jar = new NestedJarFile(this.file)) {
jar.close();
assertThatIllegalStateException().isThrownBy(() -> jar.getComment()).withMessage("Zip file closed");
assertThatIllegalStateException().isThrownBy(jar::getComment).withMessage("Zip file closed");
}
}

Expand Down Expand Up @@ -269,7 +269,7 @@ void sizeReturnsSize() throws IOException {
void sizeWhenClosedThrowsException() throws Exception {
try (NestedJarFile jar = new NestedJarFile(this.file)) {
jar.close();
assertThatIllegalStateException().isThrownBy(() -> jar.size()).withMessage("Zip file closed");
assertThatIllegalStateException().isThrownBy(jar::size).withMessage("Zip file closed");
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ void getPermissionReturnJarConnectionPermission() throws IOException {
@Test
void getInputStreamWhenNotNestedAndHasNoEntryThrowsException() throws Exception {
JarUrlConnection connection = JarUrlConnection.open(JarUrl.create(this.file));
assertThatIOException().isThrownBy(() -> connection.getInputStream()).withMessage("no entry name specified");
assertThatIOException().isThrownBy(connection::getInputStream).withMessage("no entry name specified");
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ void getPropertySourcesWhenUnavailableThrowsException() {
Environment environment = mock(Environment.class);
given(applicationContext.getEnvironment()).willReturn(environment);
PropertySourcesDeducer deducer = new PropertySourcesDeducer(applicationContext);
assertThatIllegalStateException().isThrownBy(() -> deducer.getPropertySources())
assertThatIllegalStateException().isThrownBy(deducer::getPropertySources)
.withMessage("Unable to obtain PropertySources from PropertySourcesPlaceholderConfigurer or Environment");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ void getNameWhenCustomReturnsName() {
@Test
void getLevelWhenCustomThrowsException() {
LevelConfiguration configuration = LevelConfiguration.ofCustom("FINE");
assertThatIllegalStateException().isThrownBy(() -> configuration.getLevel())
assertThatIllegalStateException().isThrownBy(configuration::getLevel)
.withMessage("Unable to provide LogLevel for 'FINE'");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package org.springframework.boot.logging.log4j2;

import java.lang.reflect.Method;
import java.util.stream.Stream;

import org.apache.logging.log4j.LogManager;
Expand Down Expand Up @@ -46,8 +47,7 @@ void propertySourceHasDisabledShutdownHook() {

@Test
void allDefaultMethodsAreImplemented() {
assertThat(Stream.of(SpringBootPropertySource.class.getMethods()).filter((method) -> method.isDefault()))
.isEmpty();
assertThat(Stream.of(SpringBootPropertySource.class.getMethods()).filter(Method::isDefault)).isEmpty();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ void noExceptionsAreThrownWhenBeforeInitializeIsCalledInParallel() {
List<Thread> threads = new ArrayList<>();
List<Throwable> exceptions = new CopyOnWriteArrayList<>();
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(() -> this.loggingSystem.beforeInitialize());
Thread thread = new Thread(this.loggingSystem::beforeInitialize);
thread.setUncaughtExceptionHandler((t, ex) -> exceptions.add(ex));
threads.add(thread);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package org.springframework.boot.sql.init;

import java.util.Arrays;
import java.util.List;

import org.junit.jupiter.api.Test;

Expand Down Expand Up @@ -59,7 +60,7 @@ void whenContinueOnErrorIsFalseThenInitializationFailsOnError() {
DatabaseInitializationSettings settings = new DatabaseInitializationSettings();
settings.setDataLocations(Arrays.asList("data.sql"));
T initializer = createEmbeddedDatabaseInitializer(settings);
assertThatExceptionOfType(DataAccessException.class).isThrownBy(() -> initializer.initializeDatabase());
assertThatExceptionOfType(DataAccessException.class).isThrownBy(initializer::initializeDatabase);
assertThatDatabaseWasAccessed(initializer);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ void getKeyManagerFactoryWhenHasAliasNotInStoreThrowsException() throws Exceptio
SslStoreBundle storeBundle = SslStoreBundle.of(keyStore, null, null);
DefaultSslManagerBundle bundle = new TestDefaultSslManagerBundle(storeBundle,
SslBundleKey.of("secret", "alias"));
assertThatIllegalStateException().isThrownBy(() -> bundle.getKeyManagerFactory())
assertThatIllegalStateException().isThrownBy(bundle::getKeyManagerFactory)
.withMessage("Keystore does not contain alias 'alias'");
}

Expand All @@ -100,7 +100,7 @@ void getKeyManagerFactoryWhenHasAliasNotDeterminedInStoreThrowsException() throw
SslStoreBundle storeBundle = SslStoreBundle.of(keyStore, null, null);
DefaultSslManagerBundle bundle = new TestDefaultSslManagerBundle(storeBundle,
SslBundleKey.of("secret", "alias"));
assertThatIllegalStateException().isThrownBy(() -> bundle.getKeyManagerFactory())
assertThatIllegalStateException().isThrownBy(bundle::getKeyManagerFactory)
.withMessage("Could not determine if keystore contains alias 'alias'");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ void cleanUp() {

@Test
void whenThereIsNoWebServerFactoryBeanThenContextRefreshWillFail() {
assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() -> this.context.refresh())
assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(this.context::refresh)
.havingRootCause()
.withMessageContaining(
"Unable to start ReactiveWebServerApplicationContext due to missing ReactiveWebServerFactory bean");
Expand All @@ -68,7 +68,7 @@ void whenThereIsNoWebServerFactoryBeanThenContextRefreshWillFail() {
@Test
void whenThereIsNoHttpHandlerBeanThenContextRefreshWillFail() {
addWebServerFactoryBean();
assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() -> this.context.refresh())
assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(this.context::refresh)
.havingRootCause()
.withMessageContaining("Unable to start ReactiveWebApplicationContext due to missing HttpHandler bean");
}
Expand All @@ -77,7 +77,7 @@ void whenThereIsNoHttpHandlerBeanThenContextRefreshWillFail() {
void whenThereAreMultipleWebServerFactoryBeansThenContextRefreshWillFail() {
addWebServerFactoryBean();
addWebServerFactoryBean("anotherWebServerFactory");
assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() -> this.context.refresh())
assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(this.context::refresh)
.havingRootCause()
.withMessageContaining(
"Unable to start ReactiveWebApplicationContext due to multiple ReactiveWebServerFactory beans");
Expand All @@ -88,7 +88,7 @@ void whenThereAreMultipleHttpHandlerBeansThenContextRefreshWillFail() {
addWebServerFactoryBean();
addHttpHandlerBean("httpHandler1");
addHttpHandlerBean("httpHandler2");
assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() -> this.context.refresh())
assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(this.context::refresh)
.havingRootCause()
.withMessageContaining("Unable to start ReactiveWebApplicationContext due to multiple HttpHandler beans");
}
Expand Down Expand Up @@ -164,7 +164,7 @@ void whenTheContextIsRefreshedThenASubsequentRefreshAttemptWillFail() {
addWebServerFactoryBean();
addHttpHandlerBean();
this.context.refresh();
assertThatIllegalStateException().isThrownBy(() -> this.context.refresh())
assertThatIllegalStateException().isThrownBy(this.context::refresh)
.withMessageContaining("multiple refresh attempts");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ void withSpecificDispatcherTypesEnumSet() throws Exception {

@Test
void failsWithDoubleRegistration() {
assertThatIllegalStateException().isThrownBy(() -> doubleRegistration())
assertThatIllegalStateException().isThrownBy(this::doubleRegistration)
.withMessage("Failed to register 'filter double-registration' on the "
+ "servlet context. Possibly already registered?");
}
Expand Down
Loading
Loading