Skip to content
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

Use lambdas where appropriate #4549

Merged
merged 1 commit into from
Jan 12, 2019
Merged
Show file tree
Hide file tree
Changes from all 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 @@ -83,16 +83,14 @@ public MockResponse dispatch(RecordedRequest request) throws InterruptedExceptio
assertEquals(200, secondResponseCode.get()); // (Still done).
}

private Thread buildRequestThread(final String path, final AtomicInteger responseCode) {
return new Thread(new Runnable() {
@Override public void run() {
final URL url = mockWebServer.url(path).url();
final HttpURLConnection conn;
try {
conn = (HttpURLConnection) url.openConnection();
responseCode.set(conn.getResponseCode()); // Force the connection to hit the "server".
} catch (IOException e) {
}
private Thread buildRequestThread(String path, AtomicInteger responseCode) {
return new Thread(() -> {
URL url = mockWebServer.url(path).url();
HttpURLConnection conn;
try {
conn = (HttpURLConnection) url.openConnection();
responseCode.set(conn.getResponseCode()); // Force the connection to hit the "server".
} catch (IOException ignored) {
}
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,15 +165,13 @@ public final class MockWebServerTest {
* response is ready.
*/
@Test public void dispatchBlocksWaitingForEnqueue() throws Exception {
new Thread() {
@Override public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
server.enqueue(new MockResponse().setBody("enqueued in the background"));
new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
}.start();
server.enqueue(new MockResponse().setBody("enqueued in the background"));
}).start();

URLConnection connection = server.url("/").url().openConnection();
InputStream in = connection.getInputStream();
Expand Down
15 changes: 2 additions & 13 deletions okcurl/src/main/java/okhttp3/curl/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
import java.util.logging.SimpleFormatter;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
Expand Down Expand Up @@ -200,13 +199,7 @@ private OkHttpClient createClient() {
builder.hostnameVerifier(createInsecureHostnameVerifier());
}
if (verbose) {
HttpLoggingInterceptor.Logger logger =
new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
System.out.println(message);
}
};
HttpLoggingInterceptor.Logger logger = System.out::println;
builder.eventListenerFactory(new LoggingEventListener.Factory(logger));
}
return builder.build();
Expand Down Expand Up @@ -292,11 +285,7 @@ private static SSLSocketFactory createInsecureSslSocketFactory(TrustManager trus
}

private static HostnameVerifier createInsecureHostnameVerifier() {
return new HostnameVerifier() {
@Override public boolean verify(String s, SSLSession sslSession) {
return true;
}
};
return (name, session) -> true;
}

private static void enableHttp2FrameLogging() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,11 +109,7 @@ public interface Logger {
void log(String message);

/** A {@link Logger} defaults output appropriate for the current platform. */
Logger DEFAULT = new Logger() {
@Override public void log(String message) {
Platform.get().log(INFO, message, null);
}
};
Logger DEFAULT = message -> Platform.get().log(INFO, message, null);
}

public HttpLoggingInterceptor() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,11 @@
package okhttp3.logging;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import javax.net.ssl.HostnameVerifier;
import okhttp3.Dns;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
Expand Down Expand Up @@ -704,11 +702,7 @@ private void bodyGetNoBody(int code) throws IOException {
@Test public void connectFail() throws IOException {
setLevel(Level.BASIC);
client = new OkHttpClient.Builder()
.dns(new Dns() {
@Override public List<InetAddress> lookup(String hostname) throws UnknownHostException {
throw new UnknownHostException("reason");
}
})
.dns(hostname -> { throw new UnknownHostException("reason"); })
.addInterceptor(applicationInterceptor)
.build();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,7 @@
package okhttp3.logging;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import okhttp3.Dns;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
Expand Down Expand Up @@ -171,17 +168,10 @@ public void secureGet() throws Exception {

@Test
public void dnsFail() throws IOException {
client =
new OkHttpClient.Builder()
.dns(
new Dns() {
@Override
public List<InetAddress> lookup(String hostname) throws UnknownHostException {
throw new UnknownHostException("reason");
}
})
.eventListenerFactory(loggingEventListenerFactory)
.build();
client = new OkHttpClient.Builder()
.dns(hostname -> { throw new UnknownHostException("reason"); })
.eventListenerFactory(loggingEventListenerFactory)
.build();

try {
client.newCall(request().build()).execute();
Expand Down
11 changes: 4 additions & 7 deletions okhttp-sse/src/main/java/okhttp3/sse/EventSources.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,15 @@
package okhttp3.sse;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.internal.sse.RealEventSource;

public final class EventSources {
public static EventSource.Factory createFactory(final OkHttpClient client) {
return new EventSource.Factory() {
@Override public EventSource newEventSource(Request request, EventSourceListener listener) {
RealEventSource eventSource = new RealEventSource(request, listener);
eventSource.connect(client);
return eventSource;
}
return (request, listener) -> {
RealEventSource eventSource = new RealEventSource(request, listener);
eventSource.connect(client);
return eventSource;
};
}

Expand Down
9 changes: 3 additions & 6 deletions okhttp-testing-support/src/main/java/okhttp3/TestUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
Expand All @@ -32,11 +31,9 @@ public final class TestUtil {
* A network that resolves only one IP address per host. Use this when testing route selection
* fallbacks to prevent the host machine's various IP addresses from interfering.
*/
private static final Dns SINGLE_INET_ADDRESS_DNS = new Dns() {
@Override public List<InetAddress> lookup(String hostname) throws UnknownHostException {
List<InetAddress> addresses = Dns.SYSTEM.lookup(hostname);
return Collections.singletonList(addresses.get(0));
}
private static final Dns SINGLE_INET_ADDRESS_DNS = hostname -> {
List<InetAddress> addresses = Dns.SYSTEM.lookup(hostname);
return Collections.singletonList(addresses.get(0));
};

private TestUtil() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,24 +38,22 @@ public class InstallUncaughtExceptionHandlerListener extends RunListener {
@Override public void testRunStarted(Description description) {
System.err.println("Installing aggressive uncaught exception handler");
oldDefaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override public void uncaughtException(Thread thread, Throwable throwable) {
StringWriter errorText = new StringWriter(256);
errorText.append("Uncaught exception in OkHttp thread \"");
errorText.append(thread.getName());
errorText.append("\"\n");
throwable.printStackTrace(new PrintWriter(errorText));
Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> {
StringWriter errorText = new StringWriter(256);
errorText.append("Uncaught exception in OkHttp thread \"");
errorText.append(thread.getName());
errorText.append("\"\n");
throwable.printStackTrace(new PrintWriter(errorText));
errorText.append("\n");
if (lastTestStarted != null) {
errorText.append("Last test to start was: ");
errorText.append(lastTestStarted.getDisplayName());
errorText.append("\n");
if (lastTestStarted != null) {
errorText.append("Last test to start was: ");
errorText.append(lastTestStarted.getDisplayName());
errorText.append("\n");
}
System.err.print(errorText.toString());
}
System.err.print(errorText.toString());

synchronized (exceptions) {
exceptions.put(throwable, lastTestStarted.getDisplayName());
}
synchronized (exceptions) {
exceptions.put(throwable, lastTestStarted.getDisplayName());
}
});
}
Expand Down
25 changes: 8 additions & 17 deletions okhttp-tests/src/test/java/okhttp3/CacheTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import okhttp3.internal.Internal;
import okhttp3.internal.io.InMemoryFileSystem;
import okhttp3.internal.platform.Platform;
Expand Down Expand Up @@ -63,11 +62,7 @@
import static org.junit.Assert.fail;

public final class CacheTest {
private static final HostnameVerifier NULL_HOSTNAME_VERIFIER = new HostnameVerifier() {
@Override public boolean verify(String s, SSLSession sslSession) {
return true;
}
};
private static final HostnameVerifier NULL_HOSTNAME_VERIFIER = (name, session) -> true;

@Rule public MockWebServer server = new MockWebServer();
@Rule public MockWebServer server2 = new MockWebServer();
Expand Down Expand Up @@ -2220,12 +2215,11 @@ private RecordedRequest assertClientSuppliedCondition(MockResponse seed, String

final AtomicReference<String> ifNoneMatch = new AtomicReference<>();
client = client.newBuilder()
.addNetworkInterceptor(new Interceptor() {
@Override public Response intercept(Chain chain) throws IOException {
ifNoneMatch.compareAndSet(null, chain.request().header("If-None-Match"));
return chain.proceed(chain.request());
}
}).build();
.addNetworkInterceptor(chain -> {
ifNoneMatch.compareAndSet(null, chain.request().header("If-None-Match"));
return chain.proceed(chain.request());
})
.build();

// Confirm the value is cached and intercepted.
assertEquals("A", get(url).body().string());
Expand All @@ -2243,11 +2237,8 @@ private RecordedRequest assertClientSuppliedCondition(MockResponse seed, String

// Confirm the interceptor isn't exercised.
client = client.newBuilder()
.addNetworkInterceptor(new Interceptor() {
@Override public Response intercept(Chain chain) throws IOException {
throw new AssertionError();
}
}).build();
.addNetworkInterceptor(chain -> { throw new AssertionError(); })
.build();
assertEquals("A", get(url).body().string());
}

Expand Down
Loading