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

@@ -28,7 +28,6 @@ import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import org.springframework.boot.devtools.filewatch.ChangedFile;
import org.springframework.boot.devtools.filewatch.FileSystemWatcher;
import org.springframework.boot.devtools.filewatch.FileSystemWatcherFactory;
import org.springframework.context.ApplicationListener;
@@ -113,14 +112,7 @@ public class ClassPathFileSystemWatcherTests {
@Bean
public ClassPathRestartStrategy restartStrategy() {
return new ClassPathRestartStrategy() {
@Override
public boolean isRestartRequired(ChangedFile file) {
return false;
}
};
return (file) -> false;
}
@Bean

View File

@@ -17,7 +17,6 @@
package org.springframework.boot.devtools.filewatch;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -221,12 +220,7 @@ public class FileSystemWatcherTests {
File folder = this.temp.newFolder();
final Set<ChangedFiles> listener2Changes = new LinkedHashSet<>();
this.watcher.addSourceFolder(folder);
this.watcher.addListener(new FileChangeListener() {
@Override
public void onChange(Set<ChangedFiles> changeSet) {
listener2Changes.addAll(changeSet);
}
});
this.watcher.addListener(listener2Changes::addAll);
this.watcher.start();
File file = touch(new File(folder, "test.txt"));
this.watcher.stopAfter(1);
@@ -262,14 +256,8 @@ public class FileSystemWatcherTests {
File file = touch(new File(folder, "file.txt"));
File trigger = touch(new File(folder, "trigger.txt"));
this.watcher.addSourceFolder(folder);
this.watcher.setTriggerFilter(new FileFilter() {
@Override
public boolean accept(File file) {
return file.getName().equals("trigger.txt");
}
});
this.watcher.setTriggerFilter(
(candidate) -> candidate.getName().equals("trigger.txt"));
this.watcher.start();
FileCopyUtils.copy("abc".getBytes(), file);
Thread.sleep(100);
@@ -285,12 +273,8 @@ public class FileSystemWatcherTests {
private void setupWatcher(long pollingInterval, long quietPeriod) {
this.watcher = new FileSystemWatcher(false, pollingInterval, quietPeriod);
this.watcher.addListener(new FileChangeListener() {
@Override
public void onChange(Set<ChangedFiles> changeSet) {
FileSystemWatcherTests.this.changes.add(changeSet);
}
});
this.watcher.addListener(
(changeSet) -> FileSystemWatcherTests.this.changes.add(changeSet));
}
private File startWithNewFolder() throws IOException {

View File

@@ -55,12 +55,7 @@ public class MainMethodTests {
@Test
public void validMainMethod() throws Exception {
MainMethod method = new TestThread(new Runnable() {
@Override
public void run() {
Valid.main();
}
}).test();
MainMethod method = new TestThread(Valid::main).test();
assertThat(method.getMethod()).isEqualTo(this.actualMain);
assertThat(method.getDeclaringClassName())
.isEqualTo(this.actualMain.getDeclaringClass().getName());
@@ -70,24 +65,14 @@ public class MainMethodTests {
public void missingArgsMainMethod() throws Exception {
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("Unable to find main method");
new TestThread(new Runnable() {
@Override
public void run() {
MissingArgs.main();
}
}).test();
new TestThread(MissingArgs::main).test();
}
@Test
public void nonStatic() throws Exception {
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("Unable to find main method");
new TestThread(new Runnable() {
@Override
public void run() {
new NonStaticMain().main();
}
}).test();
new TestThread(() -> new NonStaticMain().main()).test();
}
private static class TestThread extends Thread {

View File

@@ -19,13 +19,10 @@ package org.springframework.boot.devtools.restart;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadFactory;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.beans.factory.ObjectFactory;
@@ -64,30 +61,17 @@ public class MockRestarter implements TestRule {
Restarter.setInstance(this.mock);
given(this.mock.getInitialUrls()).willReturn(new URL[] {});
given(this.mock.getOrAddAttribute(anyString(), (ObjectFactory) any()))
.willAnswer(new Answer<Object>() {
@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() {

View File

@@ -67,14 +67,7 @@ public class OnInitializedRestarterConditionTests {
@Test
public void initialized() throws Exception {
Thread thread = new Thread() {
@Override
public void run() {
TestInitialized.main();
};
};
Thread thread = new Thread(TestInitialized::main);
thread.start();
synchronized (wait) {
wait.wait();

View File

@@ -28,7 +28,6 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile;
import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile.Kind;
@@ -84,14 +83,7 @@ public class RestarterTests {
@Test
public void testRestart() throws Exception {
Restarter.clearInstance();
Thread thread = new Thread() {
@Override
public void run() {
SampleApplication.main();
};
};
Thread thread = new Thread(SampleApplication::main);
thread.start();
Thread.sleep(2600);
String output = this.out.toString();
@@ -150,12 +142,7 @@ public class RestarterTests {
@Test
@SuppressWarnings("rawtypes")
public void getOrAddAttributeWithExistingAttribute() throws Exception {
Restarter.getInstance().getOrAddAttribute("x", new ObjectFactory<String>() {
@Override
public String getObject() throws BeansException {
return "abc";
}
});
Restarter.getInstance().getOrAddAttribute("x", () -> "abc");
ObjectFactory objectFactory = mock(ObjectFactory.class);
Object attribute = Restarter.getInstance().getOrAddAttribute("x", objectFactory);
assertThat(attribute).isEqualTo("abc");
@@ -166,19 +153,16 @@ public class RestarterTests {
public void getThreadFactory() throws Exception {
final ClassLoader parentLoader = Thread.currentThread().getContextClassLoader();
final ClassLoader contextClassLoader = new URLClassLoader(new URL[0]);
Thread thread = new Thread() {
@Override
public void run() {
Runnable runnable = mock(Runnable.class);
Thread regular = new Thread();
ThreadFactory factory = Restarter.getInstance().getThreadFactory();
Thread viaFactory = factory.newThread(runnable);
// Regular threads will inherit the current thread
assertThat(regular.getContextClassLoader()).isEqualTo(contextClassLoader);
// Factory threads should inherit from the initial thread
assertThat(viaFactory.getContextClassLoader()).isEqualTo(parentLoader);
};
};
Thread thread = new Thread(() -> {
Runnable runnable = mock(Runnable.class);
Thread regular = new Thread();
ThreadFactory factory = Restarter.getInstance().getThreadFactory();
Thread viaFactory = factory.newThread(runnable);
// Regular threads will inherit the current thread
assertThat(regular.getContextClassLoader()).isEqualTo(contextClassLoader);
// Factory threads should inherit from the initial thread
assertThat(viaFactory.getContextClassLoader()).isEqualTo(parentLoader);
});
thread.setContextClassLoader(contextClassLoader);
thread.start();
thread.join();

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.
@@ -81,12 +81,8 @@ public class SilentExitExceptionHandlerTests {
private Throwable thrown;
TestThread() {
setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
TestThread.this.thrown = e;
}
});
setUncaughtExceptionHandler(
(thread, exception) -> TestThread.this.thrown = exception);
}
public Throwable getThrown() {
@@ -119,21 +115,16 @@ public class SilentExitExceptionHandlerTests {
@Override
protected Thread[] getAllThreads() {
final CountDownLatch threadRunning = new CountDownLatch(1);
Thread daemonThread = new Thread(new Runnable() {
@Override
public void run() {
synchronized (TestSilentExitExceptionHandler.this.monitor) {
threadRunning.countDown();
try {
TestSilentExitExceptionHandler.this.monitor.wait();
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
Thread daemonThread = new Thread(() -> {
synchronized (TestSilentExitExceptionHandler.this.monitor) {
threadRunning.countDown();
try {
TestSilentExitExceptionHandler.this.monitor.wait();
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
});
daemonThread.setDaemon(true);
daemonThread.start();

View File

@@ -33,8 +33,6 @@ import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.boot.devtools.tunnel.payload.HttpTunnelPayload;
import org.springframework.boot.devtools.tunnel.server.HttpTunnelServer.HttpConnection;
@@ -90,13 +88,10 @@ public class HttpTunnelServerTests {
public void setup() throws Exception {
MockitoAnnotations.initMocks(this);
this.server = new HttpTunnelServer(this.serverConnection);
given(this.serverConnection.open(anyInt())).willAnswer(new Answer<ByteChannel>() {
@Override
public ByteChannel answer(InvocationOnMock invocation) throws Throwable {
MockServerChannel channel = HttpTunnelServerTests.this.serverChannel;
channel.setTimeout((Integer) invocation.getArguments()[0]);
return channel;
}
given(this.serverConnection.open(anyInt())).willAnswer((invocation) -> {
MockServerChannel channel = HttpTunnelServerTests.this.serverChannel;
channel.setTimeout((Integer) invocation.getArguments()[0]);
return channel;
});
this.servletRequest = new MockHttpServletRequest();
this.servletRequest.setAsyncSupported(true);
@@ -311,15 +306,10 @@ public class HttpTunnelServerTests {
.willThrow(new IllegalArgumentException());
final HttpConnection connection = new HttpConnection(request, this.response);
final AtomicBoolean responded = new AtomicBoolean();
Thread connectionThread = new Thread() {
@Override
public void run() {
connection.waitForResponse();
responded.set(true);
}
};
Thread connectionThread = new Thread(() -> {
connection.waitForResponse();
responded.set(true);
});
connectionThread.start();
assertThat(responded.get()).isFalse();
Thread.sleep(sleepBeforeResponse);