1
0
mirror of https://github.com/square/okhttp.git synced 2025-08-08 23:42:08 +03:00

Run IntelliJ inspections on the codebase

Some nullability warnings, some diamond operators, adopting Objects.equals(),
and some dead code elimination.
This commit is contained in:
Jesse Wilson
2019-01-01 10:58:45 -05:00
parent ded5e1fd26
commit 0dc50f1112
67 changed files with 218 additions and 237 deletions

View File

@@ -135,9 +135,9 @@ public final class MockWebServer extends ExternalResource implements Closeable {
private final BlockingQueue<RecordedRequest> requestQueue = new LinkedBlockingQueue<>(); private final BlockingQueue<RecordedRequest> requestQueue = new LinkedBlockingQueue<>();
private final Set<Socket> openClientSockets = private final Set<Socket> openClientSockets =
Collections.newSetFromMap(new ConcurrentHashMap<Socket, Boolean>()); Collections.newSetFromMap(new ConcurrentHashMap<>());
private final Set<Http2Connection> openConnections = private final Set<Http2Connection> openConnections =
Collections.newSetFromMap(new ConcurrentHashMap<Http2Connection, Boolean>()); Collections.newSetFromMap(new ConcurrentHashMap<>());
private final AtomicInteger requestCount = new AtomicInteger(); private final AtomicInteger requestCount = new AtomicInteger();
private long bodyLimit = Long.MAX_VALUE; private long bodyLimit = Long.MAX_VALUE;
private ServerSocketFactory serverSocketFactory = ServerSocketFactory.getDefault(); private ServerSocketFactory serverSocketFactory = ServerSocketFactory.getDefault();

View File

@@ -24,6 +24,7 @@ import java.net.URI;
import java.net.URLConnection; import java.net.URLConnection;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.annotation.Nullable;
import okhttp3.internal.huc.JavaApiConverter; import okhttp3.internal.huc.JavaApiConverter;
/** /**
@@ -64,7 +65,8 @@ public class AndroidShimResponseCache extends ResponseCache {
return JavaApiConverter.createJavaCacheResponse(okResponse); return JavaApiConverter.createJavaCacheResponse(okResponse);
} }
@Override public CacheRequest put(URI uri, URLConnection urlConnection) throws IOException { @Override public @Nullable CacheRequest put(
URI uri, URLConnection urlConnection) throws IOException {
Response okResponse = JavaApiConverter.createOkResponseForCachePut(uri, urlConnection); Response okResponse = JavaApiConverter.createOkResponseForCachePut(uri, urlConnection);
if (okResponse == null) { if (okResponse == null) {
// The URLConnection is not cacheable or could not be converted. Stop. // The URLConnection is not cacheable or could not be converted. Stop.

View File

@@ -25,14 +25,16 @@ import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.annotation.Nullable;
public class AbstractResponseCache extends ResponseCache { public class AbstractResponseCache extends ResponseCache {
@Override public CacheResponse get(URI uri, String requestMethod, @Override public @Nullable CacheResponse get(URI uri, String requestMethod,
Map<String, List<String>> requestHeaders) throws IOException { Map<String, List<String>> requestHeaders) throws IOException {
return null; return null;
} }
@Override public CacheRequest put(URI uri, URLConnection connection) throws IOException { @Override public @Nullable CacheRequest put(
URI uri, URLConnection connection) throws IOException {
return null; return null;
} }

View File

@@ -399,7 +399,7 @@ public class JavaApiConverterTest {
} }
// Check retrieval of headers by index. // Check retrieval of headers by index.
assertEquals(null, httpUrlConnection.getHeaderFieldKey(0)); assertNull(httpUrlConnection.getHeaderFieldKey(0));
assertEquals("HTTP/1.1 200 Fantastic", httpUrlConnection.getHeaderField(0)); assertEquals("HTTP/1.1 200 Fantastic", httpUrlConnection.getHeaderField(0));
// After header zero there may be additional entries provided at the beginning or end by the // After header zero there may be additional entries provided at the beginning or end by the
// implementation. It's probably important that the relative ordering of the headers is // implementation. It's probably important that the relative ordering of the headers is

View File

@@ -1543,7 +1543,7 @@ public final class ResponseCacheTest {
URLConnection connection2 = openConnection(server.url("/").url()); URLConnection connection2 = openConnection(server.url("/").url());
assertEquals("A", readAscii(connection2)); assertEquals("A", readAscii(connection2));
assertEquals(null, connection2.getHeaderField("Warning")); assertNull(connection2.getHeaderField("Warning"));
} }
@Test public void getHeadersRetainsCached200LevelWarnings() throws Exception { @Test public void getHeadersRetainsCached200LevelWarnings() throws Exception {
@@ -1600,7 +1600,7 @@ public final class ResponseCacheTest {
// still valid // still valid
HttpURLConnection connection1 = openConnection(server.url("/a").url()); HttpURLConnection connection1 = openConnection(server.url("/a").url());
assertEquals("A", readAscii(connection1)); assertEquals("A", readAscii(connection1));
assertEquals(null, connection1.getHeaderField("Allow")); assertNull(connection1.getHeaderField("Allow"));
// conditional cache hit; The cached data should be returned, but the cache is not updated. // conditional cache hit; The cached data should be returned, but the cache is not updated.
HttpURLConnection connection2 = openConnection(server.url("/a").url()); HttpURLConnection connection2 = openConnection(server.url("/a").url());

View File

@@ -19,7 +19,6 @@ import java.io.IOException;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HostnameVerifier;
@@ -827,7 +826,7 @@ public final class HttpLoggingInterceptorTest {
} }
void assertNoMoreLogs() { void assertNoMoreLogs() {
assertTrue("More messages remain: " + logs.subList(index, logs.size()), index == logs.size()); assertEquals("More messages remain: " + logs.subList(index, logs.size()), index, logs.size());
} }
@Override public void log(String message) { @Override public void log(String message) {

View File

@@ -18,11 +18,6 @@
<artifactId>okhttp</artifactId> <artifactId>okhttp</artifactId>
<version>${project.version}</version> <version>${project.version}</version>
</dependency> </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>okhttp-testing-support</artifactId>
<version>${project.version}</version>
</dependency>
<dependency> <dependency>
<groupId>com.google.code.findbugs</groupId> <groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId> <artifactId>jsr305</artifactId>

View File

@@ -15,6 +15,7 @@
*/ */
package okhttp3.internal.sse; package okhttp3.internal.sse;
import java.util.Objects;
import javax.annotation.Nullable; import javax.annotation.Nullable;
final class Event { final class Event {
@@ -37,8 +38,8 @@ final class Event {
if (this == o) return true; if (this == o) return true;
if (!(o instanceof Event)) return false; if (!(o instanceof Event)) return false;
Event other = (Event) o; Event other = (Event) o;
return (id != null ? id.equals(other.id) : other.id == null) return Objects.equals(id, other.id)
&& (type != null ? type.equals(other.type) : other.type == null) && Objects.equals(type, other.type)
&& data.equals(other.data); && data.equals(other.data);
} }

View File

@@ -23,7 +23,7 @@ import okhttp3.internal.http.RecordingProxySelector;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals;
public final class AddressTest { public final class AddressTest {
private Dns dns = Dns.SYSTEM; private Dns dns = Dns.SYSTEM;
@@ -47,7 +47,7 @@ public final class AddressTest {
authenticator, null, protocols, connectionSpecs, new RecordingProxySelector()); authenticator, null, protocols, connectionSpecs, new RecordingProxySelector());
Address b = new Address("square.com", 80, dns, socketFactory, null, null, null, Address b = new Address("square.com", 80, dns, socketFactory, null, null, null,
authenticator, null, protocols, connectionSpecs, new RecordingProxySelector()); authenticator, null, protocols, connectionSpecs, new RecordingProxySelector());
assertFalse(a.equals(b)); assertNotEquals(a, b);
} }
@Test public void addressToString() throws Exception { @Test public void addressToString() throws Exception {

View File

@@ -1865,7 +1865,7 @@ public final class CacheTest {
Response response2 = get(server.url("/")); Response response2 = get(server.url("/"));
assertEquals("A", response2.body().string()); assertEquals("A", response2.body().string());
assertEquals(null, response2.header("Warning")); assertNull(response2.header("Warning"));
} }
@Test public void getHeadersRetainsCached200LevelWarnings() throws Exception { @Test public void getHeadersRetainsCached200LevelWarnings() throws Exception {
@@ -1910,7 +1910,7 @@ public final class CacheTest {
long t0 = System.currentTimeMillis(); long t0 = System.currentTimeMillis();
Response response1 = get(server.url("/a")); Response response1 = get(server.url("/a"));
assertEquals("A", response1.body().string()); assertEquals("A", response1.body().string());
assertEquals(null, response1.header("Allow")); assertNull(response1.header("Allow"));
assertEquals(0, response1.receivedResponseAtMillis() - t0, 250.0); assertEquals(0, response1.receivedResponseAtMillis() - t0, 250.0);
// A conditional cache hit updates the cache. // A conditional cache hit updates the cache.
@@ -2397,7 +2397,7 @@ public final class CacheTest {
assertEquals("B", get(url).body().string()); assertEquals("B", get(url).body().string());
assertEquals("B", get(url).body().string()); assertEquals("B", get(url).body().string());
assertEquals(null, server.takeRequest().getHeader("If-None-Match")); assertNull(server.takeRequest().getHeader("If-None-Match"));
assertEquals("v1", server.takeRequest().getHeader("If-None-Match")); assertEquals("v1", server.takeRequest().getHeader("If-None-Match"));
assertEquals("v1", server.takeRequest().getHeader("If-None-Match")); assertEquals("v1", server.takeRequest().getHeader("If-None-Match"));
assertEquals("v2", server.takeRequest().getHeader("If-None-Match")); assertEquals("v2", server.takeRequest().getHeader("If-None-Match"));
@@ -2443,7 +2443,7 @@ public final class CacheTest {
Response response2 = get(server.url("/")); Response response2 = get(server.url("/"));
assertEquals("abcd", response2.body().string()); assertEquals("abcd", response2.body().string());
assertEquals(null, server.takeRequest().getHeader("If-None-Match")); assertNull(server.takeRequest().getHeader("If-None-Match"));
assertEquals("α", server.takeRequest().getHeader("If-None-Match")); assertEquals("α", server.takeRequest().getHeader("If-None-Match"));
} }

View File

@@ -345,7 +345,7 @@ public final class CallTest {
assertEquals("POST", recordedRequest.getMethod()); assertEquals("POST", recordedRequest.getMethod());
assertEquals(0, recordedRequest.getBody().size()); assertEquals(0, recordedRequest.getBody().size());
assertEquals("0", recordedRequest.getHeader("Content-Length")); assertEquals("0", recordedRequest.getHeader("Content-Length"));
assertEquals(null, recordedRequest.getHeader("Content-Type")); assertNull(recordedRequest.getHeader("Content-Type"));
} }
@Test public void postZerolength_HTTPS() throws Exception { @Test public void postZerolength_HTTPS() throws Exception {
@@ -488,7 +488,7 @@ public final class CallTest {
assertEquals("DELETE", recordedRequest.getMethod()); assertEquals("DELETE", recordedRequest.getMethod());
assertEquals(0, recordedRequest.getBody().size()); assertEquals(0, recordedRequest.getBody().size());
assertEquals("0", recordedRequest.getHeader("Content-Length")); assertEquals("0", recordedRequest.getHeader("Content-Length"));
assertEquals(null, recordedRequest.getHeader("Content-Type")); assertNull(recordedRequest.getHeader("Content-Type"));
} }
@Test public void delete_HTTPS() throws Exception { @Test public void delete_HTTPS() throws Exception {
@@ -606,7 +606,7 @@ public final class CallTest {
executeSynchronously(request).assertCode(200); executeSynchronously(request).assertCode(200);
RecordedRequest recordedRequest = server.takeRequest(); RecordedRequest recordedRequest = server.takeRequest();
assertEquals(null, recordedRequest.getHeader("Content-Type")); assertNull(recordedRequest.getHeader("Content-Type"));
assertEquals("3", recordedRequest.getHeader("Content-Length")); assertEquals("3", recordedRequest.getHeader("Content-Length"));
assertEquals("abc", recordedRequest.getBody().readUtf8()); assertEquals("abc", recordedRequest.getBody().readUtf8());
} }

View File

@@ -24,8 +24,7 @@ import okhttp3.tls.HeldCertificate;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class CertificatePinnerTest { public final class CertificatePinnerTest {
@@ -87,9 +86,9 @@ public final class CertificatePinnerTest {
.build(); .build();
String keypairBCertificate2Pin = CertificatePinner.pin(heldCertificateB2.certificate()); String keypairBCertificate2Pin = CertificatePinner.pin(heldCertificateB2.certificate());
assertTrue(certA1Sha256Pin.equals(keypairACertificate2Pin)); assertEquals(certA1Sha256Pin, keypairACertificate2Pin);
assertTrue(certB1Sha256Pin.equals(keypairBCertificate2Pin)); assertEquals(certB1Sha256Pin, keypairBCertificate2Pin);
assertFalse(certA1Sha256Pin.equals(certB1Sha256Pin)); assertNotEquals(certA1Sha256Pin, certB1Sha256Pin);
} }
@Test public void successfulCheck() throws Exception { @Test public void successfulCheck() throws Exception {

View File

@@ -297,6 +297,7 @@ public final class ConnectionSpecTest {
+ "supportsTlsExtensions=true)", connectionSpec.toString()); + "supportsTlsExtensions=true)", connectionSpec.toString());
} }
@SafeVarargs
private static <T> Set<T> set(T... values) { private static <T> Set<T> set(T... values) {
return new LinkedHashSet<>(Arrays.asList(values)); return new LinkedHashSet<>(Arrays.asList(values));
} }

View File

@@ -79,20 +79,20 @@ public final class CookieTest {
} }
@Test public void invalidCharacters() throws Exception { @Test public void invalidCharacters() throws Exception {
assertEquals(null, Cookie.parse(url, "a\u0000b=cd")); assertNull(Cookie.parse(url, "a\u0000b=cd"));
assertEquals(null, Cookie.parse(url, "ab=c\u0000d")); assertNull(Cookie.parse(url, "ab=c\u0000d"));
assertEquals(null, Cookie.parse(url, "a\u0001b=cd")); assertNull(Cookie.parse(url, "a\u0001b=cd"));
assertEquals(null, Cookie.parse(url, "ab=c\u0001d")); assertNull(Cookie.parse(url, "ab=c\u0001d"));
assertEquals(null, Cookie.parse(url, "a\u0009b=cd")); assertNull(Cookie.parse(url, "a\u0009b=cd"));
assertEquals(null, Cookie.parse(url, "ab=c\u0009d")); assertNull(Cookie.parse(url, "ab=c\u0009d"));
assertEquals(null, Cookie.parse(url, "a\u001fb=cd")); assertNull(Cookie.parse(url, "a\u001fb=cd"));
assertEquals(null, Cookie.parse(url, "ab=c\u001fd")); assertNull(Cookie.parse(url, "ab=c\u001fd"));
assertEquals(null, Cookie.parse(url, "a\u007fb=cd")); assertNull(Cookie.parse(url, "a\u007fb=cd"));
assertEquals(null, Cookie.parse(url, "ab=c\u007fd")); assertNull(Cookie.parse(url, "ab=c\u007fd"));
assertEquals(null, Cookie.parse(url, "a\u0080b=cd")); assertNull(Cookie.parse(url, "a\u0080b=cd"));
assertEquals(null, Cookie.parse(url, "ab=c\u0080d")); assertNull(Cookie.parse(url, "ab=c\u0080d"));
assertEquals(null, Cookie.parse(url, "a\u00ffb=cd")); assertNull(Cookie.parse(url, "a\u00ffb=cd"));
assertEquals(null, Cookie.parse(url, "ab=c\u00ffd")); assertNull(Cookie.parse(url, "ab=c\u00ffd"));
} }
@Test public void maxAge() throws Exception { @Test public void maxAge() throws Exception {

View File

@@ -36,6 +36,7 @@ import org.junit.Test;
import static java.net.CookiePolicy.ACCEPT_ORIGINAL_SERVER; import static java.net.CookiePolicy.ACCEPT_ORIGINAL_SERVER;
import static okhttp3.TestUtil.defaultClient; import static okhttp3.TestUtil.defaultClient;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@@ -66,12 +67,12 @@ public class CookiesTest {
HttpCookie cookie = cookies.get(0); HttpCookie cookie = cookies.get(0);
assertEquals("a", cookie.getName()); assertEquals("a", cookie.getName());
assertEquals("android", cookie.getValue()); assertEquals("android", cookie.getValue());
assertEquals(null, cookie.getComment()); assertNull(cookie.getComment());
assertEquals(null, cookie.getCommentURL()); assertNull(cookie.getCommentURL());
assertEquals(false, cookie.getDiscard()); assertFalse(cookie.getDiscard());
assertTrue(cookie.getMaxAge() > 100000000000L); assertTrue(cookie.getMaxAge() > 100000000000L);
assertEquals("/path", cookie.getPath()); assertEquals("/path", cookie.getPath());
assertEquals(true, cookie.getSecure()); assertTrue(cookie.getSecure());
assertEquals(0, cookie.getVersion()); assertEquals(0, cookie.getVersion());
} }
@@ -98,11 +99,11 @@ public class CookiesTest {
HttpCookie cookie = cookies.get(0); HttpCookie cookie = cookies.get(0);
assertEquals("a", cookie.getName()); assertEquals("a", cookie.getName());
assertEquals("android", cookie.getValue()); assertEquals("android", cookie.getValue());
assertEquals(null, cookie.getCommentURL()); assertNull(cookie.getCommentURL());
assertEquals(false, cookie.getDiscard()); assertFalse(cookie.getDiscard());
assertEquals(60.0, cookie.getMaxAge(), 1.0); // Converting to a fixed date can cause rounding! assertEquals(60.0, cookie.getMaxAge(), 1.0); // Converting to a fixed date can cause rounding!
assertEquals("/path", cookie.getPath()); assertEquals("/path", cookie.getPath());
assertEquals(true, cookie.getSecure()); assertTrue(cookie.getSecure());
} }
@Test public void testQuotedAttributeValues() throws Exception { @Test public void testQuotedAttributeValues() throws Exception {
@@ -133,7 +134,7 @@ public class CookiesTest {
assertEquals("android", cookie.getValue()); assertEquals("android", cookie.getValue());
assertEquals(60.0, cookie.getMaxAge(), 1.0); // Converting to a fixed date can cause rounding! assertEquals(60.0, cookie.getMaxAge(), 1.0); // Converting to a fixed date can cause rounding!
assertEquals("/path", cookie.getPath()); assertEquals("/path", cookie.getPath());
assertEquals(true, cookie.getSecure()); assertTrue(cookie.getSecure());
} }
@Test public void testSendingCookiesFromStore() throws Exception { @Test public void testSendingCookiesFromStore() throws Exception {

View File

@@ -320,6 +320,7 @@ public abstract class DelegatingSSLSocket extends SSLSocket {
} }
} }
@SuppressWarnings("unchecked") // Using reflection to delegate.
public <T> T getOption(SocketOption<T> name) throws IOException { public <T> T getOption(SocketOption<T> name) throws IOException {
try { try {
return (T) SSLSocket.class.getMethod("getOption", SocketOption.class).invoke(delegate, name); return (T) SSLSocket.class.getMethod("getOption", SocketOption.class).invoke(delegate, name);
@@ -328,6 +329,7 @@ public abstract class DelegatingSSLSocket extends SSLSocket {
} }
} }
@SuppressWarnings("unchecked") // Using reflection to delegate.
public Set<SocketOption<?>> supportedOptions() { public Set<SocketOption<?>> supportedOptions() {
try { try {
return (Set<SocketOption<?>>) SSLSocket.class.getMethod("supportedOptions").invoke(delegate); return (Set<SocketOption<?>>) SSLSocket.class.getMethod("supportedOptions").invoke(delegate);

View File

@@ -317,7 +317,8 @@ public final class DispatcherTest {
listener.recordedEventTypes()); listener.recordedEventTypes());
} }
private <T> Set<T> set(T... values) { @SafeVarargs
private final <T> Set<T> set(T... values) {
return set(Arrays.asList(values)); return set(Arrays.asList(values));
} }

View File

@@ -36,9 +36,8 @@ import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap; import static java.util.Collections.singletonMap;
import static okhttp3.TestUtil.headerEntries; import static okhttp3.TestUtil.headerEntries;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class HeadersTest { public final class HeadersTest {
@@ -398,7 +397,7 @@ public final class HeadersTest {
.add("Connection", "close") .add("Connection", "close")
.add("Transfer-Encoding", "chunked") .add("Transfer-Encoding", "chunked")
.build(); .build();
assertTrue(headers1.equals(headers2)); assertEquals(headers1, headers2);
assertEquals(headers1.hashCode(), headers2.hashCode()); assertEquals(headers1.hashCode(), headers2.hashCode());
} }
@@ -411,8 +410,8 @@ public final class HeadersTest {
.add("Connection", "keep-alive") .add("Connection", "keep-alive")
.add("Transfer-Encoding", "chunked") .add("Transfer-Encoding", "chunked")
.build(); .build();
assertFalse(headers1.equals(headers2)); assertNotEquals(headers1, headers2);
assertFalse(headers1.hashCode() == headers2.hashCode()); assertNotEquals(headers1.hashCode(), headers2.hashCode());
} }
@Test public void headersToString() { @Test public void headersToString() {

View File

@@ -138,10 +138,10 @@ public final class HttpUrlTest {
assertEquals(parse("http://host/a/b?query"), base.newBuilder("?query").build()); assertEquals(parse("http://host/a/b?query"), base.newBuilder("?query").build());
assertEquals(parse("http://host/a/b#fragment"), base.newBuilder("#fragment").build()); assertEquals(parse("http://host/a/b#fragment"), base.newBuilder("#fragment").build());
assertEquals(parse("http://host/a/b"), base.newBuilder("").build()); assertEquals(parse("http://host/a/b"), base.newBuilder("").build());
assertEquals(null, base.newBuilder("ftp://b")); assertNull(base.newBuilder("ftp://b"));
assertEquals(null, base.newBuilder("ht+tp://b")); assertNull(base.newBuilder("ht+tp://b"));
assertEquals(null, base.newBuilder("ht-tp://b")); assertNull(base.newBuilder("ht-tp://b"));
assertEquals(null, base.newBuilder("ht.tp://b")); assertNull(base.newBuilder("ht.tp://b"));
} }
@Test public void redactedUrl() { @Test public void redactedUrl() {
@@ -166,10 +166,10 @@ public final class HttpUrlTest {
@Test public void resolveUnsupportedScheme() throws Exception { @Test public void resolveUnsupportedScheme() throws Exception {
HttpUrl base = parse("http://a/"); HttpUrl base = parse("http://a/");
assertEquals(null, base.resolve("ftp://b")); assertNull(base.resolve("ftp://b"));
assertEquals(null, base.resolve("ht+tp://b")); assertNull(base.resolve("ht+tp://b"));
assertEquals(null, base.resolve("ht-tp://b")); assertNull(base.resolve("ht-tp://b"));
assertEquals(null, base.resolve("ht.tp://b")); assertNull(base.resolve("ht.tp://b"));
} }
@Test public void resolveSchemeLikePath() throws Exception { @Test public void resolveSchemeLikePath() throws Exception {
@@ -183,7 +183,7 @@ public final class HttpUrlTest {
/** https://tools.ietf.org/html/rfc3986#section-5.4.1 */ /** https://tools.ietf.org/html/rfc3986#section-5.4.1 */
@Test public void rfc3886NormalExamples() { @Test public void rfc3886NormalExamples() {
HttpUrl url = parse("http://a/b/c/d;p?q"); HttpUrl url = parse("http://a/b/c/d;p?q");
assertEquals(null, url.resolve("g:h")); // No 'g:' scheme in HttpUrl. assertNull(url.resolve("g:h")); // No 'g:' scheme in HttpUrl.
assertEquals(parse("http://a/b/c/g"), url.resolve("g")); assertEquals(parse("http://a/b/c/g"), url.resolve("g"));
assertEquals(parse("http://a/b/c/g"), url.resolve("./g")); assertEquals(parse("http://a/b/c/g"), url.resolve("./g"));
assertEquals(parse("http://a/b/c/g/"), url.resolve("g/")); assertEquals(parse("http://a/b/c/g/"), url.resolve("g/"));
@@ -798,8 +798,8 @@ public final class HttpUrlTest {
assertEquals("host", url.host()); assertEquals("host", url.host());
assertEquals(80, url.port()); assertEquals(80, url.port());
assertEquals("/", url.encodedPath()); assertEquals("/", url.encodedPath());
assertEquals(null, url.query()); assertNull(url.query());
assertEquals(null, url.fragment()); assertNull(url.fragment());
} }
@Test public void fullUrlComposition() throws Exception { @Test public void fullUrlComposition() throws Exception {
@@ -1372,7 +1372,7 @@ public final class HttpUrlTest {
@Test public void fromJavaNetUrlUnsupportedScheme() throws Exception { @Test public void fromJavaNetUrlUnsupportedScheme() throws Exception {
URL javaNetUrl = new URL("mailto:user@example.com"); URL javaNetUrl = new URL("mailto:user@example.com");
assertEquals(null, HttpUrl.get(javaNetUrl)); assertNull(HttpUrl.get(javaNetUrl));
} }
@Test public void fromUri() throws Exception { @Test public void fromUri() throws Exception {
@@ -1383,12 +1383,12 @@ public final class HttpUrlTest {
@Test public void fromUriUnsupportedScheme() throws Exception { @Test public void fromUriUnsupportedScheme() throws Exception {
URI uri = new URI("mailto:user@example.com"); URI uri = new URI("mailto:user@example.com");
assertEquals(null, HttpUrl.get(uri)); assertNull(HttpUrl.get(uri));
} }
@Test public void fromUriPartial() throws Exception { @Test public void fromUriPartial() throws Exception {
URI uri = new URI("/path"); URI uri = new URI("/path");
assertEquals(null, HttpUrl.get(uri)); assertNull(HttpUrl.get(uri));
} }
@Test public void composeQueryWithComponents() throws Exception { @Test public void composeQueryWithComponents() throws Exception {
@@ -1418,7 +1418,7 @@ public final class HttpUrlTest {
.removeAllQueryParameters("a+=& b") .removeAllQueryParameters("a+=& b")
.build(); .build();
assertEquals("http://host/", url.toString()); assertEquals("http://host/", url.toString());
assertEquals(null, url.queryParameter("a+=& b")); assertNull(url.queryParameter("a+=& b"));
} }
@Test public void composeQueryRemoveEncodedQueryParameter() throws Exception { @Test public void composeQueryRemoveEncodedQueryParameter() throws Exception {
@@ -1427,7 +1427,7 @@ public final class HttpUrlTest {
.removeAllEncodedQueryParameters("a+=& b") .removeAllEncodedQueryParameters("a+=& b")
.build(); .build();
assertEquals("http://host/", url.toString()); assertEquals("http://host/", url.toString());
assertEquals(null, url.queryParameter("a =& b")); assertNull(url.queryParameter("a =& b"));
} }
@Test public void composeQuerySetQueryParameter() throws Exception { @Test public void composeQuerySetQueryParameter() throws Exception {
@@ -1473,7 +1473,7 @@ public final class HttpUrlTest {
.build(); .build();
assertEquals(1, url.querySize()); assertEquals(1, url.querySize());
assertEquals("", url.queryParameterName(0)); assertEquals("", url.queryParameterName(0));
assertEquals(null, url.queryParameterValue(0)); assertNull(url.queryParameterValue(0));
} }
@Test public void ampersandQueryIsTwoNameValuePairsWithEmptyKeys() throws Exception { @Test public void ampersandQueryIsTwoNameValuePairsWithEmptyKeys() throws Exception {
@@ -1482,9 +1482,9 @@ public final class HttpUrlTest {
.build(); .build();
assertEquals(2, url.querySize()); assertEquals(2, url.querySize());
assertEquals("", url.queryParameterName(0)); assertEquals("", url.queryParameterName(0));
assertEquals(null, url.queryParameterValue(0)); assertNull(url.queryParameterValue(0));
assertEquals("", url.queryParameterName(1)); assertEquals("", url.queryParameterName(1));
assertEquals(null, url.queryParameterValue(1)); assertNull(url.queryParameterValue(1));
} }
@Test public void removeAllDoesNotRemoveQueryIfNoParametersWereRemoved() throws Exception { @Test public void removeAllDoesNotRemoveQueryIfNoParametersWereRemoved() throws Exception {
@@ -1500,9 +1500,9 @@ public final class HttpUrlTest {
assertEquals(3, url.querySize()); assertEquals(3, url.querySize());
assertEquals(new LinkedHashSet<>(Arrays.asList("foo", "bar", "baz")), assertEquals(new LinkedHashSet<>(Arrays.asList("foo", "bar", "baz")),
url.queryParameterNames()); url.queryParameterNames());
assertEquals(null, url.queryParameterValue(0)); assertNull(url.queryParameterValue(0));
assertEquals(null, url.queryParameterValue(1)); assertNull(url.queryParameterValue(1));
assertEquals(null, url.queryParameterValue(2)); assertNull(url.queryParameterValue(2));
assertEquals(singletonList((String) null), url.queryParameterValues("foo")); assertEquals(singletonList((String) null), url.queryParameterValues("foo"));
assertEquals(singletonList((String) null), url.queryParameterValues("bar")); assertEquals(singletonList((String) null), url.queryParameterValues("bar"));
assertEquals(singletonList((String) null), url.queryParameterValues("baz")); assertEquals(singletonList((String) null), url.queryParameterValues("baz"));
@@ -1585,8 +1585,8 @@ public final class HttpUrlTest {
.fragment(null) .fragment(null)
.build(); .build();
assertEquals("http://host/", url.toString()); assertEquals("http://host/", url.toString());
assertEquals(null, url.fragment()); assertNull(url.fragment());
assertEquals(null, url.encodedFragment()); assertNull(url.encodedFragment());
} }
@Test public void clearEncodedFragment() throws Exception { @Test public void clearEncodedFragment() throws Exception {
@@ -1595,8 +1595,8 @@ public final class HttpUrlTest {
.encodedFragment(null) .encodedFragment(null)
.build(); .build();
assertEquals("http://host/", url.toString()); assertEquals("http://host/", url.toString());
assertEquals(null, url.fragment()); assertNull(url.fragment());
assertEquals(null, url.encodedFragment()); assertNull(url.encodedFragment());
} }
@Test public void topPrivateDomain() { @Test public void topPrivateDomain() {

View File

@@ -942,7 +942,7 @@ public final class InterceptorTest {
private final BlockingQueue<Exception> exceptions = new LinkedBlockingQueue<>(); private final BlockingQueue<Exception> exceptions = new LinkedBlockingQueue<>();
public ExceptionCatchingExecutor() { public ExceptionCatchingExecutor() {
super(1, 1, 0, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); super(1, 1, 0, TimeUnit.SECONDS, new SynchronousQueue<>());
} }
@Override public void execute(final Runnable runnable) { @Override public void execute(final Runnable runnable) {

View File

@@ -26,7 +26,6 @@ import org.junit.runners.Parameterized;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
/** /**
@@ -60,7 +59,7 @@ public class MediaTypeTest {
assertEquals("plain", mediaType.subtype()); assertEquals("plain", mediaType.subtype());
assertEquals("UTF-8", mediaType.charset().name()); assertEquals("UTF-8", mediaType.charset().name());
assertEquals("text/plain;boundary=foo;charset=utf-8", mediaType.toString()); assertEquals("text/plain;boundary=foo;charset=utf-8", mediaType.toString());
assertTrue(mediaType.equals(parse("text/plain;boundary=foo;charset=utf-8"))); assertEquals(mediaType, parse("text/plain;boundary=foo;charset=utf-8"));
assertEquals(mediaType.hashCode(), assertEquals(mediaType.hashCode(),
parse("text/plain;boundary=foo;charset=utf-8").hashCode()); parse("text/plain;boundary=foo;charset=utf-8").hashCode());
} }

View File

@@ -19,6 +19,7 @@ import java.io.IOException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date; import java.util.Date;
import javax.annotation.Nullable;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
@@ -31,13 +32,13 @@ import static org.junit.Assert.assertTrue;
*/ */
public final class RecordedResponse { public final class RecordedResponse {
public final Request request; public final Request request;
public final Response response; public final @Nullable Response response;
public final WebSocket webSocket; public final @Nullable WebSocket webSocket;
public final String body; public final @Nullable String body;
public final IOException failure; public final @Nullable IOException failure;
public RecordedResponse(Request request, Response response, WebSocket webSocket, String body, public RecordedResponse(Request request, @Nullable Response response,
IOException failure) { @Nullable WebSocket webSocket, @Nullable String body, @Nullable IOException failure) {
this.request = request; this.request = request;
this.response = response; this.response = response;
this.webSocket = webSocket; this.webSocket = webSocket;

View File

@@ -217,7 +217,7 @@ public final class RecordingEventListener extends EventListener {
this.inetAddressList = inetAddressList; this.inetAddressList = inetAddressList;
} }
@Nullable @Override public CallEvent closes() { @Override public @Nullable CallEvent closes() {
return new DnsStart(call, domainName); return new DnsStart(call, domainName);
} }
} }
@@ -265,7 +265,7 @@ public final class RecordingEventListener extends EventListener {
this.ioe = ioe; this.ioe = ioe;
} }
@Nullable @Override public CallEvent closes() { @Override public @Nullable CallEvent closes() {
return new ConnectStart(call, inetSocketAddress, proxy); return new ConnectStart(call, inetSocketAddress, proxy);
} }
} }
@@ -284,7 +284,7 @@ public final class RecordingEventListener extends EventListener {
this.handshake = handshake; this.handshake = handshake;
} }
@Nullable @Override public CallEvent closes() { @Override public @Nullable CallEvent closes() {
return new SecureConnectStart(call); return new SecureConnectStart(call);
} }
} }
@@ -306,7 +306,7 @@ public final class RecordingEventListener extends EventListener {
this.connection = connection; this.connection = connection;
} }
@Nullable @Override public CallEvent closes() { @Override public @Nullable CallEvent closes() {
return new ConnectionAcquired(call, connection); return new ConnectionAcquired(call, connection);
} }
} }
@@ -322,7 +322,7 @@ public final class RecordingEventListener extends EventListener {
super(call); super(call);
} }
@Nullable @Override public CallEvent closes() { @Override public @Nullable CallEvent closes() {
return new CallStart(call); return new CallStart(call);
} }
} }
@@ -350,7 +350,7 @@ public final class RecordingEventListener extends EventListener {
this.headerLength = headerLength; this.headerLength = headerLength;
} }
@Nullable @Override public CallEvent closes() { @Override public @Nullable CallEvent closes() {
return new RequestHeadersStart(call); return new RequestHeadersStart(call);
} }
} }
@@ -369,7 +369,7 @@ public final class RecordingEventListener extends EventListener {
this.bytesWritten = bytesWritten; this.bytesWritten = bytesWritten;
} }
@Nullable @Override public CallEvent closes() { @Override public @Nullable CallEvent closes() {
return new RequestBodyStart(call); return new RequestBodyStart(call);
} }
} }
@@ -388,7 +388,7 @@ public final class RecordingEventListener extends EventListener {
this.headerLength = headerLength; this.headerLength = headerLength;
} }
@Nullable @Override public CallEvent closes() { @Override public @Nullable CallEvent closes() {
return new RequestHeadersStart(call); return new RequestHeadersStart(call);
} }
} }
@@ -407,7 +407,7 @@ public final class RecordingEventListener extends EventListener {
this.bytesRead = bytesRead; this.bytesRead = bytesRead;
} }
@Nullable @Override public CallEvent closes() { @Override public @Nullable CallEvent closes() {
return new ResponseBodyStart(call); return new ResponseBodyStart(call);
} }
} }

View File

@@ -61,8 +61,7 @@ public final class SocksProxy {
private ServerSocket serverSocket; private ServerSocket serverSocket;
private AtomicInteger connectionCount = new AtomicInteger(); private AtomicInteger connectionCount = new AtomicInteger();
private final Set<Socket> openSockets = private final Set<Socket> openSockets = Collections.newSetFromMap(new ConcurrentHashMap<>());
Collections.newSetFromMap(new ConcurrentHashMap<Socket, Boolean>());
public void play() throws IOException { public void play() throws IOException {
serverSocket = new ServerSocket(0); serverSocket = new ServerSocket(0);

View File

@@ -46,7 +46,7 @@ public final class WebPlatformUrlTest {
} }
} }
@Parameter(0) @Parameter
public WebPlatformUrlTestData testData; public WebPlatformUrlTestData testData;
private static final List<String> HTTP_URL_SCHEMES private static final List<String> HTTP_URL_SCHEMES

View File

@@ -24,7 +24,6 @@ import java.util.concurrent.atomic.AtomicReference;
import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.MockWebServer;
import okio.BufferedSink; import okio.BufferedSink;
import org.junit.Ignore;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;

View File

@@ -33,7 +33,6 @@ import okio.Okio;
import okio.Source; import okio.Source;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.TemporaryFolder; import org.junit.rules.TemporaryFolder;
@@ -1249,7 +1248,7 @@ public final class DiskLruCacheTest {
a.close(); a.close();
iterator.remove(); iterator.remove();
assertEquals(null, cache.get("a")); assertNull(cache.get("a"));
} }
@Test public void iteratorRemoveBeforeNext() throws Exception { @Test public void iteratorRemoveBeforeNext() throws Exception {

View File

@@ -26,6 +26,7 @@ import org.junit.Test;
import static okhttp3.TestUtil.headerEntries; import static okhttp3.TestUtil.headerEntries;
import static okio.ByteString.decodeHex; import static okio.ByteString.decodeHex;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class HpackTest { public final class HpackTest {
@@ -384,7 +385,7 @@ public final class HpackTest {
assertEquals(0, hpackReader.headerCount); assertEquals(0, hpackReader.headerCount);
assertEquals(0, hpackReader.dynamicTableByteCount); assertEquals(0, hpackReader.dynamicTableByteCount);
assertEquals(null, hpackReader.dynamicTable[readerHeaderTableLength() - 1]); assertNull(hpackReader.dynamicTable[readerHeaderTableLength() - 1]);
assertEquals(headerEntries(":method", "GET"), hpackReader.getAndResetHeaderList()); assertEquals(headerEntries(":method", "GET"), hpackReader.getAndResetHeaderList());
} }

View File

@@ -55,6 +55,7 @@ import static okhttp3.internal.http2.Settings.HEADER_TABLE_SIZE;
import static okhttp3.internal.http2.Settings.INITIAL_WINDOW_SIZE; import static okhttp3.internal.http2.Settings.INITIAL_WINDOW_SIZE;
import static okhttp3.internal.http2.Settings.MAX_CONCURRENT_STREAMS; import static okhttp3.internal.http2.Settings.MAX_CONCURRENT_STREAMS;
import static okhttp3.internal.http2.Settings.MAX_FRAME_SIZE; import static okhttp3.internal.http2.Settings.MAX_FRAME_SIZE;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@@ -195,11 +196,11 @@ public final class Http2ConnectionTest {
InFrame data1 = peer.takeFrame(); InFrame data1 = peer.takeFrame();
assertEquals(Http2.TYPE_DATA, data1.type); assertEquals(Http2.TYPE_DATA, data1.type);
assertEquals(3, data1.streamId); assertEquals(3, data1.streamId);
assertTrue(Arrays.equals("abcde".getBytes(UTF_8), data1.data)); assertArrayEquals("abcde".getBytes(UTF_8), data1.data);
InFrame data2 = peer.takeFrame(); InFrame data2 = peer.takeFrame();
assertEquals(Http2.TYPE_DATA, data2.type); assertEquals(Http2.TYPE_DATA, data2.type);
assertEquals(3, data2.streamId); assertEquals(3, data2.streamId);
assertTrue(Arrays.equals("fghi".getBytes(UTF_8), data2.data)); assertArrayEquals("fghi".getBytes(UTF_8), data2.data);
} }
/** /**
@@ -283,7 +284,7 @@ public final class Http2ConnectionTest {
InFrame data1 = peer.takeFrame(); InFrame data1 = peer.takeFrame();
assertEquals(Http2.TYPE_DATA, data1.type); assertEquals(Http2.TYPE_DATA, data1.type);
assertEquals(3, data1.streamId); assertEquals(3, data1.streamId);
assertTrue(Arrays.equals("abcdef".getBytes(UTF_8), data1.data)); assertArrayEquals("abcdef".getBytes(UTF_8), data1.data);
} }
@Test public void readSendsWindowUpdateHttp2() throws Exception { @Test public void readSendsWindowUpdateHttp2() throws Exception {
@@ -546,7 +547,7 @@ public final class Http2ConnectionTest {
assertEquals(-1, synStream.associatedStreamId); assertEquals(-1, synStream.associatedStreamId);
assertEquals(headerEntries("b", "banana"), synStream.headerBlock); assertEquals(headerEntries("b", "banana"), synStream.headerBlock);
InFrame requestData = peer.takeFrame(); InFrame requestData = peer.takeFrame();
assertTrue(Arrays.equals("c3po".getBytes(UTF_8), requestData.data)); assertArrayEquals("c3po".getBytes(UTF_8), requestData.data);
} }
@Test public void serverFinishesStreamWithHeaders() throws Exception { @Test public void serverFinishesStreamWithHeaders() throws Exception {
@@ -634,11 +635,11 @@ public final class Http2ConnectionTest {
InFrame data1 = peer.takeFrame(); InFrame data1 = peer.takeFrame();
assertEquals(Http2.TYPE_DATA, data1.type); assertEquals(Http2.TYPE_DATA, data1.type);
assertEquals(3, data1.streamId); assertEquals(3, data1.streamId);
assertTrue(Arrays.equals("abcdefghi".getBytes(UTF_8), data1.data)); assertArrayEquals("abcdefghi".getBytes(UTF_8), data1.data);
assertEquals(false, data1.inFinished); assertFalse(data1.inFinished);
InFrame headers2 = peer.takeFrame(); InFrame headers2 = peer.takeFrame();
assertEquals(Http2.TYPE_HEADERS, headers2.type); assertEquals(Http2.TYPE_HEADERS, headers2.type);
assertEquals(true, headers2.inFinished); assertTrue(headers2.inFinished);
} }
@Test public void clientCannotReadTrailersWithoutExhaustingStream() throws Exception { @Test public void clientCannotReadTrailersWithoutExhaustingStream() throws Exception {
@@ -765,7 +766,7 @@ public final class Http2ConnectionTest {
assertEquals(-1, synStream.associatedStreamId); assertEquals(-1, synStream.associatedStreamId);
assertEquals(headerEntries("b", "banana"), synStream.headerBlock); assertEquals(headerEntries("b", "banana"), synStream.headerBlock);
InFrame requestData = peer.takeFrame(); InFrame requestData = peer.takeFrame();
assertTrue(Arrays.equals("c3po".getBytes(UTF_8), requestData.data)); assertArrayEquals("c3po".getBytes(UTF_8), requestData.data);
InFrame nextFrame = peer.takeFrame(); InFrame nextFrame = peer.takeFrame();
assertEquals(headerEntries("e", "elephant"), nextFrame.headerBlock); assertEquals(headerEntries("e", "elephant"), nextFrame.headerBlock);
@@ -1108,7 +1109,7 @@ public final class Http2ConnectionTest {
assertFalse(synStream.outFinished); assertFalse(synStream.outFinished);
InFrame data = peer.takeFrame(); InFrame data = peer.takeFrame();
assertEquals(Http2.TYPE_DATA, data.type); assertEquals(Http2.TYPE_DATA, data.type);
assertTrue(Arrays.equals("square".getBytes(UTF_8), data.data)); assertArrayEquals("square".getBytes(UTF_8), data.data);
InFrame fin = peer.takeFrame(); InFrame fin = peer.takeFrame();
assertEquals(Http2.TYPE_DATA, fin.type); assertEquals(Http2.TYPE_DATA, fin.type);
assertTrue(fin.inFinished); assertTrue(fin.inFinished);
@@ -1304,7 +1305,7 @@ public final class Http2ConnectionTest {
InFrame data1 = peer.takeFrame(); InFrame data1 = peer.takeFrame();
assertEquals(Http2.TYPE_DATA, data1.type); assertEquals(Http2.TYPE_DATA, data1.type);
assertEquals(3, data1.streamId); assertEquals(3, data1.streamId);
assertTrue(Arrays.equals("abcdef".getBytes(UTF_8), data1.data)); assertArrayEquals("abcdef".getBytes(UTF_8), data1.data);
} }
@Test public void sendGoAway() throws Exception { @Test public void sendGoAway() throws Exception {
@@ -1554,7 +1555,7 @@ public final class Http2ConnectionTest {
assertEquals(Http2.TYPE_HEADERS, peer.takeFrame().type); assertEquals(Http2.TYPE_HEADERS, peer.takeFrame().type);
InFrame data = peer.takeFrame(); InFrame data = peer.takeFrame();
assertEquals(Http2.TYPE_DATA, data.type); assertEquals(Http2.TYPE_DATA, data.type);
assertTrue(Arrays.equals("abcdefghij".getBytes(UTF_8), data.data)); assertArrayEquals("abcdefghij".getBytes(UTF_8), data.data);
assertTrue(data.inFinished); assertTrue(data.inFinished);
} }

View File

@@ -240,7 +240,7 @@ public final class Http2Test {
@Override public void settings(boolean clearPrevious, Settings settings) { @Override public void settings(boolean clearPrevious, Settings settings) {
assertFalse(clearPrevious); // No clearPrevious in HTTP/2. assertFalse(clearPrevious); // No clearPrevious in HTTP/2.
assertEquals(reducedTableSizeBytes, settings.getHeaderTableSize()); assertEquals(reducedTableSizeBytes, settings.getHeaderTableSize());
assertEquals(false, settings.getEnablePush(true)); assertFalse(settings.getEnablePush(true));
} }
}); });
} }

View File

@@ -16,14 +16,13 @@
package okhttp3.internal.http2; package okhttp3.internal.http2;
import java.io.IOException; import java.io.IOException;
import java.util.Arrays;
import java.util.Random; import java.util.Random;
import okio.Buffer; import okio.Buffer;
import okio.ByteString; import okio.ByteString;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/** Original version of this class was lifted from {@code com.twitter.hpack.HuffmanTest}. */ /** Original version of this class was lifted from {@code com.twitter.hpack.HuffmanTest}. */
public final class HuffmanTest { public final class HuffmanTest {
@@ -45,6 +44,6 @@ public final class HuffmanTest {
assertEquals(buffer.size(), Huffman.get().encodedLength(data)); assertEquals(buffer.size(), Huffman.get().encodedLength(data));
byte[] decodedBytes = Huffman.get().decode(buffer.readByteArray()); byte[] decodedBytes = Huffman.get().decode(buffer.readByteArray());
assertTrue(Arrays.equals(data.toByteArray(), decodedBytes)); assertArrayEquals(data.toByteArray(), decodedBytes);
} }
} }

View File

@@ -20,6 +20,7 @@ import org.junit.Test;
import static okhttp3.internal.http2.Settings.DEFAULT_INITIAL_WINDOW_SIZE; import static okhttp3.internal.http2.Settings.DEFAULT_INITIAL_WINDOW_SIZE;
import static okhttp3.internal.http2.Settings.MAX_CONCURRENT_STREAMS; import static okhttp3.internal.http2.Settings.MAX_CONCURRENT_STREAMS;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public final class SettingsTest { public final class SettingsTest {
@Test public void unsetField() { @Test public void unsetField() {
@@ -33,9 +34,9 @@ public final class SettingsTest {
settings.set(Settings.HEADER_TABLE_SIZE, 8096); settings.set(Settings.HEADER_TABLE_SIZE, 8096);
assertEquals(8096, settings.getHeaderTableSize()); assertEquals(8096, settings.getHeaderTableSize());
assertEquals(true, settings.getEnablePush(true)); assertTrue(settings.getEnablePush(true));
settings.set(Settings.ENABLE_PUSH, 1); settings.set(Settings.ENABLE_PUSH, 1);
assertEquals(true, settings.getEnablePush(false)); assertTrue(settings.getEnablePush(false));
settings.clear(); settings.clear();
assertEquals(-3, settings.getMaxConcurrentStreams(-3)); assertEquals(-3, settings.getMaxConcurrentStreams(-3));

View File

@@ -36,8 +36,8 @@ import okhttp3.Request;
import okhttp3.Response; import okhttp3.Response;
import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.MockWebServer;
import okhttp3.tls.HeldCertificate;
import okhttp3.tls.HandshakeCertificates; import okhttp3.tls.HandshakeCertificates;
import okhttp3.tls.HeldCertificate;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
@@ -47,7 +47,7 @@ import static okhttp3.internal.platform.PlatformTest.getPlatform;
import static okhttp3.tls.internal.TlsUtil.newKeyManager; import static okhttp3.tls.internal.TlsUtil.newKeyManager;
import static okhttp3.tls.internal.TlsUtil.newTrustManager; import static okhttp3.tls.internal.TlsUtil.newTrustManager;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public final class ClientAuthTest { public final class ClientAuthTest {
@@ -149,7 +149,7 @@ public final class ClientAuthTest {
Call call = client.newCall(new Request.Builder().url(server.url("/")).build()); Call call = client.newCall(new Request.Builder().url(server.url("/")).build());
Response response = call.execute(); Response response = call.execute();
assertEquals(new X500Principal("CN=Local Host"), response.handshake().peerPrincipal()); assertEquals(new X500Principal("CN=Local Host"), response.handshake().peerPrincipal());
assertEquals(null, response.handshake().localPrincipal()); assertNull(response.handshake().localPrincipal());
assertEquals("abc", response.body().string()); assertEquals("abc", response.body().string());
} }
@@ -165,7 +165,7 @@ public final class ClientAuthTest {
Call call = client.newCall(new Request.Builder().url(server.url("/")).build()); Call call = client.newCall(new Request.Builder().url(server.url("/")).build());
Response response = call.execute(); Response response = call.execute();
assertEquals(new X500Principal("CN=Local Host"), response.handshake().peerPrincipal()); assertEquals(new X500Principal("CN=Local Host"), response.handshake().peerPrincipal());
assertEquals(null, response.handshake().localPrincipal()); assertNull(response.handshake().localPrincipal());
assertEquals("abc", response.body().string()); assertEquals("abc", response.body().string());
} }

View File

@@ -17,6 +17,7 @@ package okhttp3.internal.ws;
import java.io.IOException; import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.BlockingQueue; import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@@ -24,7 +25,6 @@ import javax.annotation.Nullable;
import okhttp3.Response; import okhttp3.Response;
import okhttp3.WebSocket; import okhttp3.WebSocket;
import okhttp3.WebSocketListener; import okhttp3.WebSocketListener;
import okhttp3.internal.Util;
import okhttp3.internal.platform.Platform; import okhttp3.internal.platform.Platform;
import okio.ByteString; import okio.ByteString;
@@ -309,8 +309,8 @@ public final class WebSocketRecorder extends WebSocketListener {
@Override public boolean equals(Object other) { @Override public boolean equals(Object other) {
return other instanceof Message return other instanceof Message
&& Util.equal(((Message) other).bytes, bytes) && Objects.equals(((Message) other).bytes, bytes)
&& Util.equal(((Message) other).string, string); && Objects.equals(((Message) other).string, string);
} }
} }

View File

@@ -36,7 +36,6 @@ import static okhttp3.internal.ws.WebSocketProtocol.OPCODE_BINARY;
import static okhttp3.internal.ws.WebSocketProtocol.OPCODE_TEXT; import static okhttp3.internal.ws.WebSocketProtocol.OPCODE_TEXT;
import static okhttp3.internal.ws.WebSocketProtocol.PAYLOAD_BYTE_MAX; import static okhttp3.internal.ws.WebSocketProtocol.PAYLOAD_BYTE_MAX;
import static okhttp3.internal.ws.WebSocketProtocol.PAYLOAD_SHORT_MAX; import static okhttp3.internal.ws.WebSocketProtocol.PAYLOAD_SHORT_MAX;
import static okhttp3.internal.ws.WebSocketProtocol.toggleMask;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;

View File

@@ -68,7 +68,7 @@ public final class JavaNetAuthenticator implements Authenticator {
} }
private InetAddress getConnectToInetAddress(Proxy proxy, HttpUrl url) throws IOException { private InetAddress getConnectToInetAddress(Proxy proxy, HttpUrl url) throws IOException {
return (proxy != null && proxy.type() != Proxy.Type.DIRECT) return proxy.type() != Proxy.Type.DIRECT
? ((InetSocketAddress) proxy.address()).getAddress() ? ((InetSocketAddress) proxy.address()).getAddress()
: InetAddress.getByName(url.host()); : InetAddress.getByName(url.host());
} }

View File

@@ -21,6 +21,7 @@ import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.net.URLStreamHandler; import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory; import java.net.URLStreamHandlerFactory;
import javax.annotation.Nullable;
import okhttp3.internal.URLFilter; import okhttp3.internal.URLFilter;
import okhttp3.internal.annotations.EverythingIsNonNull; import okhttp3.internal.annotations.EverythingIsNonNull;
import okhttp3.internal.huc.OkHttpURLConnection; import okhttp3.internal.huc.OkHttpURLConnection;
@@ -65,7 +66,7 @@ public final class OkUrlFactory implements URLStreamHandlerFactory, Cloneable {
return open(url, client.proxy()); return open(url, client.proxy());
} }
HttpURLConnection open(URL url, Proxy proxy) { HttpURLConnection open(URL url, @Nullable Proxy proxy) {
String protocol = url.getProtocol(); String protocol = url.getProtocol();
OkHttpClient copy = client.newBuilder() OkHttpClient copy = client.newBuilder()
.proxy(proxy) .proxy(proxy)

View File

@@ -134,7 +134,6 @@ abstract class DelegatingHttpsURLConnection extends HttpsURLConnection {
return delegate.getContent(); return delegate.getContent();
} }
@SuppressWarnings("unchecked") // Spec does not generify
@Override public Object getContent(Class[] types) throws IOException { @Override public Object getContent(Class[] types) throws IOException {
return delegate.getContent(types); return delegate.getContent(types);
} }

View File

@@ -1501,7 +1501,7 @@ public final class UrlConnectionCacheTest {
URLConnection connection2 = urlFactory.open(server.url("/").url()); URLConnection connection2 = urlFactory.open(server.url("/").url());
assertEquals("A", readAscii(connection2)); assertEquals("A", readAscii(connection2));
assertEquals(null, connection2.getHeaderField("Warning")); assertNull(connection2.getHeaderField("Warning"));
} }
@Test public void getHeadersRetainsCached200LevelWarnings() throws Exception { @Test public void getHeadersRetainsCached200LevelWarnings() throws Exception {
@@ -1539,7 +1539,7 @@ public final class UrlConnectionCacheTest {
// cache miss; seed the cache // cache miss; seed the cache
HttpURLConnection connection1 = urlFactory.open(server.url("/a").url()); HttpURLConnection connection1 = urlFactory.open(server.url("/a").url());
assertEquals("A", readAscii(connection1)); assertEquals("A", readAscii(connection1));
assertEquals(null, connection1.getHeaderField("Allow")); assertNull(connection1.getHeaderField("Allow"));
// conditional cache hit; update the cache // conditional cache hit; update the cache
HttpURLConnection connection2 = urlFactory.open(server.url("/a").url()); HttpURLConnection connection2 = urlFactory.open(server.url("/a").url());

View File

@@ -18,14 +18,13 @@ package okhttp3;
import java.net.Proxy; import java.net.Proxy;
import java.net.ProxySelector; import java.net.ProxySelector;
import java.util.List; import java.util.List;
import java.util.Objects;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import javax.net.SocketFactory; import javax.net.SocketFactory;
import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.SSLSocketFactory;
import okhttp3.internal.Util; import okhttp3.internal.Util;
import static okhttp3.internal.Util.equal;
/** /**
* A specification for a connection to an origin server. For simple connections, this is the * A specification for a connection to an origin server. For simple connections, this is the
* server's hostname and port. If an explicit proxy is requested (or {@linkplain Proxy#NO_PROXY no * server's hostname and port. If an explicit proxy is requested (or {@linkplain Proxy#NO_PROXY no
@@ -178,10 +177,10 @@ public final class Address {
&& this.protocols.equals(that.protocols) && this.protocols.equals(that.protocols)
&& this.connectionSpecs.equals(that.connectionSpecs) && this.connectionSpecs.equals(that.connectionSpecs)
&& this.proxySelector.equals(that.proxySelector) && this.proxySelector.equals(that.proxySelector)
&& equal(this.proxy, that.proxy) && Objects.equals(this.proxy, that.proxy)
&& equal(this.sslSocketFactory, that.sslSocketFactory) && Objects.equals(this.sslSocketFactory, that.sslSocketFactory)
&& equal(this.hostnameVerifier, that.hostnameVerifier) && Objects.equals(this.hostnameVerifier, that.hostnameVerifier)
&& equal(this.certificatePinner, that.certificatePinner) && Objects.equals(this.certificatePinner, that.certificatePinner)
&& this.url().port() == that.url().port(); && this.url().port() == that.url().port();
} }

View File

@@ -141,11 +141,11 @@ public final class Cache implements Closeable, Flushable {
private static final int ENTRY_COUNT = 2; private static final int ENTRY_COUNT = 2;
final InternalCache internalCache = new InternalCache() { final InternalCache internalCache = new InternalCache() {
@Override public Response get(Request request) throws IOException { @Override public @Nullable Response get(Request request) throws IOException {
return Cache.this.get(request); return Cache.this.get(request);
} }
@Override public CacheRequest put(Response response) throws IOException { @Override public @Nullable CacheRequest put(Response response) throws IOException {
return Cache.this.put(response); return Cache.this.put(response);
} }

View File

@@ -22,14 +22,13 @@ import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.Set; import java.util.Set;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLPeerUnverifiedException;
import okhttp3.internal.tls.CertificateChainCleaner; import okhttp3.internal.tls.CertificateChainCleaner;
import okio.ByteString; import okio.ByteString;
import static okhttp3.internal.Util.equal;
/** /**
* Constrains which certificates are trusted. Pinning certificates defends against attacks on * Constrains which certificates are trusted. Pinning certificates defends against attacks on
* certificate authorities. It also prevents connections through man-in-the-middle certificate * certificate authorities. It also prevents connections through man-in-the-middle certificate
@@ -139,7 +138,8 @@ public final class CertificatePinner {
@Override public boolean equals(@Nullable Object other) { @Override public boolean equals(@Nullable Object other) {
if (other == this) return true; if (other == this) return true;
return other instanceof CertificatePinner return other instanceof CertificatePinner
&& (equal(certificateChainCleaner, ((CertificatePinner) other).certificateChainCleaner) && (Objects.equals(certificateChainCleaner,
((CertificatePinner) other).certificateChainCleaner)
&& pins.equals(((CertificatePinner) other).pins)); && pins.equals(((CertificatePinner) other).pins));
} }
@@ -228,7 +228,7 @@ public final class CertificatePinner {
/** Returns a certificate pinner that uses {@code certificateChainCleaner}. */ /** Returns a certificate pinner that uses {@code certificateChainCleaner}. */
CertificatePinner withCertificateChainCleaner( CertificatePinner withCertificateChainCleaner(
@Nullable CertificateChainCleaner certificateChainCleaner) { @Nullable CertificateChainCleaner certificateChainCleaner) {
return equal(this.certificateChainCleaner, certificateChainCleaner) return Objects.equals(this.certificateChainCleaner, certificateChainCleaner)
? this ? this
: new CertificatePinner(pins, certificateChainCleaner); : new CertificatePinner(pins, certificateChainCleaner);
} }

View File

@@ -49,7 +49,7 @@ public final class ConnectionPool {
*/ */
private static final Executor executor = new ThreadPoolExecutor(0 /* corePoolSize */, private static final Executor executor = new ThreadPoolExecutor(0 /* corePoolSize */,
Integer.MAX_VALUE /* maximumPoolSize */, 60L /* keepAliveTime */, TimeUnit.SECONDS, Integer.MAX_VALUE /* maximumPoolSize */, 60L /* keepAliveTime */, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp ConnectionPool", true)); new SynchronousQueue<>(), Util.threadFactory("OkHttp ConnectionPool", true));
/** The maximum number of idle connections for each address. */ /** The maximum number of idle connections for each address. */
private final int maxIdleConnections; private final int maxIdleConnections;
@@ -111,18 +111,17 @@ public final class ConnectionPool {
} }
/** /**
* Returns a recycled connection to {@code address}, or null if no such connection exists. The * Acquires a recycled connection to {@code address} for {@code streamAllocation}. If non-null
* route is null if the address has not yet been routed. * {@code route} is the resolved route for a connection.
*/ */
@Nullable RealConnection get(Address address, StreamAllocation streamAllocation, Route route) { void acquire(Address address, StreamAllocation streamAllocation, @Nullable Route route) {
assert (Thread.holdsLock(this)); assert (Thread.holdsLock(this));
for (RealConnection connection : connections) { for (RealConnection connection : connections) {
if (connection.isEligible(address, route)) { if (connection.isEligible(address, route)) {
streamAllocation.acquire(connection, true); streamAllocation.acquire(connection, true);
return connection; return;
} }
} }
return null;
} }
/** /**

View File

@@ -63,7 +63,7 @@ public final class Dispatcher {
public synchronized ExecutorService executorService() { public synchronized ExecutorService executorService() {
if (executorService == null) { if (executorService == null) {
executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS, executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp Dispatcher", false)); new SynchronousQueue<>(), Util.threadFactory("OkHttp Dispatcher", false));
} }
return executorService; return executorService;
} }

View File

@@ -105,13 +105,13 @@ public final class FormBody extends RequestBody {
public static final class Builder { public static final class Builder {
private final List<String> names = new ArrayList<>(); private final List<String> names = new ArrayList<>();
private final List<String> values = new ArrayList<>(); private final List<String> values = new ArrayList<>();
private final Charset charset; private final @Nullable Charset charset;
public Builder() { public Builder() {
this(null); this(null);
} }
public Builder(Charset charset) { public Builder(@Nullable Charset charset) {
this.charset = charset; this.charset = charset;
} }

View File

@@ -202,7 +202,7 @@ public final class Headers {
return result; return result;
} }
private static String get(String[] namesAndValues, String name) { private static @Nullable String get(String[] namesAndValues, String name) {
for (int i = namesAndValues.length - 2; i >= 0; i -= 2) { for (int i = namesAndValues.length - 2; i >= 0; i -= 2) {
if (name.equalsIgnoreCase(namesAndValues[i])) { if (name.equalsIgnoreCase(namesAndValues[i])) {
return namesAndValues[i + 1]; return namesAndValues[i + 1];
@@ -419,7 +419,7 @@ public final class Headers {
} }
/** Equivalent to {@code build().get(name)}, but potentially faster. */ /** Equivalent to {@code build().get(name)}, but potentially faster. */
public String get(String name) { public @Nullable String get(String name) {
for (int i = namesAndValues.size() - 2; i >= 0; i -= 2) { for (int i = namesAndValues.size() - 2; i >= 0; i -= 2) {
if (name.equalsIgnoreCase(namesAndValues.get(i))) { if (name.equalsIgnoreCase(namesAndValues.get(i))) {
return namesAndValues.get(i + 1); return namesAndValues.get(i + 1);

View File

@@ -1088,9 +1088,8 @@ public final class HttpUrl {
public Builder setPathSegment(int index, String pathSegment) { public Builder setPathSegment(int index, String pathSegment) {
if (pathSegment == null) throw new NullPointerException("pathSegment == null"); if (pathSegment == null) throw new NullPointerException("pathSegment == null");
String canonicalPathSegment = canonicalize( String canonicalPathSegment = canonicalize(pathSegment, 0, pathSegment.length(),
pathSegment, 0, pathSegment.length(), PATH_SEGMENT_ENCODE_SET, false, false, false, true, PATH_SEGMENT_ENCODE_SET, false, false, false, true, null);
null);
if (isDot(canonicalPathSegment) || isDotDot(canonicalPathSegment)) { if (isDot(canonicalPathSegment) || isDotDot(canonicalPathSegment)) {
throw new IllegalArgumentException("unexpected path segment: " + pathSegment); throw new IllegalArgumentException("unexpected path segment: " + pathSegment);
} }
@@ -1102,9 +1101,8 @@ public final class HttpUrl {
if (encodedPathSegment == null) { if (encodedPathSegment == null) {
throw new NullPointerException("encodedPathSegment == null"); throw new NullPointerException("encodedPathSegment == null");
} }
String canonicalPathSegment = canonicalize(encodedPathSegment, String canonicalPathSegment = canonicalize(encodedPathSegment, 0, encodedPathSegment.length(),
0, encodedPathSegment.length(), PATH_SEGMENT_ENCODE_SET, true, false, false, true, PATH_SEGMENT_ENCODE_SET, true, false, false, true, null);
null);
encodedPathSegments.set(index, canonicalPathSegment); encodedPathSegments.set(index, canonicalPathSegment);
if (isDot(canonicalPathSegment) || isDotDot(canonicalPathSegment)) { if (isDot(canonicalPathSegment) || isDotDot(canonicalPathSegment)) {
throw new IllegalArgumentException("unexpected path segment: " + encodedPathSegment); throw new IllegalArgumentException("unexpected path segment: " + encodedPathSegment);
@@ -1362,9 +1360,8 @@ public final class HttpUrl {
if (!hasPassword) { if (!hasPassword) {
int passwordColonOffset = delimiterOffset( int passwordColonOffset = delimiterOffset(
input, pos, componentDelimiterOffset, ':'); input, pos, componentDelimiterOffset, ':');
String canonicalUsername = canonicalize( String canonicalUsername = canonicalize(input, pos, passwordColonOffset,
input, pos, passwordColonOffset, USERNAME_ENCODE_SET, true, false, false, true, USERNAME_ENCODE_SET, true, false, false, true, null);
null);
this.encodedUsername = hasUsername this.encodedUsername = hasUsername
? this.encodedUsername + "%40" + canonicalUsername ? this.encodedUsername + "%40" + canonicalUsername
: canonicalUsername; : canonicalUsername;
@@ -1377,8 +1374,7 @@ public final class HttpUrl {
hasUsername = true; hasUsername = true;
} else { } else {
this.encodedPassword = this.encodedPassword + "%40" + canonicalize(input, pos, this.encodedPassword = this.encodedPassword + "%40" + canonicalize(input, pos,
componentDelimiterOffset, PASSWORD_ENCODE_SET, true, false, false, true, componentDelimiterOffset, PASSWORD_ENCODE_SET, true, false, false, true, null);
null);
} }
pos = componentDelimiterOffset + 1; pos = componentDelimiterOffset + 1;
break; break;
@@ -1586,7 +1582,7 @@ public final class HttpUrl {
return limit; // No colon. return limit; // No colon.
} }
private static String canonicalizeHost(String input, int pos, int limit) { private static @Nullable String canonicalizeHost(String input, int pos, int limit) {
// Start by percent decoding the host. The WHATWG spec suggests doing this only after we've // Start by percent decoding the host. The WHATWG spec suggests doing this only after we've
// checked for IPv6 square braces. But Chrome does it first, and that's more lenient. // checked for IPv6 square braces. But Chrome does it first, and that's more lenient.
String percentDecoded = percentDecode(input, pos, limit, false); String percentDecoded = percentDecode(input, pos, limit, false);
@@ -1682,7 +1678,7 @@ public final class HttpUrl {
*/ */
static String canonicalize(String input, int pos, int limit, String encodeSet, static String canonicalize(String input, int pos, int limit, String encodeSet,
boolean alreadyEncoded, boolean strict, boolean plusIsSpace, boolean asciiOnly, boolean alreadyEncoded, boolean strict, boolean plusIsSpace, boolean asciiOnly,
Charset charset) { @Nullable Charset charset) {
int codePoint; int codePoint;
for (int i = pos; i < limit; i += Character.charCount(codePoint)) { for (int i = pos; i < limit; i += Character.charCount(codePoint)) {
codePoint = input.codePointAt(i); codePoint = input.codePointAt(i);
@@ -1707,7 +1703,7 @@ public final class HttpUrl {
static void canonicalize(Buffer out, String input, int pos, int limit, String encodeSet, static void canonicalize(Buffer out, String input, int pos, int limit, String encodeSet,
boolean alreadyEncoded, boolean strict, boolean plusIsSpace, boolean asciiOnly, boolean alreadyEncoded, boolean strict, boolean plusIsSpace, boolean asciiOnly,
Charset charset) { @Nullable Charset charset) {
Buffer encodedCharBuffer = null; // Lazily allocated. Buffer encodedCharBuffer = null; // Lazily allocated.
int codePoint; int codePoint;
for (int i = pos; i < limit; i += Character.charCount(codePoint)) { for (int i = pos; i < limit; i += Character.charCount(codePoint)) {
@@ -1748,10 +1744,9 @@ public final class HttpUrl {
} }
static String canonicalize(String input, String encodeSet, boolean alreadyEncoded, boolean strict, static String canonicalize(String input, String encodeSet, boolean alreadyEncoded, boolean strict,
boolean plusIsSpace, boolean asciiOnly, Charset charset) { boolean plusIsSpace, boolean asciiOnly, @Nullable Charset charset) {
return canonicalize( return canonicalize(input, 0, input.length(), encodeSet, alreadyEncoded, strict, plusIsSpace,
input, 0, input.length(), encodeSet, alreadyEncoded, strict, plusIsSpace, asciiOnly, asciiOnly, charset);
charset);
} }
static String canonicalize(String input, String encodeSet, boolean alreadyEncoded, boolean strict, static String canonicalize(String input, String encodeSet, boolean alreadyEncoded, boolean strict,

View File

@@ -199,7 +199,7 @@ public final class MultipartBody extends RequestBody {
* want to have a good chance of things working, please avoid double-quotes, newlines, percent * want to have a good chance of things working, please avoid double-quotes, newlines, percent
* signs, and the like in your field names. * signs, and the like in your field names.
*/ */
static StringBuilder appendQuotedString(StringBuilder target, String key) { static void appendQuotedString(StringBuilder target, String key) {
target.append('"'); target.append('"');
for (int i = 0, len = key.length(); i < len; i++) { for (int i = 0, len = key.length(); i < len; i++) {
char ch = key.charAt(i); char ch = key.charAt(i);
@@ -219,7 +219,6 @@ public final class MultipartBody extends RequestBody {
} }
} }
target.append('"'); target.append('"');
return target;
} }
public static final class Part { public static final class Part {

View File

@@ -151,16 +151,16 @@ public class OkHttpClient implements Cloneable, Call.Factory, WebSocket.Factory
return pool.connectionBecameIdle(connection); return pool.connectionBecameIdle(connection);
} }
@Override public RealConnection get(ConnectionPool pool, Address address, @Override public void acquire(ConnectionPool pool, Address address,
StreamAllocation streamAllocation, Route route) { StreamAllocation streamAllocation, @Nullable Route route) {
return pool.get(address, streamAllocation, route); pool.acquire(address, streamAllocation, route);
} }
@Override public boolean equalsNonHost(Address a, Address b) { @Override public boolean equalsNonHost(Address a, Address b) {
return a.equalsNonHost(b); return a.equalsNonHost(b);
} }
@Override public Socket deduplicate( @Override public @Nullable Socket deduplicate(
ConnectionPool pool, Address address, StreamAllocation streamAllocation) { ConnectionPool pool, Address address, StreamAllocation streamAllocation) {
return pool.deduplicate(address, streamAllocation); return pool.deduplicate(address, streamAllocation);
} }
@@ -360,7 +360,7 @@ public class OkHttpClient implements Cloneable, Call.Factory, WebSocket.Factory
return cache; return cache;
} }
InternalCache internalCache() { @Nullable InternalCache internalCache() {
return cache != null ? cache.internalCache : internalCache; return cache != null ? cache.internalCache : internalCache;
} }

View File

@@ -59,7 +59,7 @@ final class RealCall implements Call {
this.client = client; this.client = client;
this.originalRequest = originalRequest; this.originalRequest = originalRequest;
this.forWebSocket = forWebSocket; this.forWebSocket = forWebSocket;
this.retryAndFollowUpInterceptor = new RetryAndFollowUpInterceptor(client, forWebSocket); this.retryAndFollowUpInterceptor = new RetryAndFollowUpInterceptor(client);
this.timeout = new AsyncTimeout() { this.timeout = new AsyncTimeout() {
@Override protected void timedOut() { @Override protected void timedOut() {
cancel(); cancel();

View File

@@ -54,12 +54,12 @@ public abstract class Internal {
public abstract void setCache(OkHttpClient.Builder builder, InternalCache internalCache); public abstract void setCache(OkHttpClient.Builder builder, InternalCache internalCache);
public abstract RealConnection get(ConnectionPool pool, Address address, public abstract void acquire(ConnectionPool pool, Address address,
StreamAllocation streamAllocation, Route route); StreamAllocation streamAllocation, @Nullable Route route);
public abstract boolean equalsNonHost(Address a, Address b); public abstract boolean equalsNonHost(Address a, Address b);
public abstract Socket deduplicate( public abstract @Nullable Socket deduplicate(
ConnectionPool pool, Address address, StreamAllocation streamAllocation); ConnectionPool pool, Address address, StreamAllocation streamAllocation);
public abstract void put(ConnectionPool pool, RealConnection connection); public abstract void put(ConnectionPool pool, RealConnection connection);

View File

@@ -129,11 +129,6 @@ public final class Util {
} }
} }
/** Returns true if two possibly-null objects are equal. */
public static boolean equal(Object a, Object b) {
return a == b || (a != null && a.equals(b));
}
/** /**
* Closes {@code closeable}, ignoring any checked exceptions. Does nothing if {@code closeable} is * Closes {@code closeable}, ignoring any checked exceptions. Does nothing if {@code closeable} is
* null. * null.
@@ -234,6 +229,7 @@ public final class Util {
} }
/** Returns an immutable list containing {@code elements}. */ /** Returns an immutable list containing {@code elements}. */
@SafeVarargs
public static <T> List<T> immutableList(T... elements) { public static <T> List<T> immutableList(T... elements) {
return Collections.unmodifiableList(Arrays.asList(elements.clone())); return Collections.unmodifiableList(Arrays.asList(elements.clone()));
} }
@@ -252,7 +248,6 @@ public final class Util {
* Returns an array containing only elements found in {@code first} and also in {@code * Returns an array containing only elements found in {@code first} and also in {@code
* second}. The returned elements are in the same order as in {@code first}. * second}. The returned elements are in the same order as in {@code first}.
*/ */
@SuppressWarnings("unchecked")
public static String[] intersect( public static String[] intersect(
Comparator<? super String> comparator, String[] first, String[] second) { Comparator<? super String> comparator, String[] first, String[] second) {
List<String> result = new ArrayList<>(); List<String> result = new ArrayList<>();

View File

@@ -17,6 +17,7 @@
package okhttp3.internal.cache; package okhttp3.internal.cache;
import java.io.IOException; import java.io.IOException;
import javax.annotation.Nullable;
import okhttp3.Headers; import okhttp3.Headers;
import okhttp3.Interceptor; import okhttp3.Interceptor;
import okhttp3.Protocol; import okhttp3.Protocol;
@@ -43,9 +44,9 @@ import static okhttp3.internal.Util.discard;
/** Serves requests from the cache and writes responses to the cache. */ /** Serves requests from the cache and writes responses to the cache. */
public final class CacheInterceptor implements Interceptor { public final class CacheInterceptor implements Interceptor {
final InternalCache cache; final @Nullable InternalCache cache;
public CacheInterceptor(InternalCache cache) { public CacheInterceptor(@Nullable InternalCache cache) {
this.cache = cache; this.cache = cache;
} }

View File

@@ -267,7 +267,7 @@ public final class DiskLruCache implements Closeable, Flushable {
// Use a single background thread to evict entries. // Use a single background thread to evict entries.
Executor executor = new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS, Executor executor = new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(), Util.threadFactory("OkHttp DiskLruCache", true)); new LinkedBlockingQueue<>(), Util.threadFactory("OkHttp DiskLruCache", true));
return new DiskLruCache(fileSystem, directory, appVersion, valueCount, maxSize, executor); return new DiskLruCache(fileSystem, directory, appVersion, valueCount, maxSize, executor);
} }

View File

@@ -16,6 +16,7 @@
package okhttp3.internal.cache; package okhttp3.internal.cache;
import java.io.IOException; import java.io.IOException;
import javax.annotation.Nullable;
import okhttp3.Request; import okhttp3.Request;
import okhttp3.Response; import okhttp3.Response;
@@ -24,9 +25,9 @@ import okhttp3.Response;
* okhttp3.Cache}. * okhttp3.Cache}.
*/ */
public interface InternalCache { public interface InternalCache {
Response get(Request request) throws IOException; @Nullable Response get(Request request) throws IOException;
CacheRequest put(Response response) throws IOException; @Nullable CacheRequest put(Response response) throws IOException;
/** /**
* Remove any cache entries for the supplied {@code request}. This is invoked when the client * Remove any cache entries for the supplied {@code request}. This is invoked when the client

View File

@@ -25,7 +25,6 @@ import java.util.List;
import javax.net.ssl.SSLException; import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLProtocolException;
import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocket;
import okhttp3.ConnectionSpec; import okhttp3.ConnectionSpec;
import okhttp3.internal.Internal; import okhttp3.internal.Internal;
@@ -111,8 +110,7 @@ public final class ConnectionSpecSelector {
// Look for known client-side or negotiation errors that are unlikely to be fixed by trying // Look for known client-side or negotiation errors that are unlikely to be fixed by trying
// again with a different connection spec. // again with a different connection spec.
if (e instanceof SSLHandshakeException) { if (e instanceof SSLHandshakeException) {
// If the problem was a CertificateException from the X509TrustManager, // If the problem was a CertificateException from the X509TrustManager, do not retry.
// do not retry.
if (e.getCause() instanceof CertificateException) { if (e.getCause() instanceof CertificateException) {
return false; return false;
} }
@@ -122,11 +120,8 @@ public final class ConnectionSpecSelector {
return false; return false;
} }
// On Android, SSLProtocolExceptions can be caused by TLS_FALLBACK_SCSV failures, which means we // Retry for all other SSL failures.
// retry those when we probably should not. return e instanceof SSLException;
return (e instanceof SSLHandshakeException
|| e instanceof SSLProtocolException
|| e instanceof SSLException);
} }
/** /**

View File

@@ -57,14 +57,14 @@ import static okhttp3.internal.Util.closeQuietly;
* connections. This class has APIs to release each of the above resources: * connections. This class has APIs to release each of the above resources:
* *
* <ul> * <ul>
* <li>{@link #noNewStreams()} prevents the connection from being used for new streams in the * <li>{@link #noNewStreams} prevents the connection from being used for new streams in the
* future. Use this after a {@code Connection: close} header, or when the connection may be * future. Use this after a {@code Connection: close} header, or when the connection may be
* inconsistent. * inconsistent.
* <li>{@link #streamFinished streamFinished()} releases the active stream from this allocation. * <li>{@link #streamFinished streamFinished} releases the active stream from this allocation.
* Note that only one stream may be active at a given time, so it is necessary to call * Note that only one stream may be active at a given time, so it is necessary to call
* {@link #streamFinished streamFinished()} before creating a subsequent stream with {@link * {@link #streamFinished streamFinished()} before creating a subsequent stream with {@link
* #newStream newStream()}. * #newStream newStream()}.
* <li>{@link #release()} removes the call's hold on the connection. Note that this won't * <li>{@link #release} removes the call's hold on the connection. Note that this won't
* immediately free the connection if there is a stream still lingering. That happens when a * immediately free the connection if there is a stream still lingering. That happens when a
* call is complete but its response body has yet to be fully consumed. * call is complete but its response body has yet to be fully consumed.
* </ul> * </ul>
@@ -185,7 +185,7 @@ public final class StreamAllocation {
if (result == null) { if (result == null) {
// Attempt to get a connection from the pool. // Attempt to get a connection from the pool.
Internal.instance.get(connectionPool, address, this, null); Internal.instance.acquire(connectionPool, address, this, null);
if (connection != null) { if (connection != null) {
foundPooledConnection = true; foundPooledConnection = true;
result = connection; result = connection;
@@ -223,7 +223,7 @@ public final class StreamAllocation {
List<Route> routes = routeSelection.getAll(); List<Route> routes = routeSelection.getAll();
for (int i = 0, size = routes.size(); i < size; i++) { for (int i = 0, size = routes.size(); i < size; i++) {
Route route = routes.get(i); Route route = routes.get(i);
Internal.instance.get(connectionPool, address, this, route); Internal.instance.acquire(connectionPool, address, this, route);
if (connection != null) { if (connection != null) {
foundPooledConnection = true; foundPooledConnection = true;
result = connection; result = connection;

View File

@@ -22,6 +22,7 @@ import java.util.Collections;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.TreeSet; import java.util.TreeSet;
import okhttp3.Challenge; import okhttp3.Challenge;
@@ -36,7 +37,6 @@ import okio.ByteString;
import static java.net.HttpURLConnection.HTTP_NOT_MODIFIED; import static java.net.HttpURLConnection.HTTP_NOT_MODIFIED;
import static java.net.HttpURLConnection.HTTP_NO_CONTENT; import static java.net.HttpURLConnection.HTTP_NO_CONTENT;
import static okhttp3.internal.Util.equal;
import static okhttp3.internal.http.StatusLine.HTTP_CONTINUE; import static okhttp3.internal.http.StatusLine.HTTP_CONTINUE;
/** Headers and utilities for internal use by OkHttp. */ /** Headers and utilities for internal use by OkHttp. */
@@ -71,7 +71,7 @@ public final class HttpHeaders {
public static boolean varyMatches( public static boolean varyMatches(
Response cachedResponse, Headers cachedRequest, Request newRequest) { Response cachedResponse, Headers cachedRequest, Request newRequest) {
for (String field : varyFields(cachedResponse)) { for (String field : varyFields(cachedResponse)) {
if (!equal(cachedRequest.values(field), newRequest.headers(field))) return false; if (!Objects.equals(cachedRequest.values(field), newRequest.headers(field))) return false;
} }
return true; return true;
} }

View File

@@ -66,14 +66,12 @@ public final class RetryAndFollowUpInterceptor implements Interceptor {
private static final int MAX_FOLLOW_UPS = 20; private static final int MAX_FOLLOW_UPS = 20;
private final OkHttpClient client; private final OkHttpClient client;
private final boolean forWebSocket;
private volatile StreamAllocation streamAllocation; private volatile StreamAllocation streamAllocation;
private Object callStackTrace; private Object callStackTrace;
private volatile boolean canceled; private volatile boolean canceled;
public RetryAndFollowUpInterceptor(OkHttpClient client, boolean forWebSocket) { public RetryAndFollowUpInterceptor(OkHttpClient client) {
this.client = client; this.client = client;
this.forWebSocket = forWebSocket;
} }
/** /**

View File

@@ -22,7 +22,7 @@ import java.util.Collections;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import okhttp3.internal.Util; import java.util.Objects;
import okio.Buffer; import okio.Buffer;
import okio.BufferedSource; import okio.BufferedSource;
import okio.ByteString; import okio.ByteString;
@@ -483,9 +483,9 @@ final class Hpack {
// it's unnecessary to waste cycles looking at them. This check is built on the // it's unnecessary to waste cycles looking at them. This check is built on the
// observation that the header entries we care about are in adjacent pairs, and we // observation that the header entries we care about are in adjacent pairs, and we
// always know the first index of the pair. // always know the first index of the pair.
if (Util.equal(STATIC_HEADER_TABLE[headerNameIndex - 1].value, value)) { if (Objects.equals(STATIC_HEADER_TABLE[headerNameIndex - 1].value, value)) {
headerIndex = headerNameIndex; headerIndex = headerNameIndex;
} else if (Util.equal(STATIC_HEADER_TABLE[headerNameIndex].value, value)) { } else if (Objects.equals(STATIC_HEADER_TABLE[headerNameIndex].value, value)) {
headerIndex = headerNameIndex + 1; headerIndex = headerNameIndex + 1;
} }
} }
@@ -493,8 +493,8 @@ final class Hpack {
if (headerIndex == -1) { if (headerIndex == -1) {
for (int j = nextHeaderIndex + 1, length = dynamicTable.length; j < length; j++) { for (int j = nextHeaderIndex + 1, length = dynamicTable.length; j < length; j++) {
if (Util.equal(dynamicTable[j].name, name)) { if (Objects.equals(dynamicTable[j].name, name)) {
if (Util.equal(dynamicTable[j].value, value)) { if (Objects.equals(dynamicTable[j].value, value)) {
headerIndex = j - nextHeaderIndex + STATIC_HEADER_TABLE.length; headerIndex = j - nextHeaderIndex + STATIC_HEADER_TABLE.length;
break; break;
} else if (headerNameIndex == -1) { } else if (headerNameIndex == -1) {

View File

@@ -80,7 +80,7 @@ public final class Http2Connection implements Closeable {
* threads because listeners are not required to return promptly. * threads because listeners are not required to return promptly.
*/ */
private static final ExecutorService listenerExecutor = new ThreadPoolExecutor(0, private static final ExecutorService listenerExecutor = new ThreadPoolExecutor(0,
Integer.MAX_VALUE, 60, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), Integer.MAX_VALUE, 60, TimeUnit.SECONDS, new SynchronousQueue<>(),
Util.threadFactory("OkHttp Http2Connection", true)); Util.threadFactory("OkHttp Http2Connection", true));
/** True if this peer initiated the connection. */ /** True if this peer initiated the connection. */
@@ -164,8 +164,7 @@ public final class Http2Connection implements Closeable {
} }
// Like newSingleThreadExecutor, except lazy creates the thread. // Like newSingleThreadExecutor, except lazy creates the thread.
pushExecutor = new ThreadPoolExecutor(0, 1, 60, TimeUnit.SECONDS, pushExecutor = new ThreadPoolExecutor(0, 1, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(),
new LinkedBlockingQueue<Runnable>(),
Util.threadFactory(Util.format("OkHttp %s Push Observer", connectionName), true)); Util.threadFactory(Util.format("OkHttp %s Push Observer", connectionName), true));
peerSettings.set(Settings.INITIAL_WINDOW_SIZE, DEFAULT_INITIAL_WINDOW_SIZE); peerSettings.set(Settings.INITIAL_WINDOW_SIZE, DEFAULT_INITIAL_WINDOW_SIZE);
peerSettings.set(Settings.MAX_FRAME_SIZE, Http2.INITIAL_MAX_FRAME_SIZE); peerSettings.set(Settings.MAX_FRAME_SIZE, Http2.INITIAL_MAX_FRAME_SIZE);

View File

@@ -40,7 +40,7 @@ import okhttp3.internal.tls.CertificateChainCleaner;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import static okhttp3.internal.Util.assertionError; import static okhttp3.internal.Util.assertionError;
/** Android 2.3 or better. */ /** Android 5+. */
class AndroidPlatform extends Platform { class AndroidPlatform extends Platform {
private static final int MAX_LOG_LENGTH = 4000; private static final int MAX_LOG_LENGTH = 4000;

View File

@@ -132,11 +132,12 @@ class JdkWithJettyBootPlatform extends Platform {
return protocols; // Client advertises these protocols. return protocols; // Client advertises these protocols.
} else if ((methodName.equals("selectProtocol") || methodName.equals("select")) } else if ((methodName.equals("selectProtocol") || methodName.equals("select"))
&& String.class == returnType && args.length == 1 && args[0] instanceof List) { && String.class == returnType && args.length == 1 && args[0] instanceof List) {
List<String> peerProtocols = (List) args[0]; List<?> peerProtocols = (List) args[0];
// Pick the first known protocol the peer advertises. // Pick the first known protocol the peer advertises.
for (int i = 0, size = peerProtocols.size(); i < size; i++) { for (int i = 0, size = peerProtocols.size(); i < size; i++) {
if (protocols.contains(peerProtocols.get(i))) { String protocol = (String) peerProtocols.get(i);
return selected = peerProtocols.get(i); if (protocols.contains(protocol)) {
return selected = protocol;
} }
} }
return selected = protocols.get(0); // On no intersection, try peer's first protocol. return selected = protocols.get(0); // On no intersection, try peer's first protocol.

View File

@@ -248,7 +248,7 @@ public class Platform {
Field field = c.getDeclaredField(fieldName); Field field = c.getDeclaredField(fieldName);
field.setAccessible(true); field.setAccessible(true);
Object value = field.get(instance); Object value = field.get(instance);
if (value == null || !fieldType.isInstance(value)) return null; if (!fieldType.isInstance(value)) return null;
return fieldType.cast(value); return fieldType.cast(value);
} catch (NoSuchFieldException ignored) { } catch (NoSuchFieldException ignored) {
} catch (IllegalAccessException e) { } catch (IllegalAccessException e) {

View File

@@ -246,7 +246,6 @@ final class WebSocketWriter {
return sink.timeout(); return sink.timeout();
} }
@SuppressWarnings("PointlessBitwiseExpression")
@Override public void close() throws IOException { @Override public void close() throws IOException {
if (closed) throw new IOException("closed"); if (closed) throw new IOException("closed");

View File

@@ -41,8 +41,7 @@ import org.jsoup.nodes.Element;
*/ */
public final class Crawler { public final class Crawler {
private final OkHttpClient client; private final OkHttpClient client;
private final Set<HttpUrl> fetchedUrls = Collections.synchronizedSet( private final Set<HttpUrl> fetchedUrls = Collections.synchronizedSet(new LinkedHashSet<>());
new LinkedHashSet<HttpUrl>());
private final LinkedBlockingQueue<HttpUrl> queue = new LinkedBlockingQueue<>(); private final LinkedBlockingQueue<HttpUrl> queue = new LinkedBlockingQueue<>();
private final ConcurrentHashMap<String, AtomicInteger> hostnames = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, AtomicInteger> hostnames = new ConcurrentHashMap<>();

View File

@@ -28,6 +28,7 @@
</menu> </menu>
</div> </div>
</div> </div>
</div>
</header> </header>
<section id="subtitle"> <section id="subtitle">
<div class="container"> <div class="container">