diff --git a/benchmarks/pom.xml b/benchmarks/pom.xml index bd6d7efd0..a4b942390 100644 --- a/benchmarks/pom.xml +++ b/benchmarks/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 @@ -88,7 +90,7 @@ -Xmx512m -Xbootclasspath/p:${bootclasspath} -classpath - + okhttp3.benchmarks.Benchmark diff --git a/benchmarks/src/main/java/okhttp3/benchmarks/ApacheHttpClient.java b/benchmarks/src/main/java/okhttp3/benchmarks/ApacheHttpClient.java index a5b1637e3..2f97519a2 100644 --- a/benchmarks/src/main/java/okhttp3/benchmarks/ApacheHttpClient.java +++ b/benchmarks/src/main/java/okhttp3/benchmarks/ApacheHttpClient.java @@ -15,13 +15,13 @@ */ package okhttp3.benchmarks; -import okhttp3.HttpUrl; -import okhttp3.internal.SslContextBuilder; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.TimeUnit; import java.util.zip.GZIPInputStream; import javax.net.ssl.SSLContext; +import okhttp3.HttpUrl; +import okhttp3.internal.SslContextBuilder; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; diff --git a/benchmarks/src/main/java/okhttp3/benchmarks/Benchmark.java b/benchmarks/src/main/java/okhttp3/benchmarks/Benchmark.java index 94abd95d5..d69530fe0 100644 --- a/benchmarks/src/main/java/okhttp3/benchmarks/Benchmark.java +++ b/benchmarks/src/main/java/okhttp3/benchmarks/Benchmark.java @@ -18,13 +18,6 @@ package okhttp3.benchmarks; import com.google.caliper.Param; import com.google.caliper.model.ArbitraryMeasurement; import com.google.caliper.runner.CaliperMain; -import okhttp3.HttpUrl; -import okhttp3.Protocol; -import okhttp3.internal.SslContextBuilder; -import okhttp3.mockwebserver.Dispatcher; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import okhttp3.mockwebserver.RecordedRequest; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; @@ -34,13 +27,20 @@ import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.SSLContext; +import okhttp3.HttpUrl; +import okhttp3.Protocol; +import okhttp3.internal.SslContextBuilder; +import okhttp3.mockwebserver.Dispatcher; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import okhttp3.mockwebserver.RecordedRequest; import okio.Buffer; import okio.GzipSink; /** - * This benchmark is fake, but may be useful for certain relative comparisons. - * It uses a local connection to a MockWebServer to measure how many identical - * requests per second can be carried over a fixed number of threads. + * This benchmark is fake, but may be useful for certain relative comparisons. It uses a local + * connection to a MockWebServer to measure how many identical requests per second can be carried + * over a fixed number of threads. */ public class Benchmark extends com.google.caliper.Benchmark { private static final int NUM_REPORTS = 10; @@ -48,16 +48,16 @@ public class Benchmark extends com.google.caliper.Benchmark { private final Random random = new Random(0); - /** Which client to run.*/ + /** Which client to run. */ @Param Client client; /** How many concurrent requests to execute. */ - @Param({ "1", "10" }) + @Param({"1", "10"}) int concurrencyLevel; /** How many requests to enqueue to await threads to execute them. */ - @Param({ "10" }) + @Param({"10"}) int targetBacklog; /** True to use TLS. */ @@ -74,11 +74,11 @@ public class Benchmark extends com.google.caliper.Benchmark { boolean chunked; /** The size of the HTTP response body, in uncompressed bytes. */ - @Param({ "128", "1048576" }) + @Param({"128", "1048576"}) int bodyByteCount; /** How many additional headers were included, beyond the built-in ones. */ - @Param({ "0", "20" }) + @Param({"0", "20"}) int headerCount; /** Which ALPN protocols are in use. Only useful with TLS. */ diff --git a/benchmarks/src/main/java/okhttp3/benchmarks/HttpClient.java b/benchmarks/src/main/java/okhttp3/benchmarks/HttpClient.java index 1f45927c0..0c0986ffe 100644 --- a/benchmarks/src/main/java/okhttp3/benchmarks/HttpClient.java +++ b/benchmarks/src/main/java/okhttp3/benchmarks/HttpClient.java @@ -20,6 +20,8 @@ import okhttp3.HttpUrl; /** An HTTP client to benchmark. */ interface HttpClient { void prepare(Benchmark benchmark); + void enqueue(HttpUrl url) throws Exception; + boolean acceptingJobs(); } diff --git a/benchmarks/src/main/java/okhttp3/benchmarks/NettyHttpClient.java b/benchmarks/src/main/java/okhttp3/benchmarks/NettyHttpClient.java index 62d5c37bc..8caa046c7 100644 --- a/benchmarks/src/main/java/okhttp3/benchmarks/NettyHttpClient.java +++ b/benchmarks/src/main/java/okhttp3/benchmarks/NettyHttpClient.java @@ -15,8 +15,6 @@ */ package okhttp3.benchmarks; -import okhttp3.HttpUrl; -import okhttp3.internal.SslContextBuilder; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.PooledByteBufAllocator; @@ -46,6 +44,8 @@ import java.util.Deque; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; +import okhttp3.HttpUrl; +import okhttp3.internal.SslContextBuilder; /** Netty isn't an HTTP client, but it's almost one. */ class NettyHttpClient implements HttpClient { diff --git a/benchmarks/src/main/java/okhttp3/benchmarks/OkHttp.java b/benchmarks/src/main/java/okhttp3/benchmarks/OkHttp.java index 0d80f4c82..3e8dbc327 100644 --- a/benchmarks/src/main/java/okhttp3/benchmarks/OkHttp.java +++ b/benchmarks/src/main/java/okhttp3/benchmarks/OkHttp.java @@ -15,18 +15,18 @@ */ package okhttp3.benchmarks; -import okhttp3.Call; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.ResponseBody; -import okhttp3.internal.SslContextBuilder; import java.io.IOException; import java.util.concurrent.TimeUnit; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; +import okhttp3.Call; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.ResponseBody; +import okhttp3.internal.SslContextBuilder; class OkHttp extends SynchronousHttpClient { private static final boolean VERBOSE = false; diff --git a/benchmarks/src/main/java/okhttp3/benchmarks/OkHttpAsync.java b/benchmarks/src/main/java/okhttp3/benchmarks/OkHttpAsync.java index 6aa6c333d..a4e367b3a 100644 --- a/benchmarks/src/main/java/okhttp3/benchmarks/OkHttpAsync.java +++ b/benchmarks/src/main/java/okhttp3/benchmarks/OkHttpAsync.java @@ -15,14 +15,6 @@ */ package okhttp3.benchmarks; -import okhttp3.Callback; -import okhttp3.Dispatcher; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; -import okhttp3.internal.SslContextBuilder; import java.io.IOException; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; @@ -32,6 +24,14 @@ import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; +import okhttp3.Callback; +import okhttp3.Dispatcher; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import okhttp3.internal.SslContextBuilder; class OkHttpAsync implements HttpClient { private static final boolean VERBOSE = false; diff --git a/benchmarks/src/main/java/okhttp3/benchmarks/SynchronousHttpClient.java b/benchmarks/src/main/java/okhttp3/benchmarks/SynchronousHttpClient.java index 76c267cec..4a17b8693 100644 --- a/benchmarks/src/main/java/okhttp3/benchmarks/SynchronousHttpClient.java +++ b/benchmarks/src/main/java/okhttp3/benchmarks/SynchronousHttpClient.java @@ -15,12 +15,12 @@ */ package okhttp3.benchmarks; -import okhttp3.HttpUrl; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import okhttp3.HttpUrl; /** Any HTTP client with a blocking API. */ abstract class SynchronousHttpClient implements HttpClient { diff --git a/benchmarks/src/main/java/okhttp3/benchmarks/UrlConnection.java b/benchmarks/src/main/java/okhttp3/benchmarks/UrlConnection.java index 2a1c75baa..f5c02ce0b 100644 --- a/benchmarks/src/main/java/okhttp3/benchmarks/UrlConnection.java +++ b/benchmarks/src/main/java/okhttp3/benchmarks/UrlConnection.java @@ -15,8 +15,6 @@ */ package okhttp3.benchmarks; -import okhttp3.HttpUrl; -import okhttp3.internal.SslContextBuilder; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; @@ -27,6 +25,8 @@ import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; +import okhttp3.HttpUrl; +import okhttp3.internal.SslContextBuilder; class UrlConnection extends SynchronousHttpClient { private static final boolean VERBOSE = false; diff --git a/checkstyle.xml b/checkstyle.xml index 0d6d8a420..d8540c616 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -82,7 +82,15 @@ - + + + diff --git a/okcurl/pom.xml b/okcurl/pom.xml index 2b9b7ceab..2fe893581 100644 --- a/okcurl/pom.xml +++ b/okcurl/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 diff --git a/okcurl/src/main/java/okhttp3/curl/Main.java b/okcurl/src/main/java/okhttp3/curl/Main.java index 25f3c2b5c..9d48d5153 100644 --- a/okcurl/src/main/java/okhttp3/curl/Main.java +++ b/okcurl/src/main/java/okhttp3/curl/Main.java @@ -16,17 +16,6 @@ package okhttp3.curl; import com.google.common.base.Joiner; -import okhttp3.ConnectionPool; -import okhttp3.Headers; -import okhttp3.MediaType; -import okhttp3.OkHttpClient; -import okhttp3.Protocol; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.internal.http.StatusLine; -import okhttp3.internal.framed.Http2; - import io.airlift.command.Arguments; import io.airlift.command.Command; import io.airlift.command.HelpOption; @@ -49,6 +38,16 @@ import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; +import okhttp3.ConnectionPool; +import okhttp3.Headers; +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Protocol; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.internal.framed.Http2; +import okhttp3.internal.http.StatusLine; import okio.BufferedSource; import okio.Okio; import okio.Sink; @@ -84,16 +83,16 @@ public class Main extends HelpOption implements Runnable { return Joiner.on(", ").join(Protocol.values()); } - @Option(name = { "-X", "--request" }, description = "Specify request command to use") + @Option(name = {"-X", "--request"}, description = "Specify request command to use") public String method; - @Option(name = { "-d", "--data" }, description = "HTTP POST data") + @Option(name = {"-d", "--data"}, description = "HTTP POST data") public String data; - @Option(name = { "-H", "--header" }, description = "Custom header to pass to server") + @Option(name = {"-H", "--header"}, description = "Custom header to pass to server") public List headers; - @Option(name = { "-A", "--user-agent" }, description = "User-Agent to send to server") + @Option(name = {"-A", "--user-agent"}, description = "User-Agent to send to server") public String userAgent = NAME + "/" + versionString(); @Option(name = "--connect-timeout", description = "Maximum time allowed for connection (seconds)") @@ -102,23 +101,23 @@ public class Main extends HelpOption implements Runnable { @Option(name = "--read-timeout", description = "Maximum time allowed for reading data (seconds)") public int readTimeout = DEFAULT_TIMEOUT; - @Option(name = { "-L", "--location" }, description = "Follow redirects") + @Option(name = {"-L", "--location"}, description = "Follow redirects") public boolean followRedirects; - @Option(name = { "-k", "--insecure" }, + @Option(name = {"-k", "--insecure"}, description = "Allow connections to SSL sites without certs") public boolean allowInsecure; - @Option(name = { "-i", "--include" }, description = "Include protocol headers in the output") + @Option(name = {"-i", "--include"}, description = "Include protocol headers in the output") public boolean showHeaders; @Option(name = "--frames", description = "Log HTTP/2 frames to STDERR") public boolean showHttp2Frames; - @Option(name = { "-e", "--referer" }, description = "Referer URL") + @Option(name = {"-e", "--referer"}, description = "Referer URL") public String referer; - @Option(name = { "-V", "--version" }, description = "Show version number and quit") + @Option(name = {"-V", "--version"}, description = "Show version number and quit") public boolean version; @Arguments(title = "url", description = "Remote resource URL") @@ -258,7 +257,7 @@ public class Main extends HelpOption implements Runnable { return null; } }; - context.init(null, new TrustManager[] { permissive }, null); + context.init(null, new TrustManager[] {permissive}, null); return context.getSocketFactory(); } catch (Exception e) { throw new AssertionError(e); diff --git a/okcurl/src/test/java/okhttp3/curl/MainTest.java b/okcurl/src/test/java/okhttp3/curl/MainTest.java index 9f4d553a0..12fe6d5ec 100644 --- a/okcurl/src/test/java/okhttp3/curl/MainTest.java +++ b/okcurl/src/test/java/okhttp3/curl/MainTest.java @@ -15,9 +15,9 @@ */ package okhttp3.curl; +import java.io.IOException; import okhttp3.Request; import okhttp3.RequestBody; -import java.io.IOException; import okio.Buffer; import org.junit.Test; diff --git a/okhttp-android-support/pom.xml b/okhttp-android-support/pom.xml index 58ec87b3e..2766b9e5a 100644 --- a/okhttp-android-support/pom.xml +++ b/okhttp-android-support/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 @@ -11,7 +13,9 @@ okhttp-android-support OkHttp Android Platform Support - Classes to support the Android platform's use of OkHttp (not required for most developers). + Classes to support the Android platform's use of OkHttp (not required for most + developers). + @@ -25,7 +29,7 @@ okhttp-urlconnection ${project.version} - + junit junit diff --git a/okhttp-android-support/src/main/java/okhttp3/AndroidInternal.java b/okhttp-android-support/src/main/java/okhttp3/AndroidInternal.java index 9a1678689..98d3e9cae 100644 --- a/okhttp-android-support/src/main/java/okhttp3/AndroidInternal.java +++ b/okhttp-android-support/src/main/java/okhttp3/AndroidInternal.java @@ -15,9 +15,8 @@ */ package okhttp3; -import okhttp3.internal.huc.CacheAdapter; - import java.net.ResponseCache; +import okhttp3.internal.huc.CacheAdapter; /** * Back doors to enable the use of OkHttp within the Android platform libraries. OkHttp is used to diff --git a/okhttp-android-support/src/main/java/okhttp3/AndroidShimResponseCache.java b/okhttp-android-support/src/main/java/okhttp3/AndroidShimResponseCache.java index cc669ae89..e385784ee 100644 --- a/okhttp-android-support/src/main/java/okhttp3/AndroidShimResponseCache.java +++ b/okhttp-android-support/src/main/java/okhttp3/AndroidShimResponseCache.java @@ -15,8 +15,6 @@ */ package okhttp3; -import okhttp3.internal.huc.JavaApiConverter; - import java.io.File; import java.io.IOException; import java.net.CacheRequest; @@ -26,6 +24,7 @@ import java.net.URI; import java.net.URLConnection; import java.util.List; import java.util.Map; +import okhttp3.internal.huc.JavaApiConverter; /** * A class provided for use by Android so that it can continue supporting a {@link ResponseCache} @@ -80,60 +79,55 @@ public class AndroidShimResponseCache extends ResponseCache { } /** - * Returns the number of bytes currently being used to store the values in - * this cache. This may be greater than the {@link #maxSize} if a background - * deletion is pending. + * Returns the number of bytes currently being used to store the values in this cache. This may be + * greater than the {@link #maxSize} if a background deletion is pending. */ public long size() throws IOException { return delegate.getSize(); } /** - * Returns the maximum number of bytes that this cache should use to store - * its data. + * Returns the maximum number of bytes that this cache should use to store its data. */ public long maxSize() { return delegate.getMaxSize(); } /** - * Force buffered operations to the filesystem. This ensures that responses - * written to the cache will be available the next time the cache is opened, - * even if this process is killed. + * Force buffered operations to the filesystem. This ensures that responses written to the cache + * will be available the next time the cache is opened, even if this process is killed. */ public void flush() throws IOException { delegate.flush(); } /** - * Returns the number of HTTP requests that required the network to either - * supply a response or validate a locally cached response. + * Returns the number of HTTP requests that required the network to either supply a response or + * validate a locally cached response. */ public int getNetworkCount() { return delegate.getNetworkCount(); } /** - * Returns the number of HTTP requests whose response was provided by the - * cache. This may include conditional {@code GET} requests that were - * validated over the network. + * Returns the number of HTTP requests whose response was provided by the cache. This may include + * conditional {@code GET} requests that were validated over the network. */ public int getHitCount() { return delegate.getHitCount(); } /** - * Returns the total number of HTTP requests that were made. This includes - * both client requests and requests that were made on the client's behalf - * to handle a redirects and retries. + * Returns the total number of HTTP requests that were made. This includes both client requests + * and requests that were made on the client's behalf to handle a redirects and retries. */ public int getRequestCount() { return delegate.getRequestCount(); } /** - * Uninstalls the cache and releases any active resources. Stored contents - * will remain on the filesystem. + * Uninstalls the cache and releases any active resources. Stored contents will remain on the + * filesystem. */ public void close() throws IOException { delegate.close(); @@ -145,5 +139,4 @@ public class AndroidShimResponseCache extends ResponseCache { public void delete() throws IOException { delegate.delete(); } - } diff --git a/okhttp-android-support/src/main/java/okhttp3/OkCacheContainer.java b/okhttp-android-support/src/main/java/okhttp3/OkCacheContainer.java index 06810999b..d52cb0133 100644 --- a/okhttp-android-support/src/main/java/okhttp3/OkCacheContainer.java +++ b/okhttp-android-support/src/main/java/okhttp3/OkCacheContainer.java @@ -16,8 +16,8 @@ package okhttp3; /** - * An interface that allows OkHttp to detect that a {@link java.net.ResponseCache} contains a - * {@link Cache}. + * An interface that allows OkHttp to detect that a {@link java.net.ResponseCache} contains a {@link + * Cache}. */ public interface OkCacheContainer { Cache getCache(); diff --git a/okhttp-android-support/src/main/java/okhttp3/internal/huc/CacheAdapter.java b/okhttp-android-support/src/main/java/okhttp3/internal/huc/CacheAdapter.java index b846f5ff1..8e02239de 100644 --- a/okhttp-android-support/src/main/java/okhttp3/internal/huc/CacheAdapter.java +++ b/okhttp-android-support/src/main/java/okhttp3/internal/huc/CacheAdapter.java @@ -15,11 +15,6 @@ */ package okhttp3.internal.huc; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.internal.InternalCache; -import okhttp3.internal.http.CacheRequest; -import okhttp3.internal.http.CacheStrategy; import java.io.IOException; import java.io.OutputStream; import java.net.CacheResponse; @@ -28,6 +23,11 @@ import java.net.ResponseCache; import java.net.URI; import java.util.List; import java.util.Map; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.internal.InternalCache; +import okhttp3.internal.http.CacheRequest; +import okhttp3.internal.http.CacheStrategy; import okio.Okio; import okio.Sink; @@ -95,8 +95,8 @@ public final class CacheAdapter implements InternalCache { } /** - * Returns the {@link CacheResponse} from the delegate by converting the - * OkHttp {@link Request} into the arguments required by the {@link ResponseCache}. + * Returns the {@link CacheResponse} from the delegate by converting the OkHttp {@link Request} + * into the arguments required by the {@link ResponseCache}. */ private CacheResponse getJavaCachedResponse(Request request) throws IOException { Map> headers = JavaApiConverter.extractJavaHeaders(request); diff --git a/okhttp-android-support/src/main/java/okhttp3/internal/huc/JavaApiConverter.java b/okhttp-android-support/src/main/java/okhttp3/internal/huc/JavaApiConverter.java index 064274b5b..e1fc4ff01 100644 --- a/okhttp-android-support/src/main/java/okhttp3/internal/huc/JavaApiConverter.java +++ b/okhttp-android-support/src/main/java/okhttp3/internal/huc/JavaApiConverter.java @@ -15,20 +15,6 @@ */ package okhttp3.internal.huc; -import okhttp3.CipherSuite; -import okhttp3.Handshake; -import okhttp3.Headers; -import okhttp3.MediaType; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import okhttp3.internal.Internal; -import okhttp3.internal.Util; -import okhttp3.internal.http.CacheRequest; -import okhttp3.internal.http.HttpMethod; -import okhttp3.internal.http.OkHeaders; -import okhttp3.internal.http.StatusLine; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -48,6 +34,20 @@ import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSocketFactory; +import okhttp3.CipherSuite; +import okhttp3.Handshake; +import okhttp3.Headers; +import okhttp3.MediaType; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import okhttp3.internal.Internal; +import okhttp3.internal.Util; +import okhttp3.internal.http.CacheRequest; +import okhttp3.internal.http.HttpMethod; +import okhttp3.internal.http.OkHeaders; +import okhttp3.internal.http.StatusLine; import okio.BufferedSource; import okio.Okio; import okio.Sink; @@ -62,9 +62,9 @@ public final class JavaApiConverter { } /** - * Creates an OkHttp {@link Response} using the supplied {@link URI} and {@link URLConnection} - * to supply the data. The URLConnection is assumed to already be connected. If this method - * returns {@code null} the response is uncacheable. + * Creates an OkHttp {@link Response} using the supplied {@link URI} and {@link URLConnection} to + * supply the data. The URLConnection is assumed to already be connected. If this method returns + * {@code null} the response is uncacheable. */ public static Response createOkResponseForCachePut(URI uri, URLConnection urlConnection) throws IOException { @@ -264,9 +264,9 @@ public final class JavaApiConverter { /** * Creates an OkHttp {@link Request} from the supplied information. * - *

This method allows a {@code null} value for {@code requestHeaders} for situations - * where a connection is already connected and access to the headers has been lost. - * See {@link java.net.HttpURLConnection#getRequestProperties()} for details. + *

This method allows a {@code null} value for {@code requestHeaders} for situations where a + * connection is already connected and access to the headers has been lost. See {@link + * java.net.HttpURLConnection#getRequestProperties()} for details. */ public static Request createOkRequest( URI uri, String requestMethod, Map> requestHeaders) { @@ -287,8 +287,8 @@ public final class JavaApiConverter { } /** - * Creates a {@link java.net.CacheResponse} of the correct (sub)type using information - * gathered from the supplied {@link Response}. + * Creates a {@link java.net.CacheResponse} of the correct (sub)type using information gathered + * from the supplied {@link Response}. */ public static CacheResponse createJavaCacheResponse(final Response response) { final Headers headers = response.headers(); @@ -364,6 +364,7 @@ public final class JavaApiConverter { public void abort() { okCacheRequest.abort(); } + @Override public OutputStream getBody() throws IOException { Sink body = okCacheRequest.body(); @@ -415,8 +416,8 @@ public final class JavaApiConverter { } /** - * Extracts OkHttp headers from the supplied {@link Map}. Only real headers are - * extracted. Any entry (one with a {@code null} key) is discarded. + * Extracts OkHttp headers from the supplied {@link Map}. Only real headers are extracted. Any + * entry (one with a {@code null} key) is discarded. */ // @VisibleForTesting static Headers extractOkHeaders(Map> javaHeaders) { @@ -438,9 +439,9 @@ public final class JavaApiConverter { } /** - * Extracts the status line from the supplied Java API {@link java.net.HttpURLConnection}. - * As per the spec, the status line is held as the header with the null key. Returns {@code null} - * if there is no status line. + * Extracts the status line from the supplied Java API {@link java.net.HttpURLConnection}. As per + * the spec, the status line is held as the header with the null key. Returns {@code null} if + * there is no status line. */ private static String extractStatusLine(HttpURLConnection httpUrlConnection) { // Java specifies that this will be be response header with a null key. @@ -448,9 +449,9 @@ public final class JavaApiConverter { } /** - * Extracts the status line from the supplied Java API {@link java.net.CacheResponse}. - * As per the spec, the status line is held as the header with the null key. Throws a - * {@link ProtocolException} if there is no status line. + * Extracts the status line from the supplied Java API {@link java.net.CacheResponse}. As per the + * spec, the status line is held as the header with the null key. Throws a {@link + * ProtocolException} if there is no status line. */ private static String extractStatusLine(CacheResponse javaResponse) throws IOException { Map> javaResponseHeaders = javaResponse.getHeaders(); @@ -465,7 +466,7 @@ public final class JavaApiConverter { // The status line is missing. This suggests a badly behaving cache. throw new ProtocolException( "CacheResponse is missing a \'null\' header containing the status line. Headers=" - + javaResponseHeaders); + + javaResponseHeaders); } return values.get(0); } @@ -487,6 +488,7 @@ public final class JavaApiConverter { public long contentLength() { return OkHeaders.contentLength(okHeaders); } + @Override public BufferedSource source() { return body; } @@ -507,10 +509,12 @@ public final class JavaApiConverter { String contentTypeHeader = urlConnection.getContentType(); return contentTypeHeader == null ? null : MediaType.parse(contentTypeHeader); } + @Override public long contentLength() { String s = urlConnection.getHeaderField("Content-Length"); return stringToLong(s); } + @Override public BufferedSource source() { return body; } @@ -518,10 +522,10 @@ public final class JavaApiConverter { } /** - * An {@link java.net.HttpURLConnection} that represents an HTTP request at the point where - * the request has been made, and the response headers have been received, but the body content, - * if present, has not been read yet. This intended to provide enough information for - * {@link java.net.ResponseCache} subclasses and no more. + * An {@link java.net.HttpURLConnection} that represents an HTTP request at the point where the + * request has been made, and the response headers have been received, but the body content, if + * present, has not been read yet. This intended to provide enough information for {@link + * java.net.ResponseCache} subclasses and no more. * *

Much of the method implementations are overrides to delegate to the OkHttp request and * response, or to deny access to information as a real HttpURLConnection would after connection. diff --git a/okhttp-android-support/src/test/java/okhttp3/android/HttpResponseCache.java b/okhttp-android-support/src/test/java/okhttp3/android/HttpResponseCache.java index 6b0802020..c569a3b36 100644 --- a/okhttp-android-support/src/test/java/okhttp3/android/HttpResponseCache.java +++ b/okhttp-android-support/src/test/java/okhttp3/android/HttpResponseCache.java @@ -16,10 +16,6 @@ package okhttp3.android; -import okhttp3.Cache; -import okhttp3.AndroidShimResponseCache; -import okhttp3.OkCacheContainer; - import java.io.Closeable; import java.io.File; import java.io.IOException; @@ -30,15 +26,18 @@ import java.net.URI; import java.net.URLConnection; import java.util.List; import java.util.Map; +import okhttp3.AndroidShimResponseCache; +import okhttp3.Cache; +import okhttp3.OkCacheContainer; /** * A copy of android.net.http.HttpResponseCache taken from AOSP. Android need to keep this code * working somehow. Dependencies on okhttp3 are com.android.okhttp on Android. * *

This class exists in okhttp-android-support to help keep the API as it always has been on - * Android. The public API cannot be changed. This class delegates to - * {@link AndroidShimResponseCache}, a class that exists in a package that - * enables it to interact with non-public OkHttp classes. + * Android. The public API cannot be changed. This class delegates to {@link + * AndroidShimResponseCache}, a class that exists in a package that enables it to interact with + * non-public OkHttp classes. */ public final class HttpResponseCache extends ResponseCache implements Closeable, OkCacheContainer { @@ -49,8 +48,8 @@ public final class HttpResponseCache extends ResponseCache implements Closeable, } /** - * Returns the currently-installed {@code HttpResponseCache}, or null if - * there is no cache installed or it is not a {@code HttpResponseCache}. + * Returns the currently-installed {@code HttpResponseCache}, or null if there is no cache + * installed or it is not a {@code HttpResponseCache}. */ public static HttpResponseCache getInstalled() { ResponseCache installed = ResponseCache.getDefault(); @@ -66,9 +65,8 @@ public final class HttpResponseCache extends ResponseCache implements Closeable, * @param directory the directory to hold cache data. * @param maxSize the maximum size of the cache in bytes. * @return the newly-installed cache - * @throws java.io.IOException if {@code directory} cannot be used for this cache. - * Most applications should respond to this exception by logging a - * warning. + * @throws java.io.IOException if {@code directory} cannot be used for this cache. Most + * applications should respond to this exception by logging a warning. */ public static synchronized HttpResponseCache install(File directory, long maxSize) throws IOException { @@ -103,9 +101,8 @@ public final class HttpResponseCache extends ResponseCache implements Closeable, } /** - * Returns the number of bytes currently being used to store the values in - * this cache. This may be greater than the {@link #maxSize} if a background - * deletion is pending. + * Returns the number of bytes currently being used to store the values in this cache. This may be + * greater than the {@link #maxSize} if a background deletion is pending. */ public long size() { try { @@ -117,17 +114,15 @@ public final class HttpResponseCache extends ResponseCache implements Closeable, } /** - * Returns the maximum number of bytes that this cache should use to store - * its data. + * Returns the maximum number of bytes that this cache should use to store its data. */ public long maxSize() { return shimResponseCache.maxSize(); } /** - * Force buffered operations to the filesystem. This ensures that responses - * written to the cache will be available the next time the cache is opened, - * even if this process is killed. + * Force buffered operations to the filesystem. This ensures that responses written to the cache + * will be available the next time the cache is opened, even if this process is killed. */ public void flush() { try { @@ -137,34 +132,32 @@ public final class HttpResponseCache extends ResponseCache implements Closeable, } /** - * Returns the number of HTTP requests that required the network to either - * supply a response or validate a locally cached response. + * Returns the number of HTTP requests that required the network to either supply a response or + * validate a locally cached response. */ public int getNetworkCount() { return shimResponseCache.getNetworkCount(); } /** - * Returns the number of HTTP requests whose response was provided by the - * cache. This may include conditional {@code GET} requests that were - * validated over the network. + * Returns the number of HTTP requests whose response was provided by the cache. This may include + * conditional {@code GET} requests that were validated over the network. */ public int getHitCount() { return shimResponseCache.getHitCount(); } /** - * Returns the total number of HTTP requests that were made. This includes - * both client requests and requests that were made on the client's behalf - * to handle a redirects and retries. + * Returns the total number of HTTP requests that were made. This includes both client requests + * and requests that were made on the client's behalf to handle a redirects and retries. */ public int getRequestCount() { return shimResponseCache.getRequestCount(); } /** - * Uninstalls the cache and releases any active resources. Stored contents - * will remain on the filesystem. + * Uninstalls the cache and releases any active resources. Stored contents will remain on the + * filesystem. */ @Override public void close() throws IOException { if (ResponseCache.getDefault() == this) { @@ -187,5 +180,4 @@ public final class HttpResponseCache extends ResponseCache implements Closeable, public Cache getCache() { return shimResponseCache.getCache(); } - } diff --git a/okhttp-android-support/src/test/java/okhttp3/android/HttpResponseCacheTest.java b/okhttp-android-support/src/test/java/okhttp3/android/HttpResponseCacheTest.java index dbaf9db93..842e8d310 100644 --- a/okhttp-android-support/src/test/java/okhttp3/android/HttpResponseCacheTest.java +++ b/okhttp-android-support/src/test/java/okhttp3/android/HttpResponseCacheTest.java @@ -16,12 +16,6 @@ package okhttp3.android; -import okhttp3.AndroidInternal; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.OkUrlFactory; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; import java.io.File; import java.io.InputStream; import java.net.CacheRequest; @@ -31,6 +25,12 @@ import java.net.URI; import java.net.URLConnection; import java.util.List; import java.util.Map; +import okhttp3.AndroidInternal; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.OkUrlFactory; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; import org.junit.After; import org.junit.Before; import org.junit.Rule; @@ -133,8 +133,8 @@ public final class HttpResponseCacheTest { } /** - * Make sure that statistics tracking are wired all the way through the - * wrapper class. http://code.google.com/p/android/issues/detail?id=25418 + * Make sure that statistics tracking are wired all the way through the wrapper class. + * http://code.google.com/p/android/issues/detail?id=25418 */ @Test public void statisticsTracking() throws Exception { HttpResponseCache cache = HttpResponseCache.install(cacheDir, 10 * 1024 * 1024); diff --git a/okhttp-android-support/src/test/java/okhttp3/internal/huc/CacheAdapterTest.java b/okhttp-android-support/src/test/java/okhttp3/internal/huc/CacheAdapterTest.java index eff0cd395..40d59d20c 100644 --- a/okhttp-android-support/src/test/java/okhttp3/internal/huc/CacheAdapterTest.java +++ b/okhttp-android-support/src/test/java/okhttp3/internal/huc/CacheAdapterTest.java @@ -15,14 +15,6 @@ */ package okhttp3.internal.huc; -import okhttp3.AbstractResponseCache; -import okhttp3.OkHttpClient; -import okhttp3.OkUrlFactory; -import okhttp3.internal.Internal; -import okhttp3.internal.SslContextBuilder; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import okhttp3.testing.RecordingHostnameVerifier; import java.io.IOException; import java.net.CacheRequest; import java.net.CacheResponse; @@ -38,6 +30,14 @@ import java.util.Map; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; +import okhttp3.AbstractResponseCache; +import okhttp3.OkHttpClient; +import okhttp3.OkUrlFactory; +import okhttp3.internal.Internal; +import okhttp3.internal.SslContextBuilder; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import okhttp3.testing.RecordingHostnameVerifier; import okio.Buffer; import org.junit.After; import org.junit.Before; @@ -51,10 +51,10 @@ import static org.junit.Assert.assertTrue; /** * A white-box test for {@link CacheAdapter}. See also: *

    - *
  • {@link ResponseCacheTest} for black-box tests that check that {@link ResponseCache} - * classes are called correctly by OkHttp.
  • - *
  • {@link JavaApiConverterTest} for tests that check Java API classes / OkHttp conversion - * logic.
  • + *
  • {@link ResponseCacheTest} for black-box tests that check that {@link ResponseCache} + * classes are called correctly by OkHttp. + *
  • {@link JavaApiConverterTest} for tests that check Java API classes / OkHttp conversion + * logic. *
*/ public class CacheAdapterTest { @@ -81,8 +81,8 @@ public class CacheAdapterTest { assertEquals("http", serverUrl.getProtocol()); ResponseCache responseCache = new AbstractResponseCache() { - @Override - public CacheResponse get(URI uri, String method, Map> headers) throws IOException { + @Override public CacheResponse get( + URI uri, String method, Map> headers) throws IOException { assertEquals(toUri(serverUrl), uri); assertEquals("GET", method); assertTrue("Arbitrary standard header not present", headers.containsKey("User-Agent")); @@ -214,7 +214,8 @@ public class CacheAdapterTest { assertEquals(serverUrl, connection.getURL()); HttpsURLConnection cacheHttpsUrlConnection = (HttpsURLConnection) connection; - HttpsURLConnection realHttpsUrlConnection = (HttpsURLConnection) CacheAdapterTest.this.connection; + HttpsURLConnection realHttpsUrlConnection = + (HttpsURLConnection) CacheAdapterTest.this.connection; assertEquals(realHttpsUrlConnection.getCipherSuite(), cacheHttpsUrlConnection.getCipherSuite()); assertEquals(realHttpsUrlConnection.getPeerPrincipal(), diff --git a/okhttp-android-support/src/test/java/okhttp3/internal/huc/JavaApiConverterTest.java b/okhttp-android-support/src/test/java/okhttp3/internal/huc/JavaApiConverterTest.java index 91c7737d4..13f938249 100644 --- a/okhttp-android-support/src/test/java/okhttp3/internal/huc/JavaApiConverterTest.java +++ b/okhttp-android-support/src/test/java/okhttp3/internal/huc/JavaApiConverterTest.java @@ -15,18 +15,6 @@ */ package okhttp3.internal.huc; -import okhttp3.CipherSuite; -import okhttp3.Handshake; -import okhttp3.Headers; -import okhttp3.MediaType; -import okhttp3.Protocol; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import okhttp3.internal.Internal; -import okhttp3.internal.Util; -import okhttp3.mockwebserver.MockWebServer; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -50,9 +38,20 @@ import java.util.Map; import java.util.Set; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLPeerUnverifiedException; +import okhttp3.CipherSuite; +import okhttp3.Handshake; +import okhttp3.Headers; +import okhttp3.MediaType; +import okhttp3.Protocol; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import okhttp3.internal.Internal; +import okhttp3.internal.Util; +import okhttp3.mockwebserver.MockWebServer; import okio.Buffer; import okio.BufferedSource; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -185,7 +184,8 @@ public class JavaApiConverterTest { return localCertificates; } - @Override public List getServerCertificateChain() throws SSLPeerUnverifiedException { + @Override public List getServerCertificateChain() + throws SSLPeerUnverifiedException { return serverCertificates; } @@ -223,7 +223,7 @@ public class JavaApiConverterTest { @Test public void createOkRequest_nullRequestHeaders() throws Exception { URI uri = new URI("http://foo/bar"); - Map> javaRequestHeaders = null; + Map> javaRequestHeaders = null; Request request = JavaApiConverter.createOkRequest(uri, "POST", javaRequestHeaders); assertFalse(request.isHttps()); assertEquals(uri, request.url().uri()); @@ -235,7 +235,7 @@ public class JavaApiConverterTest { @Test public void createOkRequest_nonNullRequestHeaders() throws Exception { URI uri = new URI("https://foo/bar"); - Map> javaRequestHeaders = new HashMap<>(); + Map> javaRequestHeaders = new HashMap<>(); javaRequestHeaders.put("Foo", Arrays.asList("Bar")); Request request = JavaApiConverter.createOkRequest(uri, "POST", javaRequestHeaders); assertTrue(request.isHttps()); @@ -253,7 +253,7 @@ public class JavaApiConverterTest { @Test public void createOkRequest_nullRequestHeaderKey() throws Exception { URI uri = new URI("https://foo/bar"); - Map> javaRequestHeaders = new HashMap<>(); + Map> javaRequestHeaders = new HashMap<>(); javaRequestHeaders.put(null, Arrays.asList("GET / HTTP 1.1")); javaRequestHeaders.put("Foo", Arrays.asList("Bar")); Request request = JavaApiConverter.createOkRequest(uri, "POST", javaRequestHeaders); @@ -474,8 +474,8 @@ public class JavaApiConverterTest { assertEquals("SSL_RSA_WITH_NULL_MD5", httpsUrlConnection.getCipherSuite()); assertEquals(SERVER_CERT.getSubjectX500Principal(), httpsUrlConnection.getPeerPrincipal()); - assertArrayEquals(new Certificate[] { LOCAL_CERT }, httpsUrlConnection.getLocalCertificates()); - assertArrayEquals(new Certificate[] { SERVER_CERT }, + assertArrayEquals(new Certificate[] {LOCAL_CERT}, httpsUrlConnection.getLocalCertificates()); + assertArrayEquals(new Certificate[] {SERVER_CERT}, httpsUrlConnection.getServerCertificates()); assertEquals(LOCAL_CERT.getSubjectX500Principal(), httpsUrlConnection.getLocalPrincipal()); } @@ -551,7 +551,7 @@ public class JavaApiConverterTest { Request okRequest = createArbitraryOkRequest().newBuilder() .url("https://secure/request") - .post(createRequestBody("RequestBody") ) + .post(createRequestBody("RequestBody")) .build(); ResponseBody responseBody = createResponseBody("ResponseBody"); Handshake handshake = Handshake.get(null, CipherSuite.TLS_RSA_WITH_NULL_MD5, diff --git a/okhttp-android-support/src/test/java/okhttp3/internal/huc/ResponseCacheTest.java b/okhttp-android-support/src/test/java/okhttp3/internal/huc/ResponseCacheTest.java index bfd7a3976..6f71a7254 100644 --- a/okhttp-android-support/src/test/java/okhttp3/internal/huc/ResponseCacheTest.java +++ b/okhttp-android-support/src/test/java/okhttp3/internal/huc/ResponseCacheTest.java @@ -16,18 +16,6 @@ package okhttp3.internal.huc; -import okhttp3.AbstractResponseCache; -import okhttp3.AndroidInternal; -import okhttp3.AndroidShimResponseCache; -import okhttp3.Headers; -import okhttp3.OkHttpClient; -import okhttp3.OkUrlFactory; -import okhttp3.internal.Internal; -import okhttp3.internal.SslContextBuilder; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import okhttp3.mockwebserver.RecordedRequest; -import okhttp3.testing.RecordingHostnameVerifier; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.FileNotFoundException; @@ -67,7 +55,19 @@ import java.util.concurrent.atomic.AtomicReference; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; +import okhttp3.AbstractResponseCache; +import okhttp3.AndroidInternal; +import okhttp3.AndroidShimResponseCache; +import okhttp3.Headers; +import okhttp3.OkHttpClient; +import okhttp3.OkUrlFactory; +import okhttp3.internal.Internal; +import okhttp3.internal.SslContextBuilder; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import okhttp3.mockwebserver.RecordedRequest; import okhttp3.mockwebserver.SocketPolicy; +import okhttp3.testing.RecordingHostnameVerifier; import okio.Buffer; import okio.BufferedSink; import okio.GzipSink; @@ -86,8 +86,8 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** - * Tests the interaction between OkHttp and {@link ResponseCache}. - * Based on okhttp3.CacheTest with changes for ResponseCache and HttpURLConnection. + * Tests the interaction between OkHttp and {@link ResponseCache}. Based on okhttp3.CacheTest with + * changes for ResponseCache and HttpURLConnection. */ public final class ResponseCacheTest { @Rule public TemporaryFolder cacheRule = new TemporaryFolder(); @@ -133,45 +133,45 @@ public final class ResponseCacheTest { // assertCached(false, 100); assertCached(false, 101); assertCached(false, 102); - assertCached(true, 200); + assertCached(true, 200); assertCached(false, 201); assertCached(false, 202); - assertCached(true, 203); - assertCached(true, 204); + assertCached(true, 203); + assertCached(true, 204); assertCached(false, 205); assertCached(false, 206); //Electing to not cache partial responses assertCached(false, 207); - assertCached(true, 300); - assertCached(true, 301); - assertCached(true, 302); + assertCached(true, 300); + assertCached(true, 301); + assertCached(true, 302); assertCached(false, 303); assertCached(false, 304); assertCached(false, 305); assertCached(false, 306); - assertCached(true, 307); - assertCached(true, 308); + assertCached(true, 307); + assertCached(true, 308); assertCached(false, 400); assertCached(false, 401); assertCached(false, 402); assertCached(false, 403); - assertCached(true, 404); - assertCached(true, 405); + assertCached(true, 404); + assertCached(true, 405); assertCached(false, 406); assertCached(false, 408); assertCached(false, 409); // the HTTP spec permits caching 410s, but the RI doesn't. - assertCached(true, 410); + assertCached(true, 410); assertCached(false, 411); assertCached(false, 412); assertCached(false, 413); - assertCached(true, 414); + assertCached(true, 414); assertCached(false, 415); assertCached(false, 416); assertCached(false, 417); assertCached(false, 418); assertCached(false, 500); - assertCached(true, 501); + assertCached(true, 501); assertCached(false, 502); assertCached(false, 503); assertCached(false, 504); @@ -363,10 +363,9 @@ public final class ResponseCacheTest { } /** - * We've had bugs where caching and cross-protocol redirects yield class - * cast exceptions internal to the cache because we incorrectly assumed that - * HttpsURLConnection was always HTTPS and HttpURLConnection was always HTTP; - * in practice redirects mean that each can do either. + * We've had bugs where caching and cross-protocol redirects yield class cast exceptions internal + * to the cache because we incorrectly assumed that HttpsURLConnection was always HTTPS and + * HttpURLConnection was always HTTP; in practice redirects mean that each can do either. * * https://github.com/square/okhttp/issues/214 */ @@ -767,7 +766,8 @@ public final class ResponseCacheTest { /** * Equivalent to {@code CacheTest.postInvalidatesCacheWithUncacheableResponse()} but demonstrating * that {@link ResponseCache} provides no mechanism for cache invalidation as the result of - * locally-made requests. In reality invalidation could take place from other clients at any time. + * locally-made requests. In reality invalidation could take place from other clients at any + * time. */ @Test public void postInvalidatesCacheWithUncacheableResponse() throws Exception { // 1. seed the cache @@ -1168,8 +1168,8 @@ public final class ResponseCacheTest { } /** - * For Last-Modified and Date headers, we should echo the date back in the - * exact format we were served. + * For Last-Modified and Date headers, we should echo the date back in the exact format we were + * served. */ @Test public void retainServedDateFormat() throws Exception { // Serve a response with a non-standard date format that OkHttp supports. @@ -1566,7 +1566,7 @@ public final class ResponseCacheTest { assertEquals(Arrays.asList(expectedCookies), actualCookies); } - @Test public void doNotCachePartialResponse() throws Exception { + @Test public void doNotCachePartialResponse() throws Exception { assertNotCached(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_PARTIAL) .addHeader("Date: " + formatDate(0, TimeUnit.HOURS)) @@ -1682,9 +1682,8 @@ public final class ResponseCacheTest { } /** - * @param delta the offset from the current date to use. Negative - * values yield dates in the past; positive values yield dates in the - * future. + * @param delta the offset from the current date to use. Negative values yield dates in the past; + * positive values yield dates in the future. */ private String formatDate(long delta, TimeUnit timeUnit) { return formatDate(new Date(System.currentTimeMillis() + timeUnit.toMillis(delta))); @@ -1750,9 +1749,8 @@ public final class ResponseCacheTest { } /** - * Shortens the body of {@code response} but not the corresponding headers. - * Only useful to test how clients respond to the premature conclusion of - * the HTTP body. + * Shortens the body of {@code response} but not the corresponding headers. Only useful to test + * how clients respond to the premature conclusion of the HTTP body. */ private MockResponse truncateViolently(MockResponse response, int numBytesToKeep) { response.setSocketPolicy(SocketPolicy.DISCONNECT_AT_END); @@ -1801,9 +1799,8 @@ public final class ResponseCacheTest { } /** - * Reads {@code count} characters from the stream. If the stream is - * exhausted before {@code count} characters can be read, the remaining - * characters are returned and the stream is closed. + * Reads {@code count} characters from the stream. If the stream is exhausted before {@code count} + * characters can be read, the remaining characters are returned and the stream is closed. */ private String readAscii(URLConnection connection, int count) throws IOException { HttpURLConnection httpConnection = (HttpURLConnection) connection; @@ -1848,8 +1845,8 @@ public final class ResponseCacheTest { // Android-added tests. /** - * Test that we can interrogate the response when the cache is being - * populated. http://code.google.com/p/android/issues/detail?id=7787 + * Test that we can interrogate the response when the cache is being populated. + * http://code.google.com/p/android/issues/detail?id=7787 */ @Test public void responseCacheCallbackApis() throws Exception { final String body = "ABCDE"; @@ -1973,6 +1970,7 @@ public final class ResponseCacheTest { @Override public InputStream getBody() throws IOException { return response.getBody(); } + @Override public Map> getHeaders() throws IOException { return response.getHeaders(); } diff --git a/okhttp-apache/pom.xml b/okhttp-apache/pom.xml index 6e9a797cd..f0b4b6859 100644 --- a/okhttp-apache/pom.xml +++ b/okhttp-apache/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 diff --git a/okhttp-apache/src/main/java/okhttp3/apache/HttpEntityBody.java b/okhttp-apache/src/main/java/okhttp3/apache/HttpEntityBody.java index c971691f3..45d27aafd 100644 --- a/okhttp-apache/src/main/java/okhttp3/apache/HttpEntityBody.java +++ b/okhttp-apache/src/main/java/okhttp3/apache/HttpEntityBody.java @@ -1,8 +1,8 @@ package okhttp3.apache; +import java.io.IOException; import okhttp3.MediaType; import okhttp3.RequestBody; -import java.io.IOException; import okio.BufferedSink; import org.apache.http.HttpEntity; diff --git a/okhttp-apache/src/main/java/okhttp3/apache/OkApacheClient.java b/okhttp-apache/src/main/java/okhttp3/apache/OkApacheClient.java index 2a862fa52..d5689bd7e 100644 --- a/okhttp-apache/src/main/java/okhttp3/apache/OkApacheClient.java +++ b/okhttp-apache/src/main/java/okhttp3/apache/OkApacheClient.java @@ -1,15 +1,15 @@ // Copyright 2013 Square, Inc. package okhttp3.apache; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Proxy; import okhttp3.Headers; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.Proxy; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; @@ -32,9 +32,9 @@ import static java.net.Proxy.Type.HTTP; import static org.apache.http.HttpVersion.HTTP_1_1; /** - * @deprecated OkHttp will be dropping its ability to be used with {@link HttpClient} in an - * upcoming release. Applications that need this should either downgrade to the Apache - * implementation or upgrade to OkHttp's Request/Response API. + * @deprecated OkHttp will be dropping its ability to be used with {@link HttpClient} in an upcoming + * release. Applications that need this should either downgrade to the Apache implementation or + * upgrade to OkHttp's Request/Response API. */ public final class OkApacheClient implements HttpClient { private static Request transformRequest(HttpRequest request) { diff --git a/okhttp-apache/src/test/java/okhttp3/apache/OkApacheClientTest.java b/okhttp-apache/src/test/java/okhttp3/apache/OkApacheClientTest.java index 8f5c3cd15..77493a254 100644 --- a/okhttp-apache/src/test/java/okhttp3/apache/OkApacheClientTest.java +++ b/okhttp-apache/src/test/java/okhttp3/apache/OkApacheClientTest.java @@ -1,13 +1,13 @@ package okhttp3.apache; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import okhttp3.mockwebserver.RecordedRequest; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.util.zip.GZIPInputStream; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import okhttp3.mockwebserver.RecordedRequest; import okio.Buffer; import okio.GzipSink; import okio.Okio; @@ -114,20 +114,22 @@ public class OkApacheClientTest { assertEquals("Hello, world!", request.getBody().readUtf8()); assertEquals(request.getHeader("Content-Length"), "13"); } + @Test public void postEmptyEntity() throws Exception { server.enqueue(new MockResponse()); final HttpPost post = new HttpPost(server.url("/").url().toURI()); client.execute(post); - + RecordedRequest request = server.takeRequest(); assertEquals(0, request.getBodySize()); assertNotNull(request.getBody()); } + @Test public void putEmptyEntity() throws Exception { server.enqueue(new MockResponse()); final HttpPut put = new HttpPut(server.url("/").url().toURI()); client.execute(put); - + RecordedRequest request = server.takeRequest(); assertEquals(0, request.getBodySize()); assertNotNull(request.getBody()); diff --git a/okhttp-hpacktests/pom.xml b/okhttp-hpacktests/pom.xml index 98947ce30..0a64ace19 100644 --- a/okhttp-hpacktests/pom.xml +++ b/okhttp-hpacktests/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 diff --git a/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/HpackDecodeInteropTest.java b/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/HpackDecodeInteropTest.java index bab0503a4..74ca6a2fb 100644 --- a/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/HpackDecodeInteropTest.java +++ b/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/HpackDecodeInteropTest.java @@ -15,8 +15,8 @@ */ package okhttp3.internal.spdy; -import okhttp3.internal.spdy.hpackjson.Story; import java.util.Collection; +import okhttp3.internal.spdy.hpackjson.Story; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @@ -30,7 +30,7 @@ public class HpackDecodeInteropTest extends HpackDecodeTestBase { super(story); } - @Parameterized.Parameters(name="{0}") + @Parameterized.Parameters(name = "{0}") public static Collection createStories() throws Exception { return createStories(storiesForCurrentDraft()); } diff --git a/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/HpackDecodeTestBase.java b/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/HpackDecodeTestBase.java index f5cc86aaf..77c7ddf1a 100644 --- a/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/HpackDecodeTestBase.java +++ b/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/HpackDecodeTestBase.java @@ -15,13 +15,13 @@ */ package okhttp3.internal.spdy; -import okhttp3.internal.spdy.hpackjson.Case; -import okhttp3.internal.spdy.hpackjson.HpackJsonUtil; -import okhttp3.internal.spdy.hpackjson.Story; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; +import okhttp3.internal.spdy.hpackjson.Case; +import okhttp3.internal.spdy.hpackjson.HpackJsonUtil; +import okhttp3.internal.spdy.hpackjson.Story; import okio.Buffer; import static org.junit.Assert.assertEquals; @@ -44,7 +44,7 @@ public class HpackDecodeTestBase { fail("No stories for: " + interopTestName); } for (Story story : stories) { - result.add(new Story[] { story }); + result.add(new Story[] {story}); } } return result; @@ -60,8 +60,7 @@ public class HpackDecodeTestBase { } /** - * Expects wire to be set for all cases, and compares the decoder's output to - * expected headers. + * Expects wire to be set for all cases, and compares the decoder's output to expected headers. */ protected void testDecoder() throws Exception { testDecoder(story); @@ -75,9 +74,10 @@ public class HpackDecodeTestBase { hpackReader.getAndResetHeaderList()); } } + /** - * Checks if {@code expected} and {@code observed} are equal when viewed as a - * set and headers are deduped. + * Checks if {@code expected} and {@code observed} are equal when viewed as a set and headers are + * deduped. * * TODO: See if duped headers should be preserved on decode and verify. */ diff --git a/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/HpackRoundTripTest.java b/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/HpackRoundTripTest.java index 7d130c263..22eecd776 100644 --- a/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/HpackRoundTripTest.java +++ b/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/HpackRoundTripTest.java @@ -15,6 +15,7 @@ */ package okhttp3.internal.spdy; +import java.util.Collection; import okhttp3.internal.spdy.hpackjson.Case; import okhttp3.internal.spdy.hpackjson.Story; import okio.Buffer; @@ -22,8 +23,6 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import java.util.Collection; - /** * Tests for round-tripping headers through hpack.. */ @@ -34,9 +33,9 @@ import java.util.Collection; @RunWith(Parameterized.class) public class HpackRoundTripTest extends HpackDecodeTestBase { - private static final String[] RAW_DATA = { "raw-data" }; + private static final String[] RAW_DATA = {"raw-data"}; - @Parameterized.Parameters(name="{0}") + @Parameterized.Parameters(name = "{0}") public static Collection getStories() throws Exception { return createStories(RAW_DATA); } @@ -59,5 +58,4 @@ public class HpackRoundTripTest extends HpackDecodeTestBase { testDecoder(story); } - } diff --git a/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/hpackjson/Case.java b/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/hpackjson/Case.java index 74d413f87..6ff0eb057 100644 --- a/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/hpackjson/Case.java +++ b/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/hpackjson/Case.java @@ -23,9 +23,8 @@ import okhttp3.internal.framed.Header; import okio.ByteString; /** - * Representation of an individual case (set of headers and wire format). - * There are many cases for a single story. This class is used reflectively - * with Gson to parse stories. + * Representation of an individual case (set of headers and wire format). There are many cases for a + * single story. This class is used reflectively with Gson to parse stories. */ public class Case implements Cloneable { diff --git a/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/hpackjson/HpackJsonUtil.java b/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/hpackjson/HpackJsonUtil.java index 5e31fb29c..f53ab7885 100644 --- a/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/hpackjson/HpackJsonUtil.java +++ b/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/hpackjson/HpackJsonUtil.java @@ -85,5 +85,6 @@ public final class HpackJsonUtil { return result; } - private HpackJsonUtil() { } // Utilities only. + private HpackJsonUtil() { + } // Utilities only. } diff --git a/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/hpackjson/Story.java b/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/hpackjson/Story.java index a33c3a6f9..417d426c7 100644 --- a/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/hpackjson/Story.java +++ b/okhttp-hpacktests/src/test/java/okhttp3/internal/spdy/hpackjson/Story.java @@ -19,8 +19,8 @@ import java.util.ArrayList; import java.util.List; /** - * Representation of one story, a set of request headers to encode or decode. - * This class is used reflectively with Gson to parse stories from files. + * Representation of one story, a set of request headers to encode or decode. This class is used + * reflectively with Gson to parse stories from files. */ public class Story implements Cloneable { diff --git a/okhttp-logging-interceptor/pom.xml b/okhttp-logging-interceptor/pom.xml index 011ed00fb..bd4b1466f 100644 --- a/okhttp-logging-interceptor/pom.xml +++ b/okhttp-logging-interceptor/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 diff --git a/okhttp-logging-interceptor/src/main/java/okhttp3/logging/HttpLoggingInterceptor.java b/okhttp-logging-interceptor/src/main/java/okhttp3/logging/HttpLoggingInterceptor.java index 9b4d0e6b2..f9f4fc0f7 100644 --- a/okhttp-logging-interceptor/src/main/java/okhttp3/logging/HttpLoggingInterceptor.java +++ b/okhttp-logging-interceptor/src/main/java/okhttp3/logging/HttpLoggingInterceptor.java @@ -15,6 +15,9 @@ */ package okhttp3.logging; +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.concurrent.TimeUnit; import okhttp3.Connection; import okhttp3.Headers; import okhttp3.Interceptor; @@ -27,19 +30,15 @@ import okhttp3.Response; import okhttp3.ResponseBody; import okhttp3.internal.Platform; import okhttp3.internal.http.HttpEngine; -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.concurrent.TimeUnit; import okio.Buffer; import okio.BufferedSource; /** * An OkHttp interceptor which logs request and response information. Can be applied as an - * {@linkplain OkHttpClient#interceptors() application interceptor} or as a - * {@linkplain OkHttpClient#networkInterceptors() network interceptor}. - *

- * The format of the logs created by this class should not be considered stable and may change - * slightly between releases. If you need a stable logging format, use your own interceptor. + * {@linkplain OkHttpClient#interceptors() application interceptor} or as a {@linkplain + * OkHttpClient#networkInterceptors() network interceptor}.

The format of the logs created by + * this class should not be considered stable and may change slightly between releases. If you need + * a stable logging format, use your own interceptor. */ public final class HttpLoggingInterceptor implements Interceptor { private static final Charset UTF8 = Charset.forName("UTF-8"); @@ -49,8 +48,8 @@ public final class HttpLoggingInterceptor implements Interceptor { NONE, /** * Logs request and response lines. - *

- * Example: + * + *

Example: *

{@code
      * --> POST /greeting HTTP/1.1 (3-byte body)
      *
@@ -60,8 +59,8 @@ public final class HttpLoggingInterceptor implements Interceptor {
     BASIC,
     /**
      * Logs request and response lines and their respective headers.
-     * 

- * Example: + * + *

Example: *

{@code
      * --> POST /greeting HTTP/1.1
      * Host: example.com
@@ -78,8 +77,8 @@ public final class HttpLoggingInterceptor implements Interceptor {
     HEADERS,
     /**
      * Logs request and response lines and their respective headers and bodies (if present).
-     * 

- * Example: + * + *

Example: *

{@code
      * --> POST /greeting HTTP/1.1
      * Host: example.com
diff --git a/okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.java b/okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.java
index e31a16391..82ee698cd 100644
--- a/okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.java
+++ b/okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.java
@@ -15,6 +15,10 @@
  */
 package okhttp3.logging;
 
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Pattern;
 import okhttp3.HttpUrl;
 import okhttp3.MediaType;
 import okhttp3.OkHttpClient;
@@ -24,10 +28,6 @@ import okhttp3.Response;
 import okhttp3.logging.HttpLoggingInterceptor.Level;
 import okhttp3.mockwebserver.MockResponse;
 import okhttp3.mockwebserver.MockWebServer;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.regex.Pattern;
 import okio.Buffer;
 import okio.BufferedSink;
 import okio.ByteString;
diff --git a/okhttp-testing-support/pom.xml b/okhttp-testing-support/pom.xml
index d363749fa..9b4af3439 100644
--- a/okhttp-testing-support/pom.xml
+++ b/okhttp-testing-support/pom.xml
@@ -1,6 +1,8 @@
 
 
-
+
   4.0.0
 
   
diff --git a/okhttp-testing-support/src/main/java/okhttp3/testing/InstallUncaughtExceptionHandlerListener.java b/okhttp-testing-support/src/main/java/okhttp3/testing/InstallUncaughtExceptionHandlerListener.java
index bcb4df7a2..38652c07d 100644
--- a/okhttp-testing-support/src/main/java/okhttp3/testing/InstallUncaughtExceptionHandlerListener.java
+++ b/okhttp-testing-support/src/main/java/okhttp3/testing/InstallUncaughtExceptionHandlerListener.java
@@ -15,18 +15,16 @@
  */
 package okhttp3.testing;
 
+import java.io.PrintWriter;
+import java.io.StringWriter;
 import org.junit.runner.Description;
 import org.junit.runner.Result;
 import org.junit.runner.notification.RunListener;
 
-import java.io.PrintWriter;
-import java.io.StringWriter;
-
 /**
- * A {@link org.junit.runner.notification.RunListener} used to install an aggressive default
- * {@link java.lang.Thread.UncaughtExceptionHandler} similar to the one found on Android.
- * No exceptions should escape from OkHttp that might cause apps to be killed or tests to fail on
- * Android.
+ * A {@link org.junit.runner.notification.RunListener} used to install an aggressive default {@link
+ * java.lang.Thread.UncaughtExceptionHandler} similar to the one found on Android. No exceptions
+ * should escape from OkHttp that might cause apps to be killed or tests to fail on Android.
  */
 public class InstallUncaughtExceptionHandlerListener extends RunListener {
 
diff --git a/okhttp-tests/pom.xml b/okhttp-tests/pom.xml
index cb0c01793..919722502 100644
--- a/okhttp-tests/pom.xml
+++ b/okhttp-tests/pom.xml
@@ -1,6 +1,8 @@
 
 
-
+
   4.0.0
 
   
diff --git a/okhttp-tests/src/test/java/okhttp3/AddressTest.java b/okhttp-tests/src/test/java/okhttp3/AddressTest.java
index 5f346c978..7ff65a010 100644
--- a/okhttp-tests/src/test/java/okhttp3/AddressTest.java
+++ b/okhttp-tests/src/test/java/okhttp3/AddressTest.java
@@ -15,11 +15,11 @@
  */
 package okhttp3;
 
+import java.util.List;
+import javax.net.SocketFactory;
 import okhttp3.internal.Util;
 import okhttp3.internal.http.AuthenticatorAdapter;
 import okhttp3.internal.http.RecordingProxySelector;
-import java.util.List;
-import javax.net.SocketFactory;
 import org.junit.Test;
 
 import static org.junit.Assert.assertEquals;
diff --git a/okhttp-tests/src/test/java/okhttp3/CacheTest.java b/okhttp-tests/src/test/java/okhttp3/CacheTest.java
index 85a613ae6..b6feada1d 100644
--- a/okhttp-tests/src/test/java/okhttp3/CacheTest.java
+++ b/okhttp-tests/src/test/java/okhttp3/CacheTest.java
@@ -16,13 +16,6 @@
 
 package okhttp3;
 
-import okhttp3.internal.Internal;
-import okhttp3.internal.SslContextBuilder;
-import okhttp3.internal.Util;
-import okhttp3.internal.io.InMemoryFileSystem;
-import okhttp3.mockwebserver.MockResponse;
-import okhttp3.mockwebserver.MockWebServer;
-import okhttp3.mockwebserver.RecordedRequest;
 import java.io.File;
 import java.io.IOException;
 import java.net.CookieHandler;
@@ -47,6 +40,13 @@ import java.util.concurrent.atomic.AtomicReference;
 import javax.net.ssl.HostnameVerifier;
 import javax.net.ssl.SSLContext;
 import javax.net.ssl.SSLSession;
+import okhttp3.internal.Internal;
+import okhttp3.internal.SslContextBuilder;
+import okhttp3.internal.Util;
+import okhttp3.internal.io.InMemoryFileSystem;
+import okhttp3.mockwebserver.MockResponse;
+import okhttp3.mockwebserver.MockWebServer;
+import okhttp3.mockwebserver.RecordedRequest;
 import okio.Buffer;
 import okio.BufferedSink;
 import okio.BufferedSource;
@@ -107,45 +107,45 @@ public final class CacheTest {
     // assertCached(false, 100);
     assertCached(false, 101);
     assertCached(false, 102);
-    assertCached(true,  200);
+    assertCached(true, 200);
     assertCached(false, 201);
     assertCached(false, 202);
-    assertCached(true,  203);
-    assertCached(true,  204);
+    assertCached(true, 203);
+    assertCached(true, 204);
     assertCached(false, 205);
     assertCached(false, 206); //Electing to not cache partial responses
     assertCached(false, 207);
-    assertCached(true,  300);
-    assertCached(true,  301);
-    assertCached(true,  302);
+    assertCached(true, 300);
+    assertCached(true, 301);
+    assertCached(true, 302);
     assertCached(false, 303);
     assertCached(false, 304);
     assertCached(false, 305);
     assertCached(false, 306);
-    assertCached(true,  307);
-    assertCached(true,  308);
+    assertCached(true, 307);
+    assertCached(true, 308);
     assertCached(false, 400);
     assertCached(false, 401);
     assertCached(false, 402);
     assertCached(false, 403);
-    assertCached(true,  404);
-    assertCached(true,  405);
+    assertCached(true, 404);
+    assertCached(true, 405);
     assertCached(false, 406);
     assertCached(false, 408);
     assertCached(false, 409);
     // the HTTP spec permits caching 410s, but the RI doesn't.
-    assertCached(true,  410);
+    assertCached(true, 410);
     assertCached(false, 411);
     assertCached(false, 412);
     assertCached(false, 413);
-    assertCached(true,  414);
+    assertCached(true, 414);
     assertCached(false, 415);
     assertCached(false, 416);
     assertCached(false, 417);
     assertCached(false, 418);
 
     assertCached(false, 500);
-    assertCached(true,  501);
+    assertCached(true, 501);
     assertCached(false, 502);
     assertCached(false, 503);
     assertCached(false, 504);
@@ -369,10 +369,9 @@ public final class CacheTest {
   }
 
   /**
-   * We've had bugs where caching and cross-protocol redirects yield class
-   * cast exceptions internal to the cache because we incorrectly assumed that
-   * HttpsURLConnection was always HTTPS and HttpURLConnection was always HTTP;
-   * in practice redirects mean that each can do either.
+   * We've had bugs where caching and cross-protocol redirects yield class cast exceptions internal
+   * to the cache because we incorrectly assumed that HttpsURLConnection was always HTTPS and
+   * HttpURLConnection was always HTTP; in practice redirects mean that each can do either.
    *
    * https://github.com/square/okhttp/issues/214
    */
@@ -740,8 +739,8 @@ public final class CacheTest {
 
   private RequestBody requestBodyOrNull(String requestMethod) {
     return (requestMethod.equals("POST") || requestMethod.equals("PUT"))
-          ? RequestBody.create(MediaType.parse("text/plain"), "foo")
-          : null;
+        ? RequestBody.create(MediaType.parse("text/plain"), "foo")
+        : null;
   }
 
   @Test public void postInvalidatesCache() throws Exception {
@@ -1262,8 +1261,8 @@ public final class CacheTest {
   }
 
   /**
-   * For Last-Modified and Date headers, we should echo the date back in the
-   * exact format we were served.
+   * For Last-Modified and Date headers, we should echo the date back in the exact format we were
+   * served.
    */
   @Test public void retainServedDateFormat() throws Exception {
     // Serve a response with a non-standard date format that OkHttp supports.
@@ -1774,7 +1773,7 @@ public final class CacheTest {
     assertEquals(Arrays.asList(expectedCookies), actualCookies);
   }
 
-  @Test public void doNotCachePartialResponse() throws Exception  {
+  @Test public void doNotCachePartialResponse() throws Exception {
     assertNotCached(new MockResponse()
         .setResponseCode(HttpURLConnection.HTTP_PARTIAL)
         .addHeader("Date: " + formatDate(0, TimeUnit.HOURS))
@@ -1877,10 +1876,9 @@ public final class CacheTest {
   }
 
   /**
-   * Old implementations of OkHttp's response cache wrote header fields like
-   * ":status: 200 OK". This broke our cached response parser because it split
-   * on the first colon. This regression test exists to help us read these old
-   * bad cache entries.
+   * Old implementations of OkHttp's response cache wrote header fields like ":status: 200 OK". This
+   * broke our cached response parser because it split on the first colon. This regression test
+   * exists to help us read these old bad cache entries.
    *
    * https://github.com/square/okhttp/issues/227
    */
@@ -2278,7 +2276,6 @@ public final class CacheTest {
     return client.newCall(request).execute();
   }
 
-
   private void writeFile(File directory, String file, String content) throws IOException {
     BufferedSink sink = Okio.buffer(fileSystem.sink(new File(directory, file)));
     sink.writeUtf8(content);
@@ -2286,9 +2283,8 @@ public final class CacheTest {
   }
 
   /**
-   * @param delta the offset from the current date to use. Negative
-   * values yield dates in the past; positive values yield dates in the
-   * future.
+   * @param delta the offset from the current date to use. Negative values yield dates in the past;
+   * positive values yield dates in the future.
    */
   private String formatDate(long delta, TimeUnit timeUnit) {
     return formatDate(new Date(System.currentTimeMillis() + timeUnit.toMillis(delta)));
@@ -2358,9 +2354,8 @@ public final class CacheTest {
   }
 
   /**
-   * Shortens the body of {@code response} but not the corresponding headers.
-   * Only useful to test how clients respond to the premature conclusion of
-   * the HTTP body.
+   * Shortens the body of {@code response} but not the corresponding headers. Only useful to test
+   * how clients respond to the premature conclusion of the HTTP body.
    */
   private MockResponse truncateViolently(MockResponse response, int numBytesToKeep) {
     response.setSocketPolicy(DISCONNECT_AT_END);
diff --git a/okhttp-tests/src/test/java/okhttp3/CallTest.java b/okhttp-tests/src/test/java/okhttp3/CallTest.java
index 183f50e22..4cc81b4b3 100644
--- a/okhttp-tests/src/test/java/okhttp3/CallTest.java
+++ b/okhttp-tests/src/test/java/okhttp3/CallTest.java
@@ -579,14 +579,14 @@ public final class CallTest {
     try {
       call.execute();
       fail();
-    } catch (IllegalStateException e){
+    } catch (IllegalStateException e) {
       assertEquals("Already Executed", e.getMessage());
     }
 
     try {
       call.enqueue(callback);
       fail();
-    } catch (IllegalStateException e){
+    } catch (IllegalStateException e) {
       assertEquals("Already Executed", e.getMessage());
     }
 
@@ -609,14 +609,14 @@ public final class CallTest {
     try {
       call.execute();
       fail();
-    } catch (IllegalStateException e){
+    } catch (IllegalStateException e) {
       assertEquals("Already Executed", e.getMessage());
     }
 
     try {
       call.enqueue(callback);
       fail();
-    } catch (IllegalStateException e){
+    } catch (IllegalStateException e) {
       assertEquals("Already Executed", e.getMessage());
     }
 
@@ -822,6 +822,7 @@ public final class CallTest {
       @Override public MediaType contentType() {
         return MediaType.parse("text/plain");
       }
+
       @Override public void writeTo(BufferedSink sink) throws IOException {
         sink.writeUtf8("abc");
         sink.timeout().deadline(5, TimeUnit.SECONDS);
@@ -839,6 +840,7 @@ public final class CallTest {
       @Override public MediaType contentType() {
         return MediaType.parse("text/plain");
       }
+
       @Override public void writeTo(BufferedSink sink) throws IOException {
         assertFalse(sink.timeout().hasDeadline());
         sink.writeUtf8("def");
@@ -2246,8 +2248,8 @@ public final class CallTest {
 
   /**
    * Used during tests that involve TLS connection fallback attempts. OkHttp includes the
-   * TLS_FALLBACK_SCSV cipher on fallback connections. See
-   * {@link FallbackTestClientSocketFactory} for details.
+   * TLS_FALLBACK_SCSV cipher on fallback connections. See {@link FallbackTestClientSocketFactory}
+   * for details.
    */
   private void suppressTlsFallbackScsv(OkHttpClient client) {
     FallbackTestClientSocketFactory clientSocketFactory =
diff --git a/okhttp-tests/src/test/java/okhttp3/CertificatePinnerTest.java b/okhttp-tests/src/test/java/okhttp3/CertificatePinnerTest.java
index baa17fb26..cdfe9b0f0 100644
--- a/okhttp-tests/src/test/java/okhttp3/CertificatePinnerTest.java
+++ b/okhttp-tests/src/test/java/okhttp3/CertificatePinnerTest.java
@@ -15,12 +15,12 @@
  */
 package okhttp3;
 
-import okhttp3.internal.SslContextBuilder;
 import java.security.GeneralSecurityException;
 import java.security.KeyPair;
 import java.security.cert.X509Certificate;
 import java.util.Set;
 import javax.net.ssl.SSLPeerUnverifiedException;
+import okhttp3.internal.SslContextBuilder;
 import okio.ByteString;
 import org.junit.Test;
 
@@ -165,7 +165,8 @@ public final class CertificatePinnerTest {
     certificatePinner.check("a.example.com", keypairACertificate1);
   }
 
-  @Test public void successfulMatchAcceptsAnyMatchingCertificateForWildcardHostname() throws Exception {
+  @Test public void successfulMatchAcceptsAnyMatchingCertificateForWildcardHostname()
+      throws Exception {
     CertificatePinner certificatePinner = new CertificatePinner.Builder()
         .add("*.example.com", keypairBCertificate1Pin)
         .build();
@@ -194,7 +195,8 @@ public final class CertificatePinnerTest {
     certificatePinner.check("a.example.com", keypairBCertificate1);
   }
 
-  @Test public void successfulCheckForOneHostnameWithWildcardAndDirectCertificate() throws Exception {
+  @Test public void successfulCheckForOneHostnameWithWildcardAndDirectCertificate()
+      throws Exception {
     CertificatePinner certificatePinner = new CertificatePinner.Builder()
         .add("*.example.com", keypairACertificate1Pin)
         .add("a.example.com", keypairBCertificate1Pin)
@@ -204,7 +206,8 @@ public final class CertificatePinnerTest {
     certificatePinner.check("a.example.com", keypairBCertificate1);
   }
 
-  @Test public void unsuccessfulCheckForOneHostnameWithWildcardAndDirectCertificate() throws Exception {
+  @Test public void unsuccessfulCheckForOneHostnameWithWildcardAndDirectCertificate()
+      throws Exception {
     CertificatePinner certificatePinner = new CertificatePinner.Builder()
         .add("*.example.com", keypairACertificate1Pin)
         .add("a.example.com", keypairBCertificate1Pin)
@@ -223,8 +226,9 @@ public final class CertificatePinnerTest {
         .add("second.com", keypairCCertificate1Pin)
         .build();
 
-    Set expectedPins = setOf(keypairACertificate1PinBase64, keypairBCertificate1PinBase64);
-    Set matchedPins  = certificatePinner.findMatchingPins("first.com");
+    Set expectedPins =
+        setOf(keypairACertificate1PinBase64, keypairBCertificate1PinBase64);
+    Set matchedPins = certificatePinner.findMatchingPins("first.com");
 
     assertEquals(expectedPins, matchedPins);
   }
@@ -236,8 +240,9 @@ public final class CertificatePinnerTest {
         .add("b.example.com", keypairCCertificate1Pin)
         .build();
 
-    Set expectedPins = setOf(keypairACertificate1PinBase64, keypairBCertificate1PinBase64);
-    Set matchedPins  = certificatePinner.findMatchingPins("a.example.com");
+    Set expectedPins =
+        setOf(keypairACertificate1PinBase64, keypairBCertificate1PinBase64);
+    Set matchedPins = certificatePinner.findMatchingPins("a.example.com");
 
     assertEquals(expectedPins, matchedPins);
   }
diff --git a/okhttp-tests/src/test/java/okhttp3/ConnectionPoolTest.java b/okhttp-tests/src/test/java/okhttp3/ConnectionPoolTest.java
index ef298c64f..f04871079 100644
--- a/okhttp-tests/src/test/java/okhttp3/ConnectionPoolTest.java
+++ b/okhttp-tests/src/test/java/okhttp3/ConnectionPoolTest.java
@@ -15,9 +15,6 @@
  */
 package okhttp3;
 
-import okhttp3.internal.RecordingOkAuthenticator;
-import okhttp3.internal.http.StreamAllocation;
-import okhttp3.internal.io.RealConnection;
 import java.net.InetSocketAddress;
 import java.net.Proxy;
 import java.net.ProxySelector;
@@ -25,6 +22,9 @@ import java.net.Socket;
 import java.util.Collections;
 import java.util.concurrent.TimeUnit;
 import javax.net.SocketFactory;
+import okhttp3.internal.RecordingOkAuthenticator;
+import okhttp3.internal.http.StreamAllocation;
+import okhttp3.internal.io.RealConnection;
 import org.junit.Test;
 
 import static org.junit.Assert.assertEquals;
diff --git a/okhttp-tests/src/test/java/okhttp3/ConnectionReuseTest.java b/okhttp-tests/src/test/java/okhttp3/ConnectionReuseTest.java
index b48279804..a2ac36dcd 100644
--- a/okhttp-tests/src/test/java/okhttp3/ConnectionReuseTest.java
+++ b/okhttp-tests/src/test/java/okhttp3/ConnectionReuseTest.java
@@ -15,14 +15,14 @@
  */
 package okhttp3;
 
+import java.util.Arrays;
+import java.util.concurrent.TimeUnit;
+import javax.net.ssl.SSLContext;
 import okhttp3.internal.SslContextBuilder;
 import okhttp3.mockwebserver.MockResponse;
 import okhttp3.mockwebserver.MockWebServer;
 import okhttp3.mockwebserver.SocketPolicy;
 import okhttp3.testing.RecordingHostnameVerifier;
-import java.util.Arrays;
-import java.util.concurrent.TimeUnit;
-import javax.net.ssl.SSLContext;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.rules.TestRule;
diff --git a/okhttp-tests/src/test/java/okhttp3/ConnectionSpecTest.java b/okhttp-tests/src/test/java/okhttp3/ConnectionSpecTest.java
index 7db756d5a..7fbd08e62 100644
--- a/okhttp-tests/src/test/java/okhttp3/ConnectionSpecTest.java
+++ b/okhttp-tests/src/test/java/okhttp3/ConnectionSpecTest.java
@@ -214,8 +214,8 @@ public final class ConnectionSpecTest {
 
     tlsSpec.apply(sslSocket, false);
     assertEquals(Arrays.asList(
-            CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName,
-            CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName),
+        CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName,
+        CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName),
         Arrays.asList(sslSocket.getEnabledCipherSuites()));
   }
 
@@ -249,10 +249,10 @@ public final class ConnectionSpecTest {
     });
 
     socket.setEnabledProtocols(
-        new String[] { TlsVersion.TLS_1_2.javaName, TlsVersion.TLS_1_1.javaName });
+        new String[] {TlsVersion.TLS_1_2.javaName, TlsVersion.TLS_1_1.javaName});
     assertTrue(tlsSpec.isCompatible(socket));
 
-    socket.setEnabledProtocols(new String[] { TlsVersion.TLS_1_1.javaName });
+    socket.setEnabledProtocols(new String[] {TlsVersion.TLS_1_1.javaName});
     assertFalse(tlsSpec.isCompatible(socket));
   }
 
diff --git a/okhttp-tests/src/test/java/okhttp3/DelegatingSSLSocketFactory.java b/okhttp-tests/src/test/java/okhttp3/DelegatingSSLSocketFactory.java
index 8d0d092f2..00a968e7b 100644
--- a/okhttp-tests/src/test/java/okhttp3/DelegatingSSLSocketFactory.java
+++ b/okhttp-tests/src/test/java/okhttp3/DelegatingSSLSocketFactory.java
@@ -19,13 +19,12 @@ import java.io.IOException;
 import java.net.InetAddress;
 import java.net.Socket;
 import java.net.UnknownHostException;
-import javax.net.SocketFactory;
 import javax.net.ssl.SSLSocket;
 import javax.net.ssl.SSLSocketFactory;
 
 /**
- * A {@link SSLSocketFactory} that delegates calls. Sockets can be configured after
- * creation by overriding {@link #configureSocket(javax.net.ssl.SSLSocket)}.
+ * A {@link SSLSocketFactory} that delegates calls. Sockets can be configured after creation by
+ * overriding {@link #configureSocket(javax.net.ssl.SSLSocket)}.
  */
 public class DelegatingSSLSocketFactory extends SSLSocketFactory {
 
diff --git a/okhttp-tests/src/test/java/okhttp3/FallbackTestClientSocketFactory.java b/okhttp-tests/src/test/java/okhttp3/FallbackTestClientSocketFactory.java
index 7a34362b4..eb9aaaa2d 100644
--- a/okhttp-tests/src/test/java/okhttp3/FallbackTestClientSocketFactory.java
+++ b/okhttp-tests/src/test/java/okhttp3/FallbackTestClientSocketFactory.java
@@ -29,8 +29,8 @@ import javax.net.ssl.SSLSocketFactory;
  */
 public class FallbackTestClientSocketFactory extends DelegatingSSLSocketFactory {
   /**
-   * The cipher suite used during TLS connection fallback to indicate a fallback.
-   * See https://tools.ietf.org/html/draft-ietf-tls-downgrade-scsv-00
+   * The cipher suite used during TLS connection fallback to indicate a fallback. See
+   * https://tools.ietf.org/html/draft-ietf-tls-downgrade-scsv-00
    */
   public static final String TLS_FALLBACK_SCSV = "TLS_FALLBACK_SCSV";
 
diff --git a/okhttp-tests/src/test/java/okhttp3/FormBodyTest.java b/okhttp-tests/src/test/java/okhttp3/FormBodyTest.java
index a572ff235..34e40b96f 100644
--- a/okhttp-tests/src/test/java/okhttp3/FormBodyTest.java
+++ b/okhttp-tests/src/test/java/okhttp3/FormBodyTest.java
@@ -189,7 +189,7 @@ public final class FormBodyTest {
   private String formEncode(int codePoint) throws IOException {
     // Wrap the codepoint with regular printable characters to prevent trimming.
     FormBody body = new FormBody.Builder()
-        .add("a", new String(new int[] { 'b', codePoint, 'c' }, 0, 3))
+        .add("a", new String(new int[] {'b', codePoint, 'c'}, 0, 3))
         .build();
     Buffer buffer = new Buffer();
     body.writeTo(buffer);
diff --git a/okhttp-tests/src/test/java/okhttp3/HttpUrlTest.java b/okhttp-tests/src/test/java/okhttp3/HttpUrlTest.java
index e435134d0..2cb7f8b92 100644
--- a/okhttp-tests/src/test/java/okhttp3/HttpUrlTest.java
+++ b/okhttp-tests/src/test/java/okhttp3/HttpUrlTest.java
@@ -1012,7 +1012,7 @@ public final class HttpUrlTest {
     assertEquals("http://host/=[]:;%22~%7C%3F%23@%5E%2F$%25*", url.toString());
     assertEquals("http://host/=%5B%5D:;%22~%7C%3F%23@%5E%2F$%25*", url.uri().toString());
   }
-  
+
   @Test public void toUriQueryParameterNameSpecialCharacters() throws Exception {
     HttpUrl url = new HttpUrl.Builder()
         .scheme("http")
@@ -1307,8 +1307,8 @@ public final class HttpUrlTest {
   }
 
   /**
-   * Although HttpUrl prefers percent-encodings in uppercase, it should preserve the exact
-   * structure of the original encoding.
+   * Although HttpUrl prefers percent-encodings in uppercase, it should preserve the exact structure
+   * of the original encoding.
    */
   @Test public void rawEncodingRetained() throws Exception {
     String urlString = "http://%6d%6D:%6d%6D@host/%6d%6D?%6d%6D#%6d%6D";
diff --git a/okhttp-tests/src/test/java/okhttp3/InterceptorTest.java b/okhttp-tests/src/test/java/okhttp3/InterceptorTest.java
index baea2839d..fc5765131 100644
--- a/okhttp-tests/src/test/java/okhttp3/InterceptorTest.java
+++ b/okhttp-tests/src/test/java/okhttp3/InterceptorTest.java
@@ -15,9 +15,6 @@
  */
 package okhttp3;
 
-import okhttp3.mockwebserver.MockResponse;
-import okhttp3.mockwebserver.MockWebServer;
-import okhttp3.mockwebserver.RecordedRequest;
 import java.io.IOException;
 import java.util.Arrays;
 import java.util.List;
@@ -27,6 +24,9 @@ import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.SynchronousQueue;
 import java.util.concurrent.ThreadPoolExecutor;
 import java.util.concurrent.TimeUnit;
+import okhttp3.mockwebserver.MockResponse;
+import okhttp3.mockwebserver.MockWebServer;
+import okhttp3.mockwebserver.RecordedRequest;
 import okio.Buffer;
 import okio.BufferedSink;
 import okio.ForwardingSink;
@@ -502,8 +502,8 @@ public final class InterceptorTest {
     Interceptor modifyHeaderInterceptor = new Interceptor() {
       @Override public Response intercept(Chain chain) throws IOException {
         return chain.proceed(chain.request().newBuilder()
-          .header("User-Agent", "intercepted request")
-          .build());
+            .header("User-Agent", "intercepted request")
+            .build());
       }
     };
 
@@ -533,7 +533,7 @@ public final class InterceptorTest {
    * exception goes to the uncaught exception handler.
    */
   private void interceptorThrowsRuntimeExceptionAsynchronous(
-        List interceptors) throws Exception {
+      List interceptors) throws Exception {
     interceptors.add(new Interceptor() {
       @Override public Response intercept(Chain chain) throws IOException {
         throw new RuntimeException("boom!");
diff --git a/okhttp-tests/src/test/java/okhttp3/MediaTypeTest.java b/okhttp-tests/src/test/java/okhttp3/MediaTypeTest.java
index 8f2dbe79e..b4e9c2ec2 100644
--- a/okhttp-tests/src/test/java/okhttp3/MediaTypeTest.java
+++ b/okhttp-tests/src/test/java/okhttp3/MediaTypeTest.java
@@ -16,10 +16,10 @@
  */
 package okhttp3;
 
-import okhttp3.internal.Util;
 import java.nio.charset.Charset;
 import java.nio.charset.IllegalCharsetNameException;
 import java.nio.charset.UnsupportedCharsetException;
+import okhttp3.internal.Util;
 import org.junit.Test;
 
 import static org.junit.Assert.assertEquals;
@@ -30,8 +30,8 @@ import static org.junit.Assert.fail;
 /**
  * Test MediaType API and parsing.
  *
- * 

This test includes tests from Guava's MediaTypeTest. + *

This test includes tests from Guava's + * MediaTypeTest. */ public class MediaTypeTest { @Test public void testParse() throws Exception { diff --git a/okhttp-tests/src/test/java/okhttp3/OkHttpClientTest.java b/okhttp-tests/src/test/java/okhttp3/OkHttpClientTest.java index 7a5477d04..0715a45a0 100644 --- a/okhttp-tests/src/test/java/okhttp3/OkHttpClientTest.java +++ b/okhttp-tests/src/test/java/okhttp3/OkHttpClientTest.java @@ -106,8 +106,7 @@ public final class OkHttpClientTest { } /** - * Confirm that {@code copyWithDefaults} gets some default implementations - * from the core library. + * Confirm that {@code copyWithDefaults} gets some default implementations from the core library. */ @Test public void copyWithDefaultsWhenDefaultIsGlobal() throws Exception { ProxySelector proxySelector = new RecordingProxySelector(); @@ -164,8 +163,8 @@ public final class OkHttpClientTest { } /** - * When copying the client, stateful things like the connection pool are - * shared across all clients. + * When copying the client, stateful things like the connection pool are shared across all + * clients. */ @Test public void cloneSharesStatefulInstances() throws Exception { OkHttpClient client = new OkHttpClient(); diff --git a/okhttp-tests/src/test/java/okhttp3/RecordedResponse.java b/okhttp-tests/src/test/java/okhttp3/RecordedResponse.java index ef4934520..0c9d1169f 100644 --- a/okhttp-tests/src/test/java/okhttp3/RecordedResponse.java +++ b/okhttp-tests/src/test/java/okhttp3/RecordedResponse.java @@ -15,9 +15,9 @@ */ package okhttp3; -import okhttp3.ws.WebSocket; import java.io.IOException; import java.util.Arrays; +import okhttp3.ws.WebSocket; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -96,8 +96,7 @@ public final class RecordedResponse { } /** - * Asserts that the current response was redirected and returns the prior - * response. + * Asserts that the current response was redirected and returns the prior response. */ public RecordedResponse priorResponse() { Response priorResponse = response.priorResponse(); @@ -107,8 +106,7 @@ public final class RecordedResponse { } /** - * Asserts that the current response used the network and returns the network - * response. + * Asserts that the current response used the network and returns the network response. */ public RecordedResponse networkResponse() { Response networkResponse = response.networkResponse(); @@ -130,8 +128,7 @@ public final class RecordedResponse { } /** - * Asserts that the current response used the cache and returns the cache - * response. + * Asserts that the current response used the cache and returns the cache response. */ public RecordedResponse cacheResponse() { Response cacheResponse = response.cacheResponse(); diff --git a/okhttp-tests/src/test/java/okhttp3/RecordingCallback.java b/okhttp-tests/src/test/java/okhttp3/RecordingCallback.java index 68d4adbab..22124cb52 100644 --- a/okhttp-tests/src/test/java/okhttp3/RecordingCallback.java +++ b/okhttp-tests/src/test/java/okhttp3/RecordingCallback.java @@ -41,8 +41,8 @@ public class RecordingCallback implements Callback { } /** - * Returns the recorded response triggered by {@code request}. Throws if the - * response isn't enqueued before the timeout. + * Returns the recorded response triggered by {@code request}. Throws if the response isn't + * enqueued before the timeout. */ public synchronized RecordedResponse await(HttpUrl url) throws Exception { long timeoutMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) + TIMEOUT_MILLIS; diff --git a/okhttp-tests/src/test/java/okhttp3/RequestTest.java b/okhttp-tests/src/test/java/okhttp3/RequestTest.java index 929d04b35..0ef87d6c8 100644 --- a/okhttp-tests/src/test/java/okhttp3/RequestTest.java +++ b/okhttp-tests/src/test/java/okhttp3/RequestTest.java @@ -15,13 +15,13 @@ */ package okhttp3; -import okhttp3.internal.Util; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.URI; import java.util.Arrays; import java.util.Collections; +import okhttp3.internal.Util; import okio.Buffer; import org.junit.Test; @@ -125,7 +125,8 @@ public final class RequestTest { @Test public void newBuilderUrlResetsUrl() throws Exception { Request requestWithoutCache = new Request.Builder().url("http://localhost/api").build(); - Request builtRequestWithoutCache = requestWithoutCache.newBuilder().url("http://localhost/api/foo").build(); + Request builtRequestWithoutCache = + requestWithoutCache.newBuilder().url("http://localhost/api/foo").build(); assertEquals(HttpUrl.parse("http://localhost/api/foo"), builtRequestWithoutCache.url()); Request requestWithCache = new Request.Builder().url("http://localhost/api").build(); diff --git a/okhttp-tests/src/test/java/okhttp3/SocksProxy.java b/okhttp-tests/src/test/java/okhttp3/SocksProxy.java index 4cc4cae67..ce949ebae 100644 --- a/okhttp-tests/src/test/java/okhttp3/SocksProxy.java +++ b/okhttp-tests/src/test/java/okhttp3/SocksProxy.java @@ -15,8 +15,6 @@ */ package okhttp3; -import okhttp3.internal.NamedRunnable; -import okhttp3.internal.Util; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -31,6 +29,8 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; +import okhttp3.internal.NamedRunnable; +import okhttp3.internal.Util; import okio.Buffer; import okio.BufferedSink; import okio.BufferedSource; diff --git a/okhttp-tests/src/test/java/okhttp3/SocksProxyTest.java b/okhttp-tests/src/test/java/okhttp3/SocksProxyTest.java index 83a7ba1af..f6d830174 100644 --- a/okhttp-tests/src/test/java/okhttp3/SocksProxyTest.java +++ b/okhttp-tests/src/test/java/okhttp3/SocksProxyTest.java @@ -15,8 +15,6 @@ */ package okhttp3; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; import java.io.IOException; import java.net.Proxy; import java.net.ProxySelector; @@ -24,6 +22,8 @@ import java.net.SocketAddress; import java.net.URI; import java.util.Collections; import java.util.List; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/okhttp-tests/src/test/java/okhttp3/TestUtil.java b/okhttp-tests/src/test/java/okhttp3/TestUtil.java index dffa66711..b1916189e 100644 --- a/okhttp-tests/src/test/java/okhttp3/TestUtil.java +++ b/okhttp-tests/src/test/java/okhttp3/TestUtil.java @@ -1,12 +1,12 @@ package okhttp3; -import okhttp3.internal.framed.Header; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; +import okhttp3.internal.framed.Header; public final class TestUtil { private TestUtil() { diff --git a/okhttp-tests/src/test/java/okhttp3/URLConnectionTest.java b/okhttp-tests/src/test/java/okhttp3/URLConnectionTest.java index 0328317d4..ac7265ab7 100644 --- a/okhttp-tests/src/test/java/okhttp3/URLConnectionTest.java +++ b/okhttp-tests/src/test/java/okhttp3/URLConnectionTest.java @@ -16,18 +16,6 @@ package okhttp3; -import okhttp3.internal.Internal; -import okhttp3.internal.RecordingAuthenticator; -import okhttp3.internal.RecordingOkAuthenticator; -import okhttp3.internal.SingleInetAddressDns; -import okhttp3.internal.SslContextBuilder; -import okhttp3.internal.Util; -import okhttp3.internal.Version; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import okhttp3.mockwebserver.RecordedRequest; -import okhttp3.mockwebserver.SocketPolicy; -import okhttp3.testing.RecordingHostnameVerifier; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -69,6 +57,18 @@ import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; +import okhttp3.internal.Internal; +import okhttp3.internal.RecordingAuthenticator; +import okhttp3.internal.RecordingOkAuthenticator; +import okhttp3.internal.SingleInetAddressDns; +import okhttp3.internal.SslContextBuilder; +import okhttp3.internal.Util; +import okhttp3.internal.Version; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import okhttp3.mockwebserver.RecordedRequest; +import okhttp3.mockwebserver.SocketPolicy; +import okhttp3.testing.RecordingHostnameVerifier; import okio.Buffer; import okio.BufferedSink; import okio.GzipSink; @@ -636,8 +636,8 @@ public final class URLConnectionTest { } /** - * When a pooled connection fails, don't blame the route. Otherwise pooled - * connection failures can cause unnecessary SSL fallbacks. + * When a pooled connection fails, don't blame the route. Otherwise pooled connection failures can + * cause unnecessary SSL fallbacks. * * https://github.com/square/okhttp/issues/515 */ @@ -733,11 +733,23 @@ public final class URLConnectionTest { public void testConnectViaSocketFactory(boolean useHttps) throws IOException { SocketFactory uselessSocketFactory = new SocketFactory() { - public Socket createSocket() { throw new IllegalArgumentException("useless"); } - public Socket createSocket(InetAddress host, int port) { return null; } + public Socket createSocket() { + throw new IllegalArgumentException("useless"); + } + + public Socket createSocket(InetAddress host, int port) { + return null; + } + public Socket createSocket(InetAddress address, int port, InetAddress localAddress, - int localPort) { return null; } - public Socket createSocket(String host, int port) { return null; } + int localPort) { + return null; + } + + public Socket createSocket(String host, int port) { + return null; + } + public Socket createSocket(String host, int port, InetAddress localHost, int localPort) { return null; } @@ -837,8 +849,8 @@ public final class URLConnectionTest { } /** - * We weren't honoring all of the appropriate proxy system properties when - * connecting via HTTPS. http://b/3097518 + * We weren't honoring all of the appropriate proxy system properties when connecting via HTTPS. + * http://b/3097518 */ @Test public void connectViaHttpProxyToHttpsUsingProxySystemProperty() throws Exception { testConnectViaHttpProxyToHttps(ProxyConfig.PROXY_SYSTEM_PROPERTY); @@ -849,8 +861,8 @@ public final class URLConnectionTest { } /** - * We were verifying the wrong hostname when connecting to an HTTPS site - * through a proxy. http://b/3097277 + * We were verifying the wrong hostname when connecting to an HTTPS site through a proxy. + * http://b/3097277 */ private void testConnectViaHttpProxyToHttps(ProxyConfig proxyConfig) throws Exception { RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier(); @@ -1050,9 +1062,8 @@ public final class URLConnectionTest { } /** - * Reads {@code count} characters from the stream. If the stream is - * exhausted before {@code count} characters can be read, the remaining - * characters are returned and the stream is closed. + * Reads {@code count} characters from the stream. If the stream is exhausted before {@code count} + * characters can be read, the remaining characters are returned and the stream is closed. */ private String readAscii(InputStream in, int count) throws IOException { StringBuilder result = new StringBuilder(); @@ -1100,9 +1111,8 @@ public final class URLConnectionTest { } /** - * We've had a bug where we forget the HTTP response when we see response - * code 401. This causes a new HTTP request to be issued for every call into - * the URLConnection. + * We've had a bug where we forget the HTTP response when we see response code 401. This causes a + * new HTTP request to be issued for every call into the URLConnection. */ @Test public void unauthorizedResponseHandling() throws IOException { MockResponse response = new MockResponse().addHeader("WWW-Authenticate: challenge") @@ -1177,9 +1187,8 @@ public final class URLConnectionTest { } /** - * This test checks whether connections are gzipped by default. This - * behavior in not required by the API, so a failure of this test does not - * imply a bug in the implementation. + * This test checks whether connections are gzipped by default. This behavior in not required by + * the API, so a failure of this test does not imply a bug in the implementation. */ @Test public void gzipEncodingEnabledByDefault() throws IOException, InterruptedException { server.enqueue(new MockResponse() @@ -1239,9 +1248,8 @@ public final class URLConnectionTest { } /** - * Test a bug where gzip input streams weren't exhausting the input stream, - * which corrupted the request that followed or prevented connection reuse. - * http://code.google.com/p/android/issues/detail?id=7059 + * Test a bug where gzip input streams weren't exhausting the input stream, which corrupted the + * request that followed or prevented connection reuse. http://code.google.com/p/android/issues/detail?id=7059 * http://code.google.com/p/android/issues/detail?id=38817 */ private void testClientConfiguredGzipContentEncodingAndConnectionReuse(TransferKind transferKind, @@ -1402,7 +1410,7 @@ public final class URLConnectionTest { Authenticator.setDefault(new RecordingAuthenticator()); connection = client.open(server.url("/").url()); connection.setDoOutput(true); - byte[] requestBody = { 'A', 'B', 'C', 'D' }; + byte[] requestBody = {'A', 'B', 'C', 'D'}; if (streamingMode == StreamingMode.FIXED_LENGTH) { connection.setFixedLengthStreamingMode(requestBody.length); } else if (streamingMode == StreamingMode.CHUNKED) { @@ -1684,7 +1692,7 @@ public final class URLConnectionTest { client.client().setHostnameVerifier(new RecordingHostnameVerifier()); connection = client.open(server.url("/").url()); connection.setDoOutput(true); - byte[] requestBody = { 'A', 'B', 'C', 'D' }; + byte[] requestBody = {'A', 'B', 'C', 'D'}; if (streamingMode == StreamingMode.FIXED_LENGTH) { connection.setFixedLengthStreamingMode(requestBody.length); } else if (streamingMode == StreamingMode.CHUNKED) { @@ -1723,7 +1731,7 @@ public final class URLConnectionTest { Authenticator.setDefault(new RecordingAuthenticator()); connection = client.open(server.url("/").url()); connection.setDoOutput(true); - byte[] requestBody = { 'A', 'B', 'C', 'D' }; + byte[] requestBody = {'A', 'B', 'C', 'D'}; OutputStream outputStream = connection.getOutputStream(); outputStream.write(requestBody); outputStream.close(); @@ -2046,7 +2054,7 @@ public final class URLConnectionTest { connection = client.open(server.url("/page1").url()); connection.setDoOutput(true); transferKind.setForRequest(connection, 4); - byte[] requestBody = { 'A', 'B', 'C', 'D' }; + byte[] requestBody = {'A', 'B', 'C', 'D'}; OutputStream outputStream = connection.getOutputStream(); outputStream.write(requestBody); outputStream.close(); @@ -2144,7 +2152,7 @@ public final class URLConnectionTest { connection = client.open(server.url("/page1").url()); connection.setRequestMethod(method); - byte[] requestBody = { 'A', 'B', 'C', 'D' }; + byte[] requestBody = {'A', 'B', 'C', 'D'}; if (method.equals("POST")) { connection.setDoOutput(true); OutputStream outputStream = connection.getOutputStream(); @@ -2159,7 +2167,7 @@ public final class URLConnectionTest { if (method.equals("GET")) { assertEquals("Page 2", response); - } else if (method.equals("HEAD")) { + } else if (method.equals("HEAD")) { assertEquals("", response); } else { // Methods other than GET/HEAD shouldn't follow the redirect @@ -2215,7 +2223,7 @@ public final class URLConnectionTest { RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier(); RecordingTrustManager trustManager = new RecordingTrustManager(); SSLContext sc = SSLContext.getInstance("TLS"); - sc.init(null, new TrustManager[] { trustManager }, new java.security.SecureRandom()); + sc.init(null, new TrustManager[] {trustManager}, new java.security.SecureRandom()); client.client().setHostnameVerifier(hostnameVerifier); client.client().setSslSocketFactory(sc.getSocketFactory()); @@ -2362,8 +2370,7 @@ public final class URLConnectionTest { } /** - * Retry redirects if the socket is closed. - * https://code.google.com/p/android/issues/detail?id=41576 + * Retry redirects if the socket is closed. https://code.google.com/p/android/issues/detail?id=41576 */ @Test public void sameConnectionRedirectAndReuse() throws Exception { server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP) @@ -2409,9 +2416,9 @@ public final class URLConnectionTest { } /** - * We explicitly permit apps to close the upload stream even after it has - * been transmitted. We also permit flush so that buffered streams can - * do a no-op flush when they are closed. http://b/3038470 + * We explicitly permit apps to close the upload stream even after it has been transmitted. We + * also permit flush so that buffered streams can do a no-op flush when they are closed. + * http://b/3038470 */ private void testFlushAfterStreamTransmitted(TransferKind transferKind) throws IOException { server.enqueue(new MockResponse().setBody("abc")); @@ -2521,11 +2528,11 @@ public final class URLConnectionTest { } catch (NullPointerException expected) { } try { - connection.getContent(new Class[] { null }); + connection.getContent(new Class[] {null}); fail(); } catch (NullPointerException expected) { } - assertNull(connection.getContent(new Class[] { getClass() })); + assertNull(connection.getContent(new Class[] {getClass()})); connection.getInputStream().close(); } @@ -2574,7 +2581,7 @@ public final class URLConnectionTest { connection = client.open(server.url("/").url()); connection.setDoOutput(true); OutputStream out = connection.getOutputStream(); - out.write(new byte[] { 'A', 'B', 'C' }); + out.write(new byte[] {'A', 'B', 'C'}); out.close(); assertEquals("A", readAscii(connection.getInputStream(), Integer.MAX_VALUE)); RecordedRequest request = server.takeRequest(); @@ -2916,8 +2923,8 @@ public final class URLConnectionTest { @Test public void customTokenAuthenticator() throws Exception { MockResponse pleaseAuthenticate = new MockResponse().setResponseCode(401) - .addHeader("WWW-Authenticate: Bearer realm=\"oauthed\"") - .setBody("Please authenticate."); + .addHeader("WWW-Authenticate: Bearer realm=\"oauthed\"") + .setBody("Please authenticate."); server.enqueue(pleaseAuthenticate); server.enqueue(new MockResponse().setBody("A")); @@ -3120,10 +3127,9 @@ public final class URLConnectionTest { } /** - * We had a bug where we attempted to gunzip responses that didn't have a - * body. This only came up with 304s since that response code can include - * headers (like "Content-Encoding") without any content to go along with it. - * https://github.com/square/okhttp/issues/358 + * We had a bug where we attempted to gunzip responses that didn't have a body. This only came up + * with 304s since that response code can include headers (like "Content-Encoding") without any + * content to go along with it. https://github.com/square/okhttp/issues/358 */ @Test public void noTransparentGzipFor304NotModified() throws Exception { server.enqueue(new MockResponse() @@ -3170,8 +3176,8 @@ public final class URLConnectionTest { } /** - * The RFC is unclear in this regard as it only specifies that this should - * invalidate the cache entry (if any). + * The RFC is unclear in this regard as it only specifies that this should invalidate the cache + * entry (if any). */ @Test public void bodyPermittedOnDelete() throws Exception { server.enqueue(new MockResponse()); @@ -3304,8 +3310,8 @@ public final class URLConnectionTest { } /** - * Reads at most {@code limit} characters from {@code in} and asserts that - * content equals {@code expected}. + * Reads at most {@code limit} characters from {@code in} and asserts that content equals {@code + * expected}. */ private void assertContent(String expected, HttpURLConnection connection, int limit) throws IOException { @@ -3327,6 +3333,7 @@ public final class URLConnectionTest { throws IOException { response.setChunkedBody(content, chunkSize); } + @Override void setForRequest(HttpURLConnection connection, int contentLength) { connection.setChunkedStreamingMode(5); } @@ -3335,6 +3342,7 @@ public final class URLConnectionTest { @Override void setBody(MockResponse response, Buffer content, int chunkSize) { response.setBody(content); } + @Override void setForRequest(HttpURLConnection connection, int contentLength) { connection.setFixedLengthStreamingMode(contentLength); } @@ -3345,6 +3353,7 @@ public final class URLConnectionTest { response.setSocketPolicy(DISCONNECT_AT_END); response.removeHeader("Content-Length"); } + @Override void setForRequest(HttpURLConnection connection, int contentLength) { } }; @@ -3416,7 +3425,7 @@ public final class URLConnectionTest { private final List calls = new ArrayList(); public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[] { }; + return new X509Certificate[] {}; } public void checkClientTrusted(X509Certificate[] chain, String authType) @@ -3466,8 +3475,8 @@ public final class URLConnectionTest { /** * Used during tests that involve TLS connection fallback attempts. OkHttp includes the - * TLS_FALLBACK_SCSV cipher on fallback connections. See - * {@link FallbackTestClientSocketFactory} for details. + * TLS_FALLBACK_SCSV cipher on fallback connections. See {@link FallbackTestClientSocketFactory} + * for details. */ private void suppressTlsFallbackScsv(OkHttpClient client) { FallbackTestClientSocketFactory clientSocketFactory = diff --git a/okhttp-tests/src/test/java/okhttp3/UrlComponentEncodingTester.java b/okhttp-tests/src/test/java/okhttp3/UrlComponentEncodingTester.java index 65b80e149..1645acc90 100644 --- a/okhttp-tests/src/test/java/okhttp3/UrlComponentEncodingTester.java +++ b/okhttp-tests/src/test/java/okhttp3/UrlComponentEncodingTester.java @@ -38,6 +38,7 @@ class UrlComponentEncodingTester { * See https://url.spec.whatwg.org/#percent-encoded-bytes */ private static final Map defaultEncodings; + static { Map map = new LinkedHashMap<>(); map.put( 0x0, Encoding.PERCENT); // Null character @@ -278,7 +279,7 @@ class UrlComponentEncodingTester { private void testUri( int codePoint, Encoding encoding, Component component, boolean uriEscaped) { - String string = new String(new int[] { codePoint }, 0, 1); + String string = new String(new int[] {codePoint}, 0, 1); String encoded = encoding.encode(codePoint); HttpUrl httpUrl = HttpUrl.parse(component.urlString(encoded)); URI uri = httpUrl.uri(); @@ -305,7 +306,7 @@ class UrlComponentEncodingTester { public enum Encoding { IDENTITY { public String encode(int codePoint) { - return new String(new int[] { codePoint }, 0, 1); + return new String(new int[] {codePoint}, 0, 1); } }, @@ -332,12 +333,15 @@ class UrlComponentEncodingTester { @Override public String urlString(String value) { return "http://" + value + "@example.com/"; } + @Override public String encodedValue(HttpUrl url) { return url.encodedUsername(); } + @Override public void set(HttpUrl.Builder builder, String value) { builder.username(value); } + @Override public String get(HttpUrl url) { return url.username(); } @@ -346,12 +350,15 @@ class UrlComponentEncodingTester { @Override public String urlString(String value) { return "http://:" + value + "@example.com/"; } + @Override public String encodedValue(HttpUrl url) { return url.encodedPassword(); } + @Override public void set(HttpUrl.Builder builder, String value) { builder.password(value); } + @Override public String get(HttpUrl url) { return url.password(); } @@ -360,13 +367,16 @@ class UrlComponentEncodingTester { @Override public String urlString(String value) { return "http://example.com/a" + value + "z/"; } + @Override public String encodedValue(HttpUrl url) { String path = url.encodedPath(); return path.substring(2, path.length() - 2); } + @Override public void set(HttpUrl.Builder builder, String value) { builder.addPathSegment("a" + value + "z"); } + @Override public String get(HttpUrl url) { String pathSegment = url.pathSegments().get(0); return pathSegment.substring(1, pathSegment.length() - 1); @@ -376,13 +386,16 @@ class UrlComponentEncodingTester { @Override public String urlString(String value) { return "http://example.com/?a" + value + "z"; } + @Override public String encodedValue(HttpUrl url) { String query = url.encodedQuery(); return query.substring(1, query.length() - 1); } + @Override public void set(HttpUrl.Builder builder, String value) { builder.query("a" + value + "z"); } + @Override public String get(HttpUrl url) { String query = url.query(); return query.substring(1, query.length() - 1); @@ -392,13 +405,16 @@ class UrlComponentEncodingTester { @Override public String urlString(String value) { return "http://example.com/#a" + value + "z"; } + @Override public String encodedValue(HttpUrl url) { String fragment = url.encodedFragment(); return fragment.substring(1, fragment.length() - 1); } + @Override public void set(HttpUrl.Builder builder, String value) { builder.fragment("a" + value + "z"); } + @Override public String get(HttpUrl url) { String fragment = url.fragment(); return fragment.substring(1, fragment.length() - 1); diff --git a/okhttp-tests/src/test/java/okhttp3/WebPlatformUrlTest.java b/okhttp-tests/src/test/java/okhttp3/WebPlatformUrlTest.java index a6205e9f8..a15c57ea3 100644 --- a/okhttp-tests/src/test/java/okhttp3/WebPlatformUrlTest.java +++ b/okhttp-tests/src/test/java/okhttp3/WebPlatformUrlTest.java @@ -15,10 +15,10 @@ */ package okhttp3; -import okhttp3.internal.Util; import java.io.IOException; import java.util.ArrayList; import java.util.List; +import okhttp3.internal.Util; import okio.BufferedSource; import okio.Okio; import org.junit.Test; @@ -38,7 +38,7 @@ public final class WebPlatformUrlTest { try { List result = new ArrayList<>(); for (WebPlatformUrlTestData urlTestData : loadTests()) { - result.add(new Object[] { urlTestData }); + result.add(new Object[] {urlTestData}); } return result; } catch (IOException e) { diff --git a/okhttp-tests/src/test/java/okhttp3/internal/ConnectionSpecSelectorTest.java b/okhttp-tests/src/test/java/okhttp3/internal/ConnectionSpecSelectorTest.java index e01ffdb8d..b6aa5344c 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/ConnectionSpecSelectorTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/ConnectionSpecSelectorTest.java @@ -15,8 +15,6 @@ */ package okhttp3.internal; -import okhttp3.ConnectionSpec; -import okhttp3.TlsVersion; import java.io.IOException; import java.security.cert.CertificateException; import java.util.Arrays; @@ -25,6 +23,8 @@ import java.util.Set; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSocket; +import okhttp3.ConnectionSpec; +import okhttp3.TlsVersion; import org.junit.Test; import static org.junit.Assert.assertEquals; @@ -91,7 +91,7 @@ public class ConnectionSpecSelectorTest { ConnectionSpecSelector connectionSpecSelector = createConnectionSpecSelector( ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS, sslV3); - TlsVersion[] enabledSocketTlsVersions = { TlsVersion.TLS_1_1, TlsVersion.TLS_1_0 }; + TlsVersion[] enabledSocketTlsVersions = {TlsVersion.TLS_1_1, TlsVersion.TLS_1_0}; SSLSocket socket = createSocketWithEnabledProtocols(enabledSocketTlsVersions); // MODERN_TLS is used here. diff --git a/okhttp-tests/src/test/java/okhttp3/internal/DiskLruCacheTest.java b/okhttp-tests/src/test/java/okhttp3/internal/DiskLruCacheTest.java index 1895bb38f..955214068 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/DiskLruCacheTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/DiskLruCacheTest.java @@ -15,7 +15,6 @@ */ package okhttp3.internal; -import okhttp3.internal.io.FileSystem; import java.io.File; import java.io.IOException; import java.util.ArrayDeque; @@ -26,6 +25,7 @@ import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.concurrent.Executor; +import okhttp3.internal.io.FileSystem; import okio.BufferedSink; import okio.BufferedSource; import okio.Okio; @@ -282,8 +282,8 @@ public final class DiskLruCacheTest { } /** - * Each read sees a snapshot of the file at the time read was called. - * This means that two reads of the same key can see different data. + * Each read sees a snapshot of the file at the time read was called. This means that two reads of + * the same key can see different data. */ @Test public void readAndWriteOverlapsMaintainConsistency() throws Exception { DiskLruCache.Editor v1Creator = cache.edit("k1"); @@ -859,9 +859,8 @@ public final class DiskLruCacheTest { } /** - * We had a long-lived bug where {@link DiskLruCache#trimToSize} could - * infinite loop if entries being edited required deletion for the operation - * to complete. + * We had a long-lived bug where {@link DiskLruCache#trimToSize} could infinite loop if entries + * being edited required deletion for the operation to complete. */ @Test public void trimToSizeWithActiveEdit() throws Exception { set("a", "a1234", "a1234"); @@ -1275,7 +1274,8 @@ public final class DiskLruCacheTest { editor.commit(); } - public static void setString(DiskLruCache.Editor editor, int index, String value) throws IOException { + public static void setString(DiskLruCache.Editor editor, int index, String value) + throws IOException { BufferedSink writer = Okio.buffer(editor.newSink(index)); writer.writeUtf8(value); writer.close(); diff --git a/okhttp-tests/src/test/java/okhttp3/internal/DoubleInetAddressDns.java b/okhttp-tests/src/test/java/okhttp3/internal/DoubleInetAddressDns.java index 929eccffc..7811ff5d7 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/DoubleInetAddressDns.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/DoubleInetAddressDns.java @@ -15,11 +15,11 @@ */ package okhttp3.internal; -import okhttp3.Dns; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.List; +import okhttp3.Dns; /** * A network that always resolves two IP addresses per host. Use this when testing route selection diff --git a/okhttp-tests/src/test/java/okhttp3/internal/FaultyFileSystem.java b/okhttp-tests/src/test/java/okhttp3/internal/FaultyFileSystem.java index 4eb260bdb..22b175822 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/FaultyFileSystem.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/FaultyFileSystem.java @@ -15,12 +15,12 @@ */ package okhttp3.internal; -import okhttp3.internal.io.FileSystem; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.LinkedHashSet; import java.util.Set; +import okhttp3.internal.io.FileSystem; import okio.Buffer; import okio.ForwardingSink; import okio.Sink; diff --git a/okhttp-tests/src/test/java/okhttp3/internal/OptionalMethodTest.java b/okhttp-tests/src/test/java/okhttp3/internal/OptionalMethodTest.java index aa4a0a4cc..08e025c5d 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/OptionalMethodTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/OptionalMethodTest.java @@ -17,10 +17,9 @@ package okhttp3.internal; -import org.junit.Test; - import java.io.IOException; import java.lang.reflect.InvocationTargetException; +import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -38,7 +37,8 @@ public class OptionalMethodTest { return "string"; } - public void voidMethod() {} + public void voidMethod() { + } } @SuppressWarnings("unused") @@ -70,7 +70,8 @@ public class OptionalMethodTest { throw new NumberFormatException(); } - protected void nonPublic() {} + protected void nonPublic() { + } } private final static OptionalMethod STRING_METHOD_RETURNS_ANY = @@ -194,8 +195,10 @@ public class OptionalMethodTest { assertIllegalArgumentExceptionOnInvoke(METHOD_WITH_ARGS_CORRECT_PARAMS, subClass1); // no args assertIllegalArgumentExceptionOnInvoke(METHOD_WITH_ARGS_CORRECT_PARAMS, subClass1, 123); assertIllegalArgumentExceptionOnInvoke(METHOD_WITH_ARGS_CORRECT_PARAMS, subClass1, true); - assertIllegalArgumentExceptionOnInvoke(METHOD_WITH_ARGS_CORRECT_PARAMS, subClass1, new Object()); - assertIllegalArgumentExceptionOnInvoke(METHOD_WITH_ARGS_CORRECT_PARAMS, subClass1, "one", "two"); + assertIllegalArgumentExceptionOnInvoke(METHOD_WITH_ARGS_CORRECT_PARAMS, subClass1, + new Object()); + assertIllegalArgumentExceptionOnInvoke(METHOD_WITH_ARGS_CORRECT_PARAMS, subClass1, "one", + "two"); } @Test @@ -268,11 +271,15 @@ public class OptionalMethodTest { @Test public void invokeOptionalBadArgs() throws Exception { SubClass1 subClass1 = new SubClass1(); - assertIllegalArgumentExceptionOnInvokeOptional(METHOD_WITH_ARGS_CORRECT_PARAMS, subClass1); // no args + assertIllegalArgumentExceptionOnInvokeOptional(METHOD_WITH_ARGS_CORRECT_PARAMS, + subClass1); // no args assertIllegalArgumentExceptionOnInvokeOptional(METHOD_WITH_ARGS_CORRECT_PARAMS, subClass1, 123); - assertIllegalArgumentExceptionOnInvokeOptional(METHOD_WITH_ARGS_CORRECT_PARAMS, subClass1, true); - assertIllegalArgumentExceptionOnInvokeOptional(METHOD_WITH_ARGS_CORRECT_PARAMS, subClass1, new Object()); - assertIllegalArgumentExceptionOnInvokeOptional(METHOD_WITH_ARGS_CORRECT_PARAMS, subClass1, "one", "two"); + assertIllegalArgumentExceptionOnInvokeOptional(METHOD_WITH_ARGS_CORRECT_PARAMS, subClass1, + true); + assertIllegalArgumentExceptionOnInvokeOptional(METHOD_WITH_ARGS_CORRECT_PARAMS, subClass1, + new Object()); + assertIllegalArgumentExceptionOnInvokeOptional(METHOD_WITH_ARGS_CORRECT_PARAMS, subClass1, + "one", "two"); } @Test diff --git a/okhttp-tests/src/test/java/okhttp3/internal/SingleInetAddressDns.java b/okhttp-tests/src/test/java/okhttp3/internal/SingleInetAddressDns.java index 225fee9e6..03e8ce08e 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/SingleInetAddressDns.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/SingleInetAddressDns.java @@ -15,16 +15,15 @@ */ package okhttp3.internal; -import okhttp3.Dns; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Collections; import java.util.List; +import okhttp3.Dns; /** - * A network that resolves only one IP address per host. Use this when testing - * route selection fallbacks to prevent the host machine's various IP addresses - * from interfering. + * A network that resolves only one IP address per host. Use this when testing route selection + * fallbacks to prevent the host machine's various IP addresses from interfering. */ public class SingleInetAddressDns implements Dns { @Override public List lookup(String hostname) throws UnknownHostException { diff --git a/okhttp-tests/src/test/java/okhttp3/internal/framed/HpackTest.java b/okhttp-tests/src/test/java/okhttp3/internal/framed/HpackTest.java index 70c10ec25..068ab647e 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/framed/HpackTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/framed/HpackTest.java @@ -41,8 +41,8 @@ public class HpackTest { } /** - * Variable-length quantity special cases strings which are longer than 127 - * bytes. Values such as cookies can be 4KiB, and should be possible to send. + * Variable-length quantity special cases strings which are longer than 127 bytes. Values such as + * cookies can be 4KiB, and should be possible to send. * *

http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-12#section-5.2 */ @@ -61,8 +61,8 @@ public class HpackTest { } /** - * HPACK has a max header table size, which can be smaller than the max header message. - * Ensure the larger header content is not lost. + * HPACK has a max header table size, which can be smaller than the max header message. Ensure the + * larger header content is not lost. */ @Test public void tooLargeToHPackIsStillEmitted() throws IOException { bytesIn.writeByte(0x00); // Literal indexed diff --git a/okhttp-tests/src/test/java/okhttp3/internal/framed/Http2Test.java b/okhttp-tests/src/test/java/okhttp3/internal/framed/Http2Test.java index 7d1cc0c1a..bbe771ff8 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/framed/Http2Test.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/framed/Http2Test.java @@ -15,17 +15,16 @@ */ package okhttp3.internal.framed; -import okhttp3.internal.Util; import java.io.IOException; import java.util.Arrays; import java.util.List; +import okhttp3.internal.Util; import okio.Buffer; import okio.BufferedSink; import okio.BufferedSource; import okio.ByteString; import okio.GzipSink; import okio.Okio; -import org.junit.Assert; import org.junit.Test; import static okhttp3.TestUtil.headerEntries; @@ -730,7 +729,7 @@ public class Http2Test { private static List

largeHeaders() { String[] nameValues = new String[32]; char[] chars = new char[512]; - for (int i = 0; i < nameValues.length;) { + for (int i = 0; i < nameValues.length; ) { Arrays.fill(chars, (char) i); nameValues[i++] = nameValues[i++] = String.valueOf(chars); } @@ -739,7 +738,7 @@ public class Http2Test { private static void writeMedium(BufferedSink sink, int i) throws IOException { sink.writeByte((i >>> 16) & 0xff); - sink.writeByte((i >>> 8) & 0xff); - sink.writeByte( i & 0xff); + sink.writeByte((i >>> 8) & 0xff); + sink.writeByte(i & 0xff); } } diff --git a/okhttp-tests/src/test/java/okhttp3/internal/framed/HttpOverHttp2Test.java b/okhttp-tests/src/test/java/okhttp3/internal/framed/HttpOverHttp2Test.java index ac330e411..952ac2ab0 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/framed/HttpOverHttp2Test.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/framed/HttpOverHttp2Test.java @@ -15,12 +15,12 @@ */ package okhttp3.internal.framed; +import java.net.HttpURLConnection; import okhttp3.Headers; import okhttp3.Protocol; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.PushPromise; import okhttp3.mockwebserver.RecordedRequest; -import java.net.HttpURLConnection; import org.junit.Test; import static org.junit.Assert.assertEquals; diff --git a/okhttp-tests/src/test/java/okhttp3/internal/framed/HttpOverSpdyTest.java b/okhttp-tests/src/test/java/okhttp3/internal/framed/HttpOverSpdyTest.java index fac19015b..c4f59b1e2 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/framed/HttpOverSpdyTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/framed/HttpOverSpdyTest.java @@ -15,20 +15,6 @@ */ package okhttp3.internal.framed; -import okhttp3.Cache; -import okhttp3.ConnectionPool; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.OkUrlFactory; -import okhttp3.Protocol; -import okhttp3.internal.RecordingAuthenticator; -import okhttp3.internal.SslContextBuilder; -import okhttp3.internal.Util; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import okhttp3.mockwebserver.RecordedRequest; -import okhttp3.mockwebserver.SocketPolicy; -import okhttp3.testing.RecordingHostnameVerifier; import java.io.IOException; import java.io.InputStream; import java.net.Authenticator; @@ -45,6 +31,20 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; +import okhttp3.Cache; +import okhttp3.ConnectionPool; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.OkUrlFactory; +import okhttp3.Protocol; +import okhttp3.internal.RecordingAuthenticator; +import okhttp3.internal.SslContextBuilder; +import okhttp3.internal.Util; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import okhttp3.mockwebserver.RecordedRequest; +import okhttp3.mockwebserver.SocketPolicy; +import okhttp3.testing.RecordingHostnameVerifier; import okio.Buffer; import okio.BufferedSink; import okio.GzipSink; @@ -77,7 +77,7 @@ public abstract class HttpOverSpdyTest { protected HttpURLConnection connection; protected Cache cache; - protected HttpOverSpdyTest(Protocol protocol){ + protected HttpOverSpdyTest(Protocol protocol) { this.protocol = protocol; } @@ -266,16 +266,15 @@ public abstract class HttpOverSpdyTest { } /** - * Test to ensure we don't throw a read timeout on responses that are - * progressing. For this case, we take a 4KiB body and throttle it to - * 1KiB/second. We set the read timeout to two seconds. If our - * implementation is acting correctly, it will not throw, as it is - * progressing. + * Test to ensure we don't throw a read timeout on responses that are progressing. For this + * case, we take a 4KiB body and throttle it to 1KiB/second. We set the read timeout to two + * seconds. If our implementation is acting correctly, it will not throw, as it is progressing. */ @Test public void readTimeoutMoreGranularThanBodySize() throws Exception { char[] body = new char[4096]; // 4KiB to read Arrays.fill(body, 'y'); - server.enqueue(new MockResponse().setBody(new String(body)).throttleBody(1024, 1, SECONDS)); // slow connection 1KiB/second + server.enqueue(new MockResponse().setBody(new String(body)) + .throttleBody(1024, 1, SECONDS)); // slow connection 1KiB/second connection = client.open(server.url("/").url()); connection.setReadTimeout(2000); // 2 seconds to read something. @@ -283,11 +282,10 @@ public abstract class HttpOverSpdyTest { } /** - * Test to ensure we throw a read timeout on responses that are progressing - * too slowly. For this case, we take a 2KiB body and throttle it to - * 1KiB/second. We set the read timeout to half a second. If our - * implementation is acting correctly, it will throw, as a byte doesn't - * arrive in time. + * Test to ensure we throw a read timeout on responses that are progressing too slowly. For this + * case, we take a 2KiB body and throttle it to 1KiB/second. We set the read timeout to half a + * second. If our implementation is acting correctly, it will throw, as a byte doesn't arrive in + * time. */ @Test public void readTimeoutOnSlowConnection() throws Exception { char[] body = new char[2048]; // 2KiB to read @@ -442,6 +440,7 @@ public abstract class HttpOverSpdyTest { class SpdyRequest implements Runnable { String path; CountDownLatch countDownLatch; + public SpdyRequest(String path, CountDownLatch countDownLatch) { this.path = path; this.countDownLatch = countDownLatch; diff --git a/okhttp-tests/src/test/java/okhttp3/internal/framed/MockSpdyPeer.java b/okhttp-tests/src/test/java/okhttp3/internal/framed/MockSpdyPeer.java index 1a5b6d811..edc8f41c3 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/framed/MockSpdyPeer.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/framed/MockSpdyPeer.java @@ -83,8 +83,8 @@ public final class MockSpdyPeer implements Closeable { } /** - * Sends a manually-constructed frame. This is useful to test frames that - * won't be generated naturally. + * Sends a manually-constructed frame. This is useful to test frames that won't be generated + * naturally. */ public void sendFrame(byte[] frame) throws IOException { outFrames.add(new OutFrame(frameCount++, bytesOut.size(), false)); @@ -92,9 +92,9 @@ public final class MockSpdyPeer implements Closeable { } /** - * Shortens the last frame from its original length to {@code length}. This - * will cause the peer to close the socket as soon as this frame has been - * written; otherwise the peer stays open until explicitly closed. + * Shortens the last frame from its original length to {@code length}. This will cause the peer to + * close the socket as soon as this frame has been written; otherwise the peer stays open until + * explicitly closed. */ public FrameWriter truncateLastFrame(int length) { OutFrame lastFrame = outFrames.remove(outFrames.size() - 1); diff --git a/okhttp-tests/src/test/java/okhttp3/internal/framed/Spdy3ConnectionTest.java b/okhttp-tests/src/test/java/okhttp3/internal/framed/Spdy3ConnectionTest.java index 0b2876cfb..58cdc04bd 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/framed/Spdy3ConnectionTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/framed/Spdy3ConnectionTest.java @@ -15,7 +15,6 @@ */ package okhttp3.internal.framed; -import okhttp3.internal.Util; import java.io.IOException; import java.io.InterruptedIOException; import java.net.Socket; @@ -26,6 +25,7 @@ import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import okhttp3.internal.Util; import okio.AsyncTimeout; import okio.Buffer; import okio.BufferedSink; @@ -274,6 +274,7 @@ public final class Spdy3ConnectionTest { @Override public void onStream(FramedStream stream) throws IOException { throw new AssertionError(); } + @Override public void onSettings(FramedConnection connection) { maxConcurrentStreams.set(connection.maxConcurrentStreams()); } @@ -475,8 +476,7 @@ public final class Spdy3ConnectionTest { } /** - * Test that the client sends a RST_STREAM if doing so won't disrupt the - * output stream. + * Test that the client sends a RST_STREAM if doing so won't disrupt the output stream. */ @Test public void clientClosesClientInputStream() throws Exception { // write the mocking script @@ -517,8 +517,7 @@ public final class Spdy3ConnectionTest { } /** - * Test that the client doesn't send a RST_STREAM if doing so will disrupt - * the output stream. + * Test that the client doesn't send a RST_STREAM if doing so will disrupt the output stream. */ @Test public void clientClosesClientInputStreamIfOutputStreamIsClosed() throws Exception { // write the mocking script diff --git a/okhttp-tests/src/test/java/okhttp3/internal/framed/Spdy3Test.java b/okhttp-tests/src/test/java/okhttp3/internal/framed/Spdy3Test.java index c026b84ba..953009ffc 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/framed/Spdy3Test.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/framed/Spdy3Test.java @@ -15,8 +15,8 @@ */ package okhttp3.internal.framed; -import okhttp3.internal.Util; import java.io.IOException; +import okhttp3.internal.Util; import okio.Buffer; import okio.ByteString; import org.junit.Test; diff --git a/okhttp-tests/src/test/java/okhttp3/internal/http/CookiesTest.java b/okhttp-tests/src/test/java/okhttp3/internal/http/CookiesTest.java index 8fe535cd8..f22e2698a 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/http/CookiesTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/http/CookiesTest.java @@ -16,11 +16,6 @@ package okhttp3.internal.http; -import okhttp3.OkHttpClient; -import okhttp3.OkUrlFactory; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import okhttp3.mockwebserver.RecordedRequest; import java.io.IOException; import java.net.CookieHandler; import java.net.CookieManager; @@ -33,6 +28,11 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import okhttp3.OkHttpClient; +import okhttp3.OkUrlFactory; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import okhttp3.mockwebserver.RecordedRequest; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -206,12 +206,12 @@ public class CookiesTest { RecordedRequest request = server.takeRequest(); assertEquals("$Version=\"1\"; " - + "a=\"android\";$Path=\"/\";$Domain=\"" - + server.getCookieDomain() - + "\"; " - + "b=\"banana\";$Path=\"/\";$Domain=\"" - + server.getCookieDomain() - + "\"", request.getHeader("Cookie")); + + "a=\"android\";$Path=\"/\";$Domain=\"" + + server.getCookieDomain() + + "\"; " + + "b=\"banana\";$Path=\"/\";$Domain=\"" + + server.getCookieDomain() + + "\"", request.getHeader("Cookie")); } @Test public void testRedirectsDoNotIncludeTooManyCookies() throws Exception { @@ -238,11 +238,11 @@ public class CookiesTest { RecordedRequest request = redirectSource.takeRequest(); assertEquals("$Version=\"1\"; " - + "c=\"cookie\";$Path=\"/\";$Domain=\"" - + redirectSource.getCookieDomain() - + "\";$Port=\"" - + portList - + "\"", request.getHeader("Cookie")); + + "c=\"cookie\";$Path=\"/\";$Domain=\"" + + redirectSource.getCookieDomain() + + "\";$Port=\"" + + portList + + "\"", request.getHeader("Cookie")); for (String header : redirectTarget.takeRequest().getHeaders().names()) { if (header.startsWith("Cookie")) { @@ -252,10 +252,9 @@ public class CookiesTest { } /** - * Test which headers show up where. The cookie manager should be notified - * of both user-specified and derived headers like {@code Host}. Headers - * named {@code Cookie} or {@code Cookie2} that are returned by the cookie - * manager should show up in the request and in {@code + * Test which headers show up where. The cookie manager should be notified of both user-specified + * and derived headers like {@code Host}. Headers named {@code Cookie} or {@code Cookie2} that are + * returned by the cookie manager should show up in the request and in {@code * getRequestProperties}. */ @Test public void testHeadersSentToCookieHandler() throws IOException, InterruptedException { @@ -324,7 +323,7 @@ public class CookiesTest { } }); MockWebServer server = new MockWebServer(); - server. enqueue(new MockResponse()); + server.enqueue(new MockResponse()); server.start(); get(server, "/"); @@ -350,11 +349,10 @@ public class CookiesTest { } } - private Map> get(MockWebServer server, String path) throws Exception { + private Map> get(MockWebServer server, String path) throws Exception { URLConnection connection = new OkUrlFactory(client).open(server.url(path).url()); Map> headers = connection.getHeaderFields(); connection.getInputStream().close(); return headers; } - } diff --git a/okhttp-tests/src/test/java/okhttp3/internal/http/DisconnectTest.java b/okhttp-tests/src/test/java/okhttp3/internal/http/DisconnectTest.java index 47b604df7..63089b495 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/http/DisconnectTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/http/DisconnectTest.java @@ -15,12 +15,6 @@ */ package okhttp3.internal.http; -import okhttp3.DelegatingServerSocketFactory; -import okhttp3.DelegatingSocketFactory; -import okhttp3.OkHttpClient; -import okhttp3.OkUrlFactory; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -28,14 +22,18 @@ import java.net.HttpURLConnection; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.TimeUnit; - +import javax.net.ServerSocketFactory; +import javax.net.SocketFactory; +import okhttp3.DelegatingServerSocketFactory; +import okhttp3.DelegatingSocketFactory; +import okhttp3.OkHttpClient; +import okhttp3.OkUrlFactory; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; import okio.Buffer; import org.junit.Before; import org.junit.Test; -import javax.net.ServerSocketFactory; -import javax.net.SocketFactory; - import static org.junit.Assert.fail; public final class DisconnectTest { diff --git a/okhttp-tests/src/test/java/okhttp3/internal/http/ExternalHttp2Example.java b/okhttp-tests/src/test/java/okhttp3/internal/http/ExternalHttp2Example.java index bb6a346b6..cb0da6d57 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/http/ExternalHttp2Example.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/http/ExternalHttp2Example.java @@ -16,10 +16,6 @@ package okhttp3.internal.http; -import okhttp3.OkHttpClient; -import okhttp3.OkUrlFactory; -import okhttp3.Protocol; -import okhttp3.internal.Util; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; @@ -27,6 +23,10 @@ import java.util.List; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; +import okhttp3.OkHttpClient; +import okhttp3.OkUrlFactory; +import okhttp3.Protocol; +import okhttp3.internal.Util; import static okhttp3.internal.http.OkHeaders.SELECTED_PROTOCOL; diff --git a/okhttp-tests/src/test/java/okhttp3/internal/http/ExternalSpdyExample.java b/okhttp-tests/src/test/java/okhttp3/internal/http/ExternalSpdyExample.java index 57cd3a3ab..dffcb31ca 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/http/ExternalSpdyExample.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/http/ExternalSpdyExample.java @@ -16,10 +16,6 @@ package okhttp3.internal.http; -import okhttp3.OkHttpClient; -import okhttp3.OkUrlFactory; -import okhttp3.Protocol; -import okhttp3.internal.Util; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; @@ -27,6 +23,10 @@ import java.util.List; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; +import okhttp3.OkHttpClient; +import okhttp3.OkUrlFactory; +import okhttp3.Protocol; +import okhttp3.internal.Util; import static okhttp3.internal.http.OkHeaders.SELECTED_PROTOCOL; diff --git a/okhttp-tests/src/test/java/okhttp3/internal/http/FakeDns.java b/okhttp-tests/src/test/java/okhttp3/internal/http/FakeDns.java index a8e5a8687..d013bea2d 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/http/FakeDns.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/http/FakeDns.java @@ -15,13 +15,13 @@ */ package okhttp3.internal.http; -import okhttp3.Dns; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; +import okhttp3.Dns; import static org.junit.Assert.assertEquals; diff --git a/okhttp-tests/src/test/java/okhttp3/internal/http/HeadersTest.java b/okhttp-tests/src/test/java/okhttp3/internal/http/HeadersTest.java index 098d9df05..18e41d9e9 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/http/HeadersTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/http/HeadersTest.java @@ -15,17 +15,17 @@ */ package okhttp3.internal.http; -import okhttp3.Headers; -import okhttp3.Protocol; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.internal.framed.Header; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import okhttp3.Headers; +import okhttp3.Protocol; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.internal.framed.Header; import org.junit.Assert; import org.junit.Test; diff --git a/okhttp-tests/src/test/java/okhttp3/internal/http/HttpDateTest.java b/okhttp-tests/src/test/java/okhttp3/internal/http/HttpDateTest.java index 2098d6810..0a22eb0f8 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/http/HttpDateTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/http/HttpDateTest.java @@ -15,13 +15,12 @@ */ package okhttp3.internal.http; +import java.util.Date; +import java.util.TimeZone; import org.junit.After; import org.junit.Before; import org.junit.Test; -import java.util.Date; -import java.util.TimeZone; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; diff --git a/okhttp-tests/src/test/java/okhttp3/internal/http/RouteExceptionTest.java b/okhttp-tests/src/test/java/okhttp3/internal/http/RouteExceptionTest.java index 7ae8a9666..1a0c2d8f0 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/http/RouteExceptionTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/http/RouteExceptionTest.java @@ -15,9 +15,8 @@ */ package okhttp3.internal.http; -import org.junit.Test; - import java.io.IOException; +import org.junit.Test; import static org.junit.Assert.assertSame; diff --git a/okhttp-tests/src/test/java/okhttp3/internal/http/RouteSelectorTest.java b/okhttp-tests/src/test/java/okhttp3/internal/http/RouteSelectorTest.java index ef6ca0eb4..05b57fbaa 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/http/RouteSelectorTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/http/RouteSelectorTest.java @@ -16,20 +16,12 @@ package okhttp3.internal.http; import java.io.IOException; -import java.net.ProxySelector; -import java.net.SocketAddress; -import java.net.URI; -import okhttp3.Address; -import okhttp3.Authenticator; -import okhttp3.ConnectionSpec; -import okhttp3.Protocol; -import okhttp3.Route; -import okhttp3.internal.RouteDatabase; -import okhttp3.internal.SslContextBuilder; -import okhttp3.internal.Util; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Proxy; +import java.net.ProxySelector; +import java.net.SocketAddress; +import java.net.URI; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; @@ -40,6 +32,14 @@ import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; +import okhttp3.Address; +import okhttp3.Authenticator; +import okhttp3.ConnectionSpec; +import okhttp3.Protocol; +import okhttp3.Route; +import okhttp3.internal.RouteDatabase; +import okhttp3.internal.SslContextBuilder; +import okhttp3.internal.Util; import org.junit.Before; import org.junit.Test; @@ -335,10 +335,10 @@ public final class RouteSelectorTest { socketAddress = new InetSocketAddress(InetAddress.getByName("localhost"), 1234); assertEquals("127.0.0.1", RouteSelector.getHostString(socketAddress)); socketAddress = new InetSocketAddress( - InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }), 1234); + InetAddress.getByAddress(new byte[] {127, 0, 0, 1}), 1234); assertEquals("127.0.0.1", RouteSelector.getHostString(socketAddress)); socketAddress = new InetSocketAddress( - InetAddress.getByAddress("foobar", new byte[] { 127, 0, 0, 1 }), 1234); + InetAddress.getByAddress("foobar", new byte[] {127, 0, 0, 1}), 1234); assertEquals("127.0.0.1", RouteSelector.getHostString(socketAddress)); } @@ -366,7 +366,7 @@ public final class RouteSelectorTest { List result = new ArrayList<>(); for (int i = 0; i < count; i++) { result.add(InetAddress.getByAddress( - new byte[] { (byte) prefix, (byte) 0, (byte) 0, (byte) i })); + new byte[] {(byte) prefix, (byte) 0, (byte) 0, (byte) i})); } return result; } catch (UnknownHostException e) { diff --git a/okhttp-tests/src/test/java/okhttp3/internal/http/StatusLineTest.java b/okhttp-tests/src/test/java/okhttp3/internal/http/StatusLineTest.java index be97c012e..6eb1aa8b1 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/http/StatusLineTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/http/StatusLineTest.java @@ -15,9 +15,9 @@ */ package okhttp3.internal.http; -import okhttp3.Protocol; import java.io.IOException; import java.net.ProtocolException; +import okhttp3.Protocol; import org.junit.Test; import static org.junit.Assert.assertEquals; @@ -44,9 +44,8 @@ public final class StatusLineTest { } /** - * This is not defined in the protocol but some servers won't add the leading - * empty space when the message is empty. - * http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1 + * This is not defined in the protocol but some servers won't add the leading empty space when the + * message is empty. http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1 */ @Test public void emptyMessageAndNoLeadingSpace() throws IOException { int version = 1; diff --git a/okhttp-tests/src/test/java/okhttp3/internal/http/ThreadInterruptTest.java b/okhttp-tests/src/test/java/okhttp3/internal/http/ThreadInterruptTest.java index 4e304781e..64d13960d 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/http/ThreadInterruptTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/http/ThreadInterruptTest.java @@ -15,13 +15,6 @@ */ package okhttp3.internal.http; -import okhttp3.DelegatingServerSocketFactory; -import okhttp3.DelegatingSocketFactory; -import okhttp3.OkHttpClient; -import okhttp3.OkUrlFactory; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; - import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; @@ -30,14 +23,18 @@ import java.net.HttpURLConnection; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.TimeUnit; - +import javax.net.ServerSocketFactory; +import javax.net.SocketFactory; +import okhttp3.DelegatingServerSocketFactory; +import okhttp3.DelegatingSocketFactory; +import okhttp3.OkHttpClient; +import okhttp3.OkUrlFactory; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; import okio.Buffer; import org.junit.Before; import org.junit.Test; -import javax.net.ServerSocketFactory; -import javax.net.SocketFactory; - import static org.junit.Assert.fail; public final class ThreadInterruptTest { diff --git a/okhttp-tests/src/test/java/okhttp3/internal/tls/HostnameVerifierTest.java b/okhttp-tests/src/test/java/okhttp3/internal/tls/HostnameVerifierTest.java index da6056aa5..113a71a17 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/tls/HostnameVerifierTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/tls/HostnameVerifierTest.java @@ -17,13 +17,13 @@ package okhttp3.internal.tls; -import okhttp3.internal.Util; import java.io.ByteArrayInputStream; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSession; import javax.security.auth.x500.X500Principal; +import okhttp3.internal.Util; import org.junit.Ignore; import org.junit.Test; @@ -32,8 +32,8 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** - * Tests for our hostname verifier. Most of these tests are from AOSP, which - * itself includes tests from the Apache HTTP Client test suite. + * Tests for our hostname verifier. Most of these tests are from AOSP, which itself includes tests + * from the Apache HTTP Client test suite. */ public final class HostnameVerifierTest { private HostnameVerifier verifier = OkHostnameVerifier.INSTANCE; @@ -144,9 +144,9 @@ public final class HostnameVerifierTest { } /** - * Ignored due to incompatibilities between Android and Java on how non-ASCII - * subject alt names are parsed. Android fails to parse these, which means we - * fall back to the CN. The RI does parse them, so the CN is unused. + * Ignored due to incompatibilities between Android and Java on how non-ASCII subject alt names + * are parsed. Android fails to parse these, which means we fall back to the CN. The RI does parse + * them, so the CN is unused. */ @Test @Ignore public void verifyNonAsciiSubjectAlt() throws Exception { // CN=foo.com, subjectAlt=bar.com, subjectAlt=花子.co.jp @@ -329,9 +329,9 @@ public final class HostnameVerifierTest { } /** - * Ignored due to incompatibilities between Android and Java on how non-ASCII - * subject alt names are parsed. Android fails to parse these, which means we - * fall back to the CN. The RI does parse them, so the CN is unused. + * Ignored due to incompatibilities between Android and Java on how non-ASCII subject alt names + * are parsed. Android fails to parse these, which means we fall back to the CN. The RI does parse + * them, so the CN is unused. */ @Test @Ignore public void testWilcardNonAsciiSubjectAlt() throws Exception { // CN=*.foo.com, subjectAlt=*.bar.com, subjectAlt=*.花子.co.jp @@ -432,10 +432,9 @@ public final class HostnameVerifierTest { } /** - * Earlier implementations of Android's hostname verifier required that - * wildcard names wouldn't match "*.com" or similar. This was a nonstandard - * check that we've since dropped. It is the CA's responsibility to not hand - * out certificates that match so broadly. + * Earlier implementations of Android's hostname verifier required that wildcard names wouldn't + * match "*.com" or similar. This was a nonstandard check that we've since dropped. It is the CA's + * responsibility to not hand out certificates that match so broadly. */ @Test public void wildcardsDoesNotNeedTwoDots() throws Exception { // openssl req -x509 -nodes -days 36500 -subj '/CN=*.com' -newkey rsa:512 -out cert.pem diff --git a/okhttp-urlconnection/pom.xml b/okhttp-urlconnection/pom.xml index a700dffd9..9ac03024b 100644 --- a/okhttp-urlconnection/pom.xml +++ b/okhttp-urlconnection/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 diff --git a/okhttp-urlconnection/src/main/java/okhttp3/OkUrlFactory.java b/okhttp-urlconnection/src/main/java/okhttp3/OkUrlFactory.java index 5a11ba972..b6fdd7b0c 100644 --- a/okhttp-urlconnection/src/main/java/okhttp3/OkUrlFactory.java +++ b/okhttp-urlconnection/src/main/java/okhttp3/OkUrlFactory.java @@ -15,19 +15,19 @@ */ package okhttp3; -import okhttp3.internal.huc.HttpURLConnectionImpl; -import okhttp3.internal.huc.HttpsURLConnectionImpl; import java.net.HttpURLConnection; import java.net.Proxy; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; import java.net.URLStreamHandlerFactory; +import okhttp3.internal.huc.HttpURLConnectionImpl; +import okhttp3.internal.huc.HttpsURLConnectionImpl; /** * @deprecated OkHttp will be dropping its ability to be used with {@link HttpURLConnection} in an - * upcoming release. Applications that need this should either downgrade to the system's - * built-in {@link HttpURLConnection} or upgrade to OkHttp's Request/Response API. + * upcoming release. Applications that need this should either downgrade to the system's built-in + * {@link HttpURLConnection} or upgrade to OkHttp's Request/Response API. */ public final class OkUrlFactory implements URLStreamHandlerFactory, Cloneable { private final OkHttpClient client; @@ -41,8 +41,8 @@ public final class OkUrlFactory implements URLStreamHandlerFactory, Cloneable { } /** - * Returns a copy of this stream handler factory that includes a shallow copy - * of the internal {@linkplain OkHttpClient HTTP client}. + * Returns a copy of this stream handler factory that includes a shallow copy of the internal + * {@linkplain OkHttpClient HTTP client}. */ @Override public OkUrlFactory clone() { return new OkUrlFactory(client.clone()); diff --git a/okhttp-urlconnection/src/main/java/okhttp3/internal/huc/DelegatingHttpsURLConnection.java b/okhttp-urlconnection/src/main/java/okhttp3/internal/huc/DelegatingHttpsURLConnection.java index c03eded30..86f4aa780 100644 --- a/okhttp-urlconnection/src/main/java/okhttp3/internal/huc/DelegatingHttpsURLConnection.java +++ b/okhttp-urlconnection/src/main/java/okhttp3/internal/huc/DelegatingHttpsURLConnection.java @@ -16,7 +16,6 @@ */ package okhttp3.internal.huc; -import okhttp3.Handshake; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -32,10 +31,11 @@ import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSocketFactory; +import okhttp3.Handshake; /** - * Implement an HTTPS connection by delegating to an HTTP connection for - * everything but the HTTPS-specific stuff. + * Implement an HTTPS connection by delegating to an HTTP connection for everything but the + * HTTPS-specific stuff. */ abstract class DelegatingHttpsURLConnection extends HttpsURLConnection { private final HttpURLConnection delegate; diff --git a/okhttp-urlconnection/src/main/java/okhttp3/internal/huc/HttpURLConnectionImpl.java b/okhttp-urlconnection/src/main/java/okhttp3/internal/huc/HttpURLConnectionImpl.java index 6e43756a3..05412e8b1 100644 --- a/okhttp-urlconnection/src/main/java/okhttp3/internal/huc/HttpURLConnectionImpl.java +++ b/okhttp-urlconnection/src/main/java/okhttp3/internal/huc/HttpURLConnectionImpl.java @@ -17,29 +17,6 @@ package okhttp3.internal.huc; -import okhttp3.Connection; -import okhttp3.Handshake; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Protocol; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.Route; -import okhttp3.internal.Internal; -import okhttp3.internal.Platform; -import okhttp3.internal.Util; -import okhttp3.internal.Version; -import okhttp3.internal.http.HttpDate; -import okhttp3.internal.http.HttpEngine; -import okhttp3.internal.http.HttpMethod; -import okhttp3.internal.http.OkHeaders; -import okhttp3.internal.http.RequestException; -import okhttp3.internal.http.RetryableSink; -import okhttp3.internal.http.RouteException; -import okhttp3.internal.http.StatusLine; -import okhttp3.internal.http.StreamAllocation; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; @@ -63,20 +40,42 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; +import okhttp3.Connection; +import okhttp3.Handshake; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Protocol; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.Route; +import okhttp3.internal.Internal; +import okhttp3.internal.Platform; +import okhttp3.internal.Util; +import okhttp3.internal.Version; +import okhttp3.internal.http.HttpDate; +import okhttp3.internal.http.HttpEngine; +import okhttp3.internal.http.HttpMethod; +import okhttp3.internal.http.OkHeaders; +import okhttp3.internal.http.RequestException; +import okhttp3.internal.http.RetryableSink; +import okhttp3.internal.http.RouteException; +import okhttp3.internal.http.StatusLine; +import okhttp3.internal.http.StreamAllocation; import okio.BufferedSink; import okio.Sink; /** - * This implementation uses HttpEngine to send requests and receive responses. - * This class may use multiple HttpEngines to follow redirects, authentication - * retries, etc. to retrieve the final response body. + * This implementation uses HttpEngine to send requests and receive responses. This class may use + * multiple HttpEngines to follow redirects, authentication retries, etc. to retrieve the final + * response body. * - *

What does 'connected' mean?

- * This class inherits a {@code connected} field from the superclass. That field - * is not used to indicate whether this URLConnection is - * currently connected. Instead, it indicates whether a connection has ever been - * attempted. Once a connection has been attempted, certain properties (request - * header fields, request method, etc.) are immutable. + *

What does 'connected' mean?

This class inherits a {@code connected} field from the + * superclass. That field is not used to indicate whether this URLConnection is + * currently connected. Instead, it indicates whether a connection has ever been attempted. Once a + * connection has been attempted, certain properties (request header fields, request method, etc.) + * are immutable. */ public class HttpURLConnectionImpl extends HttpURLConnection { private static final Set METHODS = new LinkedHashSet<>( @@ -96,14 +95,14 @@ public class HttpURLConnectionImpl extends HttpURLConnection { private Headers responseHeaders; /** - * The most recently attempted route. This will be null if we haven't sent a - * request yet, or if the response comes from a cache. + * The most recently attempted route. This will be null if we haven't sent a request yet, or if + * the response comes from a cache. */ private Route route; /** - * The most recently received TLS handshake. This will be null if we haven't - * connected yet, or if the most recent connection was HTTP (and not HTTPS). + * The most recently received TLS handshake. This will be null if we haven't connected yet, or if + * the most recent connection was HTTP (and not HTTPS). */ Handshake handshake; @@ -134,8 +133,8 @@ public class HttpURLConnectionImpl extends HttpURLConnection { } /** - * Returns an input stream from the server in the case of error such as the - * requested file (txt, htm, html) is not found on the remote server. + * Returns an input stream from the server in the case of error such as the requested file (txt, + * htm, html) is not found on the remote server. */ @Override public final InputStream getErrorStream() { try { @@ -176,8 +175,8 @@ public class HttpURLConnectionImpl extends HttpURLConnection { } /** - * Returns the value of the field at {@code position}. Returns null if there - * are fewer than {@code position} headers. + * Returns the value of the field at {@code position}. Returns null if there are fewer than {@code + * position} headers. */ @Override public final String getHeaderField(int position) { try { @@ -188,9 +187,8 @@ public class HttpURLConnectionImpl extends HttpURLConnection { } /** - * Returns the value of the field corresponding to the {@code fieldName}, or - * null if there is no such field. If the field has multiple values, the - * last value is returned. + * Returns the value of the field corresponding to the {@code fieldName}, or null if there is no + * such field. If the field has multiple values, the last value is returned. */ @Override public final String getHeaderField(String fieldName) { try { @@ -384,9 +382,8 @@ public class HttpURLConnectionImpl extends HttpURLConnection { } /** - * Aggressively tries to get the final HTTP response, potentially making - * many HTTP requests in the process in order to cope with redirects and - * authentication. + * Aggressively tries to get the final HTTP response, potentially making many HTTP requests in the + * process in order to cope with redirects and authentication. */ private HttpEngine getResponse() throws IOException { initHttpEngine(); @@ -440,9 +437,9 @@ public class HttpURLConnectionImpl extends HttpURLConnection { } /** - * Sends a request and optionally reads a response. Returns true if the - * request was successfully executed, and false if the request can be - * retried. Throws an exception if the request failed permanently. + * Sends a request and optionally reads a response. Returns true if the request was successfully + * executed, and false if the request can be retried. Throws an exception if the request failed + * permanently. */ private boolean execute(boolean readResponse) throws IOException { boolean releaseConnection = true; @@ -503,14 +500,15 @@ public class HttpURLConnectionImpl extends HttpURLConnection { /** * Returns true if either: + * *
    *
  • A specific proxy was explicitly configured for this connection. *
  • The response has already been retrieved, and a proxy was {@link * java.net.ProxySelector selected} in order to get it. *
* - *

Warning: This method may return false before attempting - * to connect and true afterwards. + *

Warning: This method may return false before attempting to connect and true + * afterwards. */ @Override public final boolean usingProxy() { Proxy proxy = route != null diff --git a/okhttp-urlconnection/src/main/java/okhttp3/internal/huc/HttpsURLConnectionImpl.java b/okhttp-urlconnection/src/main/java/okhttp3/internal/huc/HttpsURLConnectionImpl.java index 3b18d3d9d..180e3641b 100644 --- a/okhttp-urlconnection/src/main/java/okhttp3/internal/huc/HttpsURLConnectionImpl.java +++ b/okhttp-urlconnection/src/main/java/okhttp3/internal/huc/HttpsURLConnectionImpl.java @@ -16,11 +16,11 @@ */ package okhttp3.internal.huc; -import okhttp3.Handshake; -import okhttp3.OkHttpClient; import java.net.URL; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSocketFactory; +import okhttp3.Handshake; +import okhttp3.OkHttpClient; public final class HttpsURLConnectionImpl extends DelegatingHttpsURLConnection { private final HttpURLConnectionImpl delegate; diff --git a/okhttp-urlconnection/src/test/java/okhttp3/OkUrlFactoryTest.java b/okhttp-urlconnection/src/test/java/okhttp3/OkUrlFactoryTest.java index 1856c2c1c..df4f6a9fa 100644 --- a/okhttp-urlconnection/src/test/java/okhttp3/OkUrlFactoryTest.java +++ b/okhttp-urlconnection/src/test/java/okhttp3/OkUrlFactoryTest.java @@ -1,9 +1,5 @@ package okhttp3; -import okhttp3.internal.http.OkHeaders; -import okhttp3.internal.io.InMemoryFileSystem; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; import java.io.File; import java.io.IOException; import java.net.HttpURLConnection; @@ -13,6 +9,10 @@ import java.util.Date; import java.util.Locale; import java.util.TimeZone; import java.util.concurrent.TimeUnit; +import okhttp3.internal.http.OkHeaders; +import okhttp3.internal.io.InMemoryFileSystem; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; import okio.BufferedSource; import org.junit.After; import org.junit.Before; @@ -44,8 +44,8 @@ public class OkUrlFactoryTest { } /** - * Response code 407 should only come from proxy servers. Android's client - * throws if it is sent by an origin server. + * Response code 407 should only come from proxy servers. Android's client throws if it is sent by + * an origin server. */ @Test public void originServerSends407() throws Exception { server.enqueue(new MockResponse().setResponseCode(407)); diff --git a/okhttp-urlconnection/src/test/java/okhttp3/UrlConnectionCacheTest.java b/okhttp-urlconnection/src/test/java/okhttp3/UrlConnectionCacheTest.java index 73c25ad49..68715f308 100644 --- a/okhttp-urlconnection/src/test/java/okhttp3/UrlConnectionCacheTest.java +++ b/okhttp-urlconnection/src/test/java/okhttp3/UrlConnectionCacheTest.java @@ -16,13 +16,6 @@ package okhttp3; -import okhttp3.internal.Internal; -import okhttp3.internal.SslContextBuilder; -import okhttp3.internal.Util; -import okhttp3.internal.io.InMemoryFileSystem; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import okhttp3.mockwebserver.RecordedRequest; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; @@ -52,6 +45,13 @@ import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; +import okhttp3.internal.Internal; +import okhttp3.internal.SslContextBuilder; +import okhttp3.internal.Util; +import okhttp3.internal.io.InMemoryFileSystem; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import okhttp3.mockwebserver.RecordedRequest; import okio.Buffer; import okio.BufferedSink; import okio.GzipSink; @@ -109,57 +109,57 @@ public final class UrlConnectionCacheTest { * http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4 */ @Test public void responseCachingByResponseCode() throws Exception { - // Test each documented HTTP/1.1 code, plus the first unused value in each range. - // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html + // Test each documented HTTP/1.1 code, plus the first unused value in each range. + // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html - // We can't test 100 because it's not really a response. - // assertCached(false, 100); - assertCached(false, 101); - assertCached(false, 102); - assertCached(true, 200); - assertCached(false, 201); - assertCached(false, 202); - assertCached(true, 203); - assertCached(true, 204); - assertCached(false, 205); - assertCached(false, 206); //Electing to not cache partial responses - assertCached(false, 207); - assertCached(true, 300); - assertCached(true, 301); - assertCached(true, 302); - assertCached(false, 303); - assertCached(false, 304); - assertCached(false, 305); - assertCached(false, 306); - assertCached(true, 307); - assertCached(true, 308); - assertCached(false, 400); - assertCached(false, 401); - assertCached(false, 402); - assertCached(false, 403); - assertCached(true, 404); - assertCached(true, 405); - assertCached(false, 406); - assertCached(false, 408); - assertCached(false, 409); - // the HTTP spec permits caching 410s, but the RI doesn't. - assertCached(true, 410); - assertCached(false, 411); - assertCached(false, 412); - assertCached(false, 413); - assertCached(true, 414); - assertCached(false, 415); - assertCached(false, 416); - assertCached(false, 417); - assertCached(false, 418); + // We can't test 100 because it's not really a response. + // assertCached(false, 100); + assertCached(false, 101); + assertCached(false, 102); + assertCached(true, 200); + assertCached(false, 201); + assertCached(false, 202); + assertCached(true, 203); + assertCached(true, 204); + assertCached(false, 205); + assertCached(false, 206); //Electing to not cache partial responses + assertCached(false, 207); + assertCached(true, 300); + assertCached(true, 301); + assertCached(true, 302); + assertCached(false, 303); + assertCached(false, 304); + assertCached(false, 305); + assertCached(false, 306); + assertCached(true, 307); + assertCached(true, 308); + assertCached(false, 400); + assertCached(false, 401); + assertCached(false, 402); + assertCached(false, 403); + assertCached(true, 404); + assertCached(true, 405); + assertCached(false, 406); + assertCached(false, 408); + assertCached(false, 409); + // the HTTP spec permits caching 410s, but the RI doesn't. + assertCached(true, 410); + assertCached(false, 411); + assertCached(false, 412); + assertCached(false, 413); + assertCached(true, 414); + assertCached(false, 415); + assertCached(false, 416); + assertCached(false, 417); + assertCached(false, 418); - assertCached(false, 500); - assertCached(true, 501); - assertCached(false, 502); - assertCached(false, 503); - assertCached(false, 504); - assertCached(false, 505); - assertCached(false, 506); + assertCached(false, 500); + assertCached(true, 501); + assertCached(false, 502); + assertCached(false, 503); + assertCached(false, 504); + assertCached(false, 505); + assertCached(false, 506); } private void assertCached(boolean shouldPut, int responseCode) throws Exception { @@ -352,10 +352,9 @@ public final class UrlConnectionCacheTest { } /** - * We've had bugs where caching and cross-protocol redirects yield class - * cast exceptions internal to the cache because we incorrectly assumed that - * HttpsURLConnection was always HTTPS and HttpURLConnection was always HTTP; - * in practice redirects mean that each can do either. + * We've had bugs where caching and cross-protocol redirects yield class cast exceptions internal + * to the cache because we incorrectly assumed that HttpsURLConnection was always HTTPS and + * HttpURLConnection was always HTTP; in practice redirects mean that each can do either. * * https://github.com/square/okhttp/issues/214 */ @@ -1038,8 +1037,8 @@ public final class UrlConnectionCacheTest { } /** - * Confirm that {@link URLConnection#setIfModifiedSince} causes an - * If-Modified-Since header with a GMT timestamp. + * Confirm that {@link URLConnection#setIfModifiedSince} causes an If-Modified-Since header with a + * GMT timestamp. * * https://code.google.com/p/android/issues/detail?id=66135 */ @@ -1056,8 +1055,8 @@ public final class UrlConnectionCacheTest { } /** - * For Last-Modified and Date headers, we should echo the date back in the - * exact format we were served. + * For Last-Modified and Date headers, we should echo the date back in the exact format we were + * served. */ @Test public void retainServedDateFormat() throws Exception { // Serve a response with a non-standard date format that OkHttp supports. @@ -1503,9 +1502,9 @@ public final class UrlConnectionCacheTest { @Test public void cachePlusRange() throws Exception { assertNotCached(new MockResponse().setResponseCode(HttpURLConnection.HTTP_PARTIAL) - .addHeader("Date: " + formatDate(0, TimeUnit.HOURS)) - .addHeader("Content-Range: bytes 100-100/200") - .addHeader("Cache-Control: max-age=60")); + .addHeader("Date: " + formatDate(0, TimeUnit.HOURS)) + .addHeader("Content-Range: bytes 100-100/200") + .addHeader("Cache-Control: max-age=60")); } @Test public void conditionalHitUpdatesCache() throws Exception { @@ -1590,10 +1589,9 @@ public final class UrlConnectionCacheTest { } /** - * Old implementations of OkHttp's response cache wrote header fields like - * ":status: 200 OK". This broke our cached response parser because it split - * on the first colon. This regression test exists to help us read these old - * bad cache entries. + * Old implementations of OkHttp's response cache wrote header fields like ":status: 200 OK". This + * broke our cached response parser because it split on the first colon. This regression test + * exists to help us read these old bad cache entries. * * https://github.com/square/okhttp/issues/227 */ @@ -1656,9 +1654,8 @@ public final class UrlConnectionCacheTest { } /** - * @param delta the offset from the current date to use. Negative - * values yield dates in the past; positive values yield dates in the - * future. + * @param delta the offset from the current date to use. Negative values yield dates in the past; + * positive values yield dates in the future. */ private String formatDate(long delta, TimeUnit timeUnit) { return formatDate(new Date(System.currentTimeMillis() + timeUnit.toMillis(delta))); @@ -1733,9 +1730,8 @@ public final class UrlConnectionCacheTest { } /** - * Shortens the body of {@code response} but not the corresponding headers. - * Only useful to test how clients respond to the premature conclusion of - * the HTTP body. + * Shortens the body of {@code response} but not the corresponding headers. Only useful to test + * how clients respond to the premature conclusion of the HTTP body. */ private MockResponse truncateViolently(MockResponse response, int numBytesToKeep) { response.setSocketPolicy(DISCONNECT_AT_END); @@ -1748,9 +1744,8 @@ public final class UrlConnectionCacheTest { } /** - * Reads {@code count} characters from the stream. If the stream is - * exhausted before {@code count} characters can be read, the remaining - * characters are returned and the stream is closed. + * Reads {@code count} characters from the stream. If the stream is exhausted before {@code count} + * characters can be read, the remaining characters are returned and the stream is closed. */ private String readAscii(URLConnection connection, int count) throws IOException { HttpURLConnection httpConnection = (HttpURLConnection) connection; diff --git a/okhttp-urlconnection/src/test/java/okhttp3/internal/huc/URLEncodingTest.java b/okhttp-urlconnection/src/test/java/okhttp3/internal/huc/URLEncodingTest.java index 5f0563910..6ab009ed6 100644 --- a/okhttp-urlconnection/src/test/java/okhttp3/internal/huc/URLEncodingTest.java +++ b/okhttp-urlconnection/src/test/java/okhttp3/internal/huc/URLEncodingTest.java @@ -16,6 +16,12 @@ package okhttp3.internal.huc; +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.concurrent.atomic.AtomicReference; import okhttp3.OkHttpClient; import okhttp3.OkUrlFactory; import okhttp3.Request; @@ -24,28 +30,20 @@ import okhttp3.internal.Internal; import okhttp3.internal.InternalCache; import okhttp3.internal.http.CacheRequest; import okhttp3.internal.http.CacheStrategy; - -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.util.concurrent.atomic.AtomicReference; import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.assertEquals; /** - * Exercises HttpURLConnection to convert URL to a URI. Unlike URL#toURI, - * HttpURLConnection recovers from URLs with unescaped but unsupported URI - * characters like '{' and '|' by escaping these characters. + * Exercises HttpURLConnection to convert URL to a URI. Unlike URL#toURI, HttpURLConnection recovers + * from URLs with unescaped but unsupported URI characters like '{' and '|' by escaping these + * characters. */ public final class URLEncodingTest { /** - * This test goes through the exhaustive set of interesting ASCII characters - * because most of those characters are interesting in some way according to - * RFC 2396 and RFC 2732. http://b/1158780 + * This test goes through the exhaustive set of interesting ASCII characters because most of those + * characters are interesting in some way according to RFC 2396 and RFC 2732. http://b/1158780 */ @Test @Ignore public void lenientUrlToUri() throws Exception { // alphanum diff --git a/okhttp-ws-tests/pom.xml b/okhttp-ws-tests/pom.xml index 3fc750ab5..b78e32c94 100644 --- a/okhttp-ws-tests/pom.xml +++ b/okhttp-ws-tests/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 diff --git a/okhttp-ws-tests/src/main/java/okhttp3/ws/AutobahnTester.java b/okhttp-ws-tests/src/main/java/okhttp3/ws/AutobahnTester.java index 340182236..46a453522 100644 --- a/okhttp-ws-tests/src/main/java/okhttp3/ws/AutobahnTester.java +++ b/okhttp-ws-tests/src/main/java/okhttp3/ws/AutobahnTester.java @@ -15,12 +15,6 @@ */ package okhttp3.ws; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import okhttp3.internal.Version; import java.io.IOException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; @@ -28,6 +22,12 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import okhttp3.internal.Version; import okio.Buffer; import okio.BufferedSource; @@ -35,8 +35,8 @@ import static okhttp3.ws.WebSocket.BINARY; import static okhttp3.ws.WebSocket.TEXT; /** - * Exercises the web socket implementation against the - * Autobahn Testsuite. + * Exercises the web socket implementation against the Autobahn Testsuite. */ public final class AutobahnTester { private static final String HOST = "ws://localhost:9001"; diff --git a/okhttp-ws-tests/src/test/java/okhttp3/internal/ws/RealWebSocketTest.java b/okhttp-ws-tests/src/test/java/okhttp3/internal/ws/RealWebSocketTest.java index d9e0b9e7b..90a803ec1 100644 --- a/okhttp-ws-tests/src/test/java/okhttp3/internal/ws/RealWebSocketTest.java +++ b/okhttp-ws-tests/src/test/java/okhttp3/internal/ws/RealWebSocketTest.java @@ -15,14 +15,14 @@ */ package okhttp3.internal.ws; -import okhttp3.MediaType; -import okhttp3.RequestBody; -import okhttp3.ws.WebSocketRecorder; import java.io.Closeable; import java.io.IOException; import java.net.ProtocolException; import java.util.Random; import java.util.concurrent.Executor; +import okhttp3.MediaType; +import okhttp3.RequestBody; +import okhttp3.ws.WebSocketRecorder; import okio.Buffer; import okio.BufferedSink; import okio.BufferedSource; @@ -112,7 +112,7 @@ public final class RealWebSocketTest { @Test public void binaryMessage() throws IOException { client.sendMessage(RequestBody.create(BINARY, "Hello!")); server.readMessage(); - serverListener.assertBinaryMessage(new byte[] { 'H', 'e', 'l', 'l', 'o', '!' }); + serverListener.assertBinaryMessage(new byte[] {'H', 'e', 'l', 'l', 'o', '!'}); } @Test public void missingContentTypeThrows() throws IOException { diff --git a/okhttp-ws-tests/src/test/java/okhttp3/internal/ws/WebSocketReaderTest.java b/okhttp-ws-tests/src/test/java/okhttp3/internal/ws/WebSocketReaderTest.java index 602382ea8..358b35990 100644 --- a/okhttp-ws-tests/src/test/java/okhttp3/internal/ws/WebSocketReaderTest.java +++ b/okhttp-ws-tests/src/test/java/okhttp3/internal/ws/WebSocketReaderTest.java @@ -15,14 +15,14 @@ */ package okhttp3.internal.ws; -import okhttp3.ResponseBody; -import okhttp3.ws.WebSocketRecorder; import java.io.EOFException; import java.io.IOException; import java.net.ProtocolException; import java.util.Random; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Pattern; +import okhttp3.ResponseBody; +import okhttp3.ws.WebSocketRecorder; import okhttp3.ws.WebSocketRecorder.MessageDelegate; import okio.Buffer; import okio.BufferedSource; diff --git a/okhttp-ws-tests/src/test/java/okhttp3/ws/WebSocketCallTest.java b/okhttp-ws-tests/src/test/java/okhttp3/ws/WebSocketCallTest.java index a139d04dc..17dc89d34 100644 --- a/okhttp-ws-tests/src/test/java/okhttp3/ws/WebSocketCallTest.java +++ b/okhttp-ws-tests/src/test/java/okhttp3/ws/WebSocketCallTest.java @@ -15,6 +15,13 @@ */ package okhttp3.ws; +import java.io.IOException; +import java.net.ProtocolException; +import java.util.Random; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import javax.net.ssl.SSLContext; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; @@ -24,13 +31,6 @@ import okhttp3.internal.SslContextBuilder; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.testing.RecordingHostnameVerifier; -import java.io.IOException; -import java.net.ProtocolException; -import java.util.Random; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; -import javax.net.ssl.SSLContext; import okio.Buffer; import org.junit.After; import org.junit.Rule; diff --git a/okhttp-ws-tests/src/test/java/okhttp3/ws/WebSocketRecorder.java b/okhttp-ws-tests/src/test/java/okhttp3/ws/WebSocketRecorder.java index 14a111d1b..0f019c6b7 100644 --- a/okhttp-ws-tests/src/test/java/okhttp3/ws/WebSocketRecorder.java +++ b/okhttp-ws-tests/src/test/java/okhttp3/ws/WebSocketRecorder.java @@ -15,14 +15,14 @@ */ package okhttp3.ws; -import okhttp3.MediaType; -import okhttp3.Response; -import okhttp3.ResponseBody; -import okhttp3.internal.ws.WebSocketReader; import java.io.IOException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; +import okhttp3.MediaType; +import okhttp3.Response; +import okhttp3.ResponseBody; +import okhttp3.internal.ws.WebSocketReader; import okio.Buffer; import static okhttp3.ws.WebSocket.BINARY; diff --git a/okhttp-ws/pom.xml b/okhttp-ws/pom.xml index c28edd0c9..85d0347d6 100644 --- a/okhttp-ws/pom.xml +++ b/okhttp-ws/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 diff --git a/okhttp-ws/src/main/java/okhttp3/internal/ws/RealWebSocket.java b/okhttp-ws/src/main/java/okhttp3/internal/ws/RealWebSocket.java index 2f80c1d71..84bbbeedc 100644 --- a/okhttp-ws/src/main/java/okhttp3/internal/ws/RealWebSocket.java +++ b/okhttp-ws/src/main/java/okhttp3/internal/ws/RealWebSocket.java @@ -15,17 +15,17 @@ */ package okhttp3.internal.ws; +import java.io.IOException; +import java.net.ProtocolException; +import java.util.Random; +import java.util.concurrent.Executor; +import java.util.concurrent.atomic.AtomicBoolean; import okhttp3.MediaType; import okhttp3.RequestBody; import okhttp3.ResponseBody; import okhttp3.internal.NamedRunnable; import okhttp3.ws.WebSocket; import okhttp3.ws.WebSocketListener; -import java.io.IOException; -import java.net.ProtocolException; -import java.util.Random; -import java.util.concurrent.Executor; -import java.util.concurrent.atomic.AtomicBoolean; import okio.Buffer; import okio.BufferedSink; import okio.BufferedSource; @@ -89,8 +89,8 @@ public abstract class RealWebSocket implements WebSocket { } /** - * Read a single message from the web socket and deliver it to the listener. This method should - * be called in a loop with the return value indicating whether looping should continue. + * Read a single message from the web socket and deliver it to the listener. This method should be + * called in a loop with the return value indicating whether looping should continue. */ public boolean readMessage() { try { diff --git a/okhttp-ws/src/main/java/okhttp3/internal/ws/WebSocketProtocol.java b/okhttp-ws/src/main/java/okhttp3/internal/ws/WebSocketProtocol.java index 5ffb70e54..0a1126a14 100644 --- a/okhttp-ws/src/main/java/okhttp3/internal/ws/WebSocketProtocol.java +++ b/okhttp-ws/src/main/java/okhttp3/internal/ws/WebSocketProtocol.java @@ -47,17 +47,15 @@ public final class WebSocketProtocol { static final int OPCODE_FLAG_CONTROL = 0b00001000; /** - * Byte 1 flag for whether the payload data is masked. - *

- * If this flag is set, the next four bytes represent the mask key. These bytes appear after - * any additional bytes specified by {@link #B1_MASK_LENGTH}. + * Byte 1 flag for whether the payload data is masked.

If this flag is set, the next four + * bytes represent the mask key. These bytes appear after any additional bytes specified by {@link + * #B1_MASK_LENGTH}. */ static final int B1_FLAG_MASK = 0b10000000; /** - * Byte 1 mask for the payload length. - *

- * If this value is {@link #PAYLOAD_SHORT}, the next two bytes represent the length. - * If this value is {@link #PAYLOAD_LONG}, the next eight bytes represent the length. + * Byte 1 mask for the payload length.

If this value is {@link #PAYLOAD_SHORT}, the next two + * bytes represent the length. If this value is {@link #PAYLOAD_LONG}, the next eight bytes + * represent the length. */ static final int B1_MASK_LENGTH = 0b01111111; diff --git a/okhttp-ws/src/main/java/okhttp3/internal/ws/WebSocketReader.java b/okhttp-ws/src/main/java/okhttp3/internal/ws/WebSocketReader.java index 4eac1183b..6a72c6c77 100644 --- a/okhttp-ws/src/main/java/okhttp3/internal/ws/WebSocketReader.java +++ b/okhttp-ws/src/main/java/okhttp3/internal/ws/WebSocketReader.java @@ -15,12 +15,12 @@ */ package okhttp3.internal.ws; -import okhttp3.MediaType; -import okhttp3.ResponseBody; -import okhttp3.ws.WebSocket; import java.io.EOFException; import java.io.IOException; import java.net.ProtocolException; +import okhttp3.MediaType; +import okhttp3.ResponseBody; +import okhttp3.ws.WebSocket; import okio.Buffer; import okio.BufferedSource; import okio.Okio; @@ -54,8 +54,11 @@ import static okhttp3.internal.ws.WebSocketProtocol.validateCloseCode; public final class WebSocketReader { public interface FrameCallback { void onMessage(ResponseBody body) throws IOException; + void onPing(Buffer buffer); + void onPong(Buffer buffer); + void onClose(int code, String reason); } @@ -89,11 +92,12 @@ public final class WebSocketReader { /** * Process the next protocol frame. + * *

    - *
  • If it is a control frame this will result in a single call to {@link FrameCallback}.
  • - *
  • If it is a message frame this will result in a single call to {@link - * FrameCallback#onMessage}. If the message spans multiple frames, each interleaved control - * frame will result in a corresponding call to {@link FrameCallback}. + *
  • If it is a control frame this will result in a single call to {@link FrameCallback}. + *
  • If it is a message frame this will result in a single call to {@link + * FrameCallback#onMessage}. If the message spans multiple frames, each interleaved + * control frame will result in a corresponding call to {@link FrameCallback}. *
*/ public void processNextFrame() throws IOException { diff --git a/okhttp-ws/src/main/java/okhttp3/internal/ws/WebSocketWriter.java b/okhttp-ws/src/main/java/okhttp3/internal/ws/WebSocketWriter.java index 4eb5ca433..f4f079471 100644 --- a/okhttp-ws/src/main/java/okhttp3/internal/ws/WebSocketWriter.java +++ b/okhttp-ws/src/main/java/okhttp3/internal/ws/WebSocketWriter.java @@ -38,11 +38,11 @@ import static okhttp3.internal.ws.WebSocketProtocol.validateCloseCode; /** * An RFC 6455-compatible WebSocket frame writer. - *

- * This class is partially thread safe. Only a single "main" thread should be sending messages via - * calls to {@link #newMessageSink}, {@link #writePing}, or {@link #writeClose}. Other threads may - * call {@link #writePing}, {@link #writePong}, or {@link #writeClose} which will interleave on the - * wire with frames from the "main" sending thread. + * + *

This class is partially thread safe. Only a single "main" thread should be sending messages + * via calls to {@link #newMessageSink}, {@link #writePing}, or {@link #writeClose}. Other threads + * may call {@link #writePing}, {@link #writePong}, or {@link #writeClose} which will interleave on + * the wire with frames from the "main" sending thread. */ public final class WebSocketWriter { private final boolean isClient; @@ -90,9 +90,8 @@ public final class WebSocketWriter { /** * Send a close frame with optional code and reason. * - * @param code Status code as defined by - * Section 7.4 of RFC 6455 or - * {@code 0}. + * @param code Status code as defined by Section 7.4 of RFC 6455 or {@code 0}. * @param reason Reason for shutting down or {@code null}. */ public void writeClose(int code, String reason) throws IOException { diff --git a/okhttp-ws/src/main/java/okhttp3/ws/WebSocket.java b/okhttp-ws/src/main/java/okhttp3/ws/WebSocket.java index 20536c11e..7435c01d7 100644 --- a/okhttp-ws/src/main/java/okhttp3/ws/WebSocket.java +++ b/okhttp-ws/src/main/java/okhttp3/ws/WebSocket.java @@ -15,9 +15,9 @@ */ package okhttp3.ws; +import java.io.IOException; import okhttp3.MediaType; import okhttp3.RequestBody; -import java.io.IOException; import okio.Buffer; /** Blocking interface to connect and write to a web socket. */ @@ -50,11 +50,11 @@ public interface WebSocket { /** * Send a close frame to the server. - *

- * The corresponding {@link WebSocketListener} will continue to get messages until its - * {@link WebSocketListener#onClose onClose()} method is called. - *

- * It is an error to call this method before calling close on an active writer. Calling this + * + *

The corresponding {@link WebSocketListener} will continue to get messages until its {@link + * WebSocketListener#onClose onClose()} method is called. + * + *

It is an error to call this method before calling close on an active writer. Calling this * method more than once has no effect. * * @throws IOException if unable to write the close message. Resources will still be freed. diff --git a/okhttp-ws/src/main/java/okhttp3/ws/WebSocketCall.java b/okhttp-ws/src/main/java/okhttp3/ws/WebSocketCall.java index 64eb30109..fcbc90b09 100644 --- a/okhttp-ws/src/main/java/okhttp3/ws/WebSocketCall.java +++ b/okhttp-ws/src/main/java/okhttp3/ws/WebSocketCall.java @@ -15,6 +15,14 @@ */ package okhttp3.ws; +import java.io.IOException; +import java.net.ProtocolException; +import java.security.SecureRandom; +import java.util.Collections; +import java.util.Random; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.ThreadPoolExecutor; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; @@ -26,14 +34,6 @@ import okhttp3.internal.Util; import okhttp3.internal.http.StreamAllocation; import okhttp3.internal.ws.RealWebSocket; import okhttp3.internal.ws.WebSocketProtocol; -import java.io.IOException; -import java.net.ProtocolException; -import java.security.SecureRandom; -import java.util.Collections; -import java.util.Random; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.LinkedBlockingDeque; -import java.util.concurrent.ThreadPoolExecutor; import okio.ByteString; import static java.util.concurrent.TimeUnit.SECONDS; @@ -83,8 +83,8 @@ public final class WebSocketCall { /** * Schedules the request to be executed at some point in the future. * - *

The {@link OkHttpClient#getDispatcher dispatcher} defines when the request will run: - * usually immediately unless there are several other requests currently being executed. + *

The {@link OkHttpClient#getDispatcher dispatcher} defines when the request will run: usually + * immediately unless there are several other requests currently being executed. * *

This client will later call back {@code responseCallback} with either an HTTP response or a * failure exception. If you {@link #cancel} a request before it completes the callback will not diff --git a/okhttp-ws/src/main/java/okhttp3/ws/WebSocketListener.java b/okhttp-ws/src/main/java/okhttp3/ws/WebSocketListener.java index feb7e1fba..12d5e66aa 100644 --- a/okhttp-ws/src/main/java/okhttp3/ws/WebSocketListener.java +++ b/okhttp-ws/src/main/java/okhttp3/ws/WebSocketListener.java @@ -15,20 +15,19 @@ */ package okhttp3.ws; +import java.io.IOException; import okhttp3.Response; import okhttp3.ResponseBody; -import java.io.IOException; import okio.Buffer; /** Listener for server-initiated messages on a connected {@link WebSocket}. */ public interface WebSocketListener { /** * Called when the request has successfully been upgraded to a web socket. This method is called - * on the message reading thread to allow setting up any state before the - * {@linkplain #onMessage message}, {@linkplain #onPong pong}, and {@link #onClose close} - * callbacks start. - *

- * Do not use this callback to write to the web socket. Start a new thread or use + * on the message reading thread to allow setting up any state before the {@linkplain #onMessage + * message}, {@linkplain #onPong pong}, and {@link #onClose close} callbacks start. + * + *

Do not use this callback to write to the web socket. Start a new thread or use * another thread in your application. */ void onOpen(WebSocket webSocket, Response response); @@ -42,12 +41,12 @@ public interface WebSocketListener { void onFailure(IOException e, Response response); /** - * Called when a server message is received. The {@code type} indicates whether the - * {@code payload} should be interpreted as UTF-8 text or binary data. + * Called when a server message is received. The {@code type} indicates whether the {@code + * payload} should be interpreted as UTF-8 text or binary data. * *

Implementations must call {@code source.close()} before returning. This - * indicates completion of parsing the message payload and will consume any remaining bytes in - * the message. + * indicates completion of parsing the message payload and will consume any remaining bytes in the + * message. * *

The {@linkplain ResponseBody#contentType() content type} of {@code message} will be either * {@link WebSocket#TEXT} or {@link WebSocket#BINARY} which indicates the format of the message. @@ -61,9 +60,8 @@ public interface WebSocketListener { void onPong(Buffer payload); /** - * Called when the server sends a close message. This may have been initiated - * from a call to {@link WebSocket#close(int, String) close()} or as an unprompted - * message from the server. + * Called when the server sends a close message. This may have been initiated from a call to + * {@link WebSocket#close(int, String) close()} or as an unprompted message from the server. * * @param code The RFC-compliant * status code. diff --git a/okhttp/pom.xml b/okhttp/pom.xml index 01fd8200b..194f9dad3 100644 --- a/okhttp/pom.xml +++ b/okhttp/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 diff --git a/okhttp/src/main/java/okhttp3/Address.java b/okhttp/src/main/java/okhttp3/Address.java index 51f245218..cec154262 100644 --- a/okhttp/src/main/java/okhttp3/Address.java +++ b/okhttp/src/main/java/okhttp3/Address.java @@ -26,14 +26,13 @@ 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 server's hostname and port. If an explicit proxy is requested (or - * {@linkplain Proxy#NO_PROXY no proxy} is explicitly requested), this also includes - * that proxy information. For secure connections the address also includes the - * SSL socket factory, hostname verifier, and certificate pinner. + * 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 + * proxy} is explicitly requested), this also includes that proxy information. For secure + * connections the address also includes the SSL socket factory, hostname verifier, and certificate + * pinner. * - *

HTTP requests that share the same {@code Address} may also share the same - * {@link Connection}. + *

HTTP requests that share the same {@code Address} may also share the same {@link Connection}. */ public final class Address { final HttpUrl url; @@ -108,8 +107,8 @@ public final class Address { } /** - * Returns the protocols the client supports. This method always returns a - * non-null list that contains minimally {@link Protocol#HTTP_1_1}. + * Returns the protocols the client supports. This method always returns a non-null list that + * contains minimally {@link Protocol#HTTP_1_1}. */ public List protocols() { return protocols; @@ -128,8 +127,8 @@ public final class Address { } /** - * Returns this address's explicitly-specified HTTP proxy, or null to - * delegate to the {@linkplain #proxySelector proxy selector}. + * Returns this address's explicitly-specified HTTP proxy, or null to delegate to the {@linkplain + * #proxySelector proxy selector}. */ public Proxy proxy() { return proxy; diff --git a/okhttp/src/main/java/okhttp3/Authenticator.java b/okhttp/src/main/java/okhttp3/Authenticator.java index 01568038b..1048f49f8 100644 --- a/okhttp/src/main/java/okhttp3/Authenticator.java +++ b/okhttp/src/main/java/okhttp3/Authenticator.java @@ -35,7 +35,7 @@ import java.io.IOException; * *

Whn authentication is requested by a proxy server, the response code is 407 and the * implementation should respond with a new request that sets the "Proxy-Authorization" header. - *

   {@code
+ * 
   {@code
  *
  *    String credential = Credentials.basic(...)
  *    return response.request().newBuilder()
diff --git a/okhttp/src/main/java/okhttp3/Cache.java b/okhttp/src/main/java/okhttp3/Cache.java
index 2872cbd01..eb5e35f22 100644
--- a/okhttp/src/main/java/okhttp3/Cache.java
+++ b/okhttp/src/main/java/okhttp3/Cache.java
@@ -51,14 +51,15 @@ import okio.Source;
  * bandwidth.
  *
  * 

Cache Optimization

- * To measure cache effectiveness, this class tracks three statistics: + * + *

To measure cache effectiveness, this class tracks three statistics: *

    - *
  • {@linkplain #getRequestCount() Request Count:} the number of HTTP - * requests issued since this cache was created. - *
  • {@linkplain #getNetworkCount() Network Count:} the number of those - * requests that required network use. - *
  • {@linkplain #getHitCount() Hit Count:} the number of those requests whose - * responses were served by the cache. + *
  • {@linkplain #getRequestCount() Request Count:} the number of HTTP + * requests issued since this cache was created. + *
  • {@linkplain #getNetworkCount() Network Count:} the number of those + * requests that required network use. + *
  • {@linkplain #getHitCount() Hit Count:} the number of those requests + * whose responses were served by the cache. *
* * Sometimes a request will result in a conditional cache hit. If the cache contains a stale copy of @@ -72,8 +73,9 @@ import okio.Source; * partial responses. * *

Force a Network Response

- * In some situations, such as after a user clicks a 'refresh' button, it may be necessary to skip - * the cache, and fetch data directly from the server. To force a full refresh, add the {@code + * + *

In some situations, such as after a user clicks a 'refresh' button, it may be necessary to + * skip the cache, and fetch data directly from the server. To force a full refresh, add the {@code * no-cache} directive:

   {@code
  *
  *   Request request = new Request.Builder()
@@ -94,7 +96,8 @@ import okio.Source;
  * }
* *

Force a Cache Response

- * Sometimes you'll want to show resources if they are available immediately, but not otherwise. + * + *

Sometimes you'll want to show resources if they are available immediately, but not otherwise. * This can be used so your application can show something while waiting for the latest data * to be downloaded. To restrict a request to locally-cached resources, add the {@code * only-if-cached} directive:

   {@code
@@ -138,18 +141,23 @@ public final class Cache {
     @Override public Response get(Request request) throws IOException {
       return Cache.this.get(request);
     }
+
     @Override public CacheRequest put(Response response) throws IOException {
       return Cache.this.put(response);
     }
+
     @Override public void remove(Request request) throws IOException {
       Cache.this.remove(request);
     }
+
     @Override public void update(Response cached, Response network) throws IOException {
       Cache.this.update(cached, network);
     }
+
     @Override public void trackConditionalCacheHit() {
       Cache.this.trackConditionalCacheHit();
     }
+
     @Override public void trackResponse(CacheStrategy cacheStrategy) {
       Cache.this.trackResponse(cacheStrategy);
     }
@@ -274,34 +282,31 @@ public final class Cache {
   }
 
   /**
-   * Initialize the cache. This will include reading the journal files from
-   * the storage and building up the necessary in-memory cache information.
-   * 

- * The initialization time may vary depending on the journal file size and - * the current actual cache size. The application needs to be aware of calling - * this function during the initialization phase and preferably in a background - * worker thread. - *

- * Note that if the application chooses to not call this method to initialize - * the cache. By default, the okhttp will perform lazy initialization upon the - * first usage of the cache. + * Initialize the cache. This will include reading the journal files from the storage and building + * up the necessary in-memory cache information. + * + *

The initialization time may vary depending on the journal file size and the current actual + * cache size. The application needs to be aware of calling this function during the + * initialization phase and preferably in a background worker thread. + * + *

Note that if the application chooses to not call this method to initialize the cache. By + * default, the okhttp will perform lazy initialization upon the first usage of the cache. */ public void initialize() throws IOException { cache.initialize(); } /** - * Closes the cache and deletes all of its stored values. This will delete - * all files in the cache directory including files that weren't created by - * the cache. + * Closes the cache and deletes all of its stored values. This will delete all files in the cache + * directory including files that weren't created by the cache. */ public void delete() throws IOException { cache.delete(); } /** - * Deletes all values stored in the cache. In-flight writes to the cache will - * complete normally, but the corresponding responses will not be stored. + * Deletes all values stored in the cache. In-flight writes to the cache will complete normally, + * but the corresponding responses will not be stored. */ public void evictAll() throws IOException { cache.evictAll(); @@ -397,7 +402,6 @@ public final class Cache { if (cacheStrategy.networkRequest != null) { // If this is a conditional request, we'll increment hitCount if/when it hits. networkCount++; - } else if (cacheStrategy.cacheResponse != null) { // This response uses the cache and not the network. That's a cache hit. hitCount++; @@ -509,21 +513,18 @@ public final class Cache { * -1 * TLSv1.2 * }

- * The file is newline separated. The first two lines are the URL and - * the request method. Next is the number of HTTP Vary request header - * lines, followed by those lines. + * The file is newline separated. The first two lines are the URL and the request method. Next + * is the number of HTTP Vary request header lines, followed by those lines. * - *

Next is the response status line, followed by the number of HTTP - * response header lines, followed by those lines. + *

Next is the response status line, followed by the number of HTTP response header lines, + * followed by those lines. * - *

HTTPS responses also contain SSL session information. This begins - * with a blank line, and then a line containing the cipher suite. Next - * is the length of the peer certificate chain. These certificates are - * base64-encoded and appear each on their own line. The next line - * contains the length of the local certificate chain. These - * certificates are also base64-encoded and appear each on their own - * line. A length of -1 is used to encode a null array. The last line is - * optional. If present, it contains the TLS version. + *

HTTPS responses also contain SSL session information. This begins with a blank line, and + * then a line containing the cipher suite. Next is the length of the peer certificate chain. + * These certificates are base64-encoded and appear each on their own line. The next line + * contains the length of the local certificate chain. These certificates are also + * base64-encoded and appear each on their own line. A length of -1 is used to encode a null + * array. The last line is optional. If present, it contains the TLS version. */ public Entry(Source in) throws IOException { try { diff --git a/okhttp/src/main/java/okhttp3/CacheControl.java b/okhttp/src/main/java/okhttp3/CacheControl.java index 3f3bd166a..23a23bdbc 100644 --- a/okhttp/src/main/java/okhttp3/CacheControl.java +++ b/okhttp/src/main/java/okhttp3/CacheControl.java @@ -1,29 +1,26 @@ package okhttp3; -import okhttp3.internal.http.HeaderParser; import java.util.concurrent.TimeUnit; +import okhttp3.internal.http.HeaderParser; /** - * A Cache-Control header with cache directives from a server or client. These - * directives set policy on what responses can be stored, and which requests can - * be satisfied by those stored responses. + * A Cache-Control header with cache directives from a server or client. These directives set policy + * on what responses can be stored, and which requests can be satisfied by those stored responses. * - *

See RFC - * 2616, 14.9. + *

See RFC 2616, + * 14.9. */ public final class CacheControl { /** - * Cache control request directives that require network validation of - * responses. Note that such requests may be assisted by the cache via - * conditional GET requests. + * Cache control request directives that require network validation of responses. Note that such + * requests may be assisted by the cache via conditional GET requests. */ public static final CacheControl FORCE_NETWORK = new Builder().noCache().build(); /** - * Cache control request directives that uses the cache only, even if the - * cached response is stale. If the response isn't available in the cache or - * requires server validation, the call will fail with a {@code 504 - * Unsatisfiable Request}. + * Cache control request directives that uses the cache only, even if the cached response is + * stale. If the response isn't available in the cache or requires server validation, the call + * will fail with a {@code 504 Unsatisfiable Request}. */ public static final CacheControl FORCE_CACHE = new Builder() .onlyIfCached() @@ -76,10 +73,9 @@ public final class CacheControl { } /** - * In a response, this field's name "no-cache" is misleading. It doesn't - * prevent us from caching the response; it only means we have to validate the - * response with the origin server before returning it. We can do this with a - * conditional GET. + * In a response, this field's name "no-cache" is misleading. It doesn't prevent us from caching + * the response; it only means we have to validate the response with the origin server before + * returning it. We can do this with a conditional GET. * *

In a request, it means do not use a cache to satisfy the request. */ @@ -93,17 +89,15 @@ public final class CacheControl { } /** - * The duration past the response's served date that it can be served without - * validation. + * The duration past the response's served date that it can be served without validation. */ public int maxAgeSeconds() { return maxAgeSeconds; } /** - * The "s-maxage" directive is the max age for shared caches. Not to be - * confused with "max-age" for non-shared caches, As in Firefox and Chrome, - * this directive is not honored by this cache. + * The "s-maxage" directive is the max age for shared caches. Not to be confused with "max-age" + * for non-shared caches, As in Firefox and Chrome, this directive is not honored by this cache. */ public int sMaxAgeSeconds() { return sMaxAgeSeconds; @@ -130,11 +124,10 @@ public final class CacheControl { } /** - * This field's name "only-if-cached" is misleading. It actually means "do - * not use the network". It is set by a client who only wants to make a - * request if it can be fully satisfied by the cache. Cached responses that - * would require validation (ie. conditional gets) are not permitted if this - * header is set. + * This field's name "only-if-cached" is misleading. It actually means "do not use the network". + * It is set by a client who only wants to make a request if it can be fully satisfied by the + * cache. Cached responses that would require validation (ie. conditional gets) are not permitted + * if this header is set. */ public boolean onlyIfCached() { return onlyIfCached; @@ -145,8 +138,8 @@ public final class CacheControl { } /** - * Returns the cache directives of {@code headers}. This honors both - * Cache-Control and Pragma headers if they are present. + * Returns the cache directives of {@code headers}. This honors both Cache-Control and Pragma + * headers if they are present. */ public static CacheControl parse(Headers headers) { boolean noCache = false; @@ -291,12 +284,11 @@ public final class CacheControl { } /** - * Sets the maximum age of a cached response. If the cache response's age - * exceeds {@code maxAge}, it will not be used and a network request will - * be made. + * Sets the maximum age of a cached response. If the cache response's age exceeds {@code + * maxAge}, it will not be used and a network request will be made. * - * @param maxAge a non-negative integer. This is stored and transmitted with - * {@link TimeUnit#SECONDS} precision; finer precision will be lost. + * @param maxAge a non-negative integer. This is stored and transmitted with {@link + * TimeUnit#SECONDS} precision; finer precision will be lost. */ public Builder maxAge(int maxAge, TimeUnit timeUnit) { if (maxAge < 0) throw new IllegalArgumentException("maxAge < 0: " + maxAge); @@ -308,13 +300,11 @@ public final class CacheControl { } /** - * Accept cached responses that have exceeded their freshness lifetime by - * up to {@code maxStale}. If unspecified, stale cache responses will not be - * used. + * Accept cached responses that have exceeded their freshness lifetime by up to {@code + * maxStale}. If unspecified, stale cache responses will not be used. * - * @param maxStale a non-negative integer. This is stored and transmitted - * with {@link TimeUnit#SECONDS} precision; finer precision will be - * lost. + * @param maxStale a non-negative integer. This is stored and transmitted with {@link + * TimeUnit#SECONDS} precision; finer precision will be lost. */ public Builder maxStale(int maxStale, TimeUnit timeUnit) { if (maxStale < 0) throw new IllegalArgumentException("maxStale < 0: " + maxStale); @@ -326,14 +316,12 @@ public final class CacheControl { } /** - * Sets the minimum number of seconds that a response will continue to be - * fresh for. If the response will be stale when {@code minFresh} have - * elapsed, the cached response will not be used and a network request will - * be made. + * Sets the minimum number of seconds that a response will continue to be fresh for. If the + * response will be stale when {@code minFresh} have elapsed, the cached response will not be + * used and a network request will be made. * - * @param minFresh a non-negative integer. This is stored and transmitted - * with {@link TimeUnit#SECONDS} precision; finer precision will be - * lost. + * @param minFresh a non-negative integer. This is stored and transmitted with {@link + * TimeUnit#SECONDS} precision; finer precision will be lost. */ public Builder minFresh(int minFresh, TimeUnit timeUnit) { if (minFresh < 0) throw new IllegalArgumentException("minFresh < 0: " + minFresh); @@ -345,8 +333,8 @@ public final class CacheControl { } /** - * Only accept the response if it is in the cache. If the response isn't - * cached, a {@code 504 Unsatisfiable Request} response will be returned. + * Only accept the response if it is in the cache. If the response isn't cached, a {@code 504 + * Unsatisfiable Request} response will be returned. */ public Builder onlyIfCached() { this.onlyIfCached = true; diff --git a/okhttp/src/main/java/okhttp3/Call.java b/okhttp/src/main/java/okhttp3/Call.java index 6ffa8cc5b..3d5389796 100644 --- a/okhttp/src/main/java/okhttp3/Call.java +++ b/okhttp/src/main/java/okhttp3/Call.java @@ -18,29 +18,25 @@ package okhttp3; import java.io.IOException; /** - * A call is a request that has been prepared for execution. A call can be - * canceled. As this object represents a single request/response pair (stream), - * it cannot be executed twice. + * A call is a request that has been prepared for execution. A call can be canceled. As this object + * represents a single request/response pair (stream), it cannot be executed twice. */ public interface Call { /** - * Invokes the request immediately, and blocks until the response can be - * processed or is in error. + * Invokes the request immediately, and blocks until the response can be processed or is in + * error. * - *

The caller may read the response body with the response's - * {@link Response#body} method. To facilitate connection recycling, callers - * should always {@link ResponseBody#close() close the response body}. + *

The caller may read the response body with the response's {@link Response#body} method. To + * facilitate connection recycling, callers should always {@link ResponseBody#close() close the + * response body}. * - *

Note that transport-layer success (receiving a HTTP response code, - * headers and body) does not necessarily indicate application-layer success: - * {@code response} may still indicate an unhappy HTTP response code like 404 - * or 500. - * - * @throws IOException if the request could not be executed due to - * cancellation, a connectivity problem or timeout. Because networks can - * fail during an exchange, it is possible that the remote server - * accepted the request before the failure. + *

Note that transport-layer success (receiving a HTTP response code, headers and body) does + * not necessarily indicate application-layer success: {@code response} may still indicate an + * unhappy HTTP response code like 404 or 500. * + * @throws IOException if the request could not be executed due to cancellation, a connectivity + * problem or timeout. Because networks can fail during an exchange, it is possible that the + * remote server accepted the request before the failure. * @throws IllegalStateException when the call has already been executed. */ Response execute() throws IOException; @@ -48,22 +44,18 @@ public interface Call { /** * Schedules the request to be executed at some point in the future. * - *

The {@link OkHttpClient#getDispatcher dispatcher} defines when the - * request will run: usually immediately unless there are several other - * requests currently being executed. + *

The {@link OkHttpClient#getDispatcher dispatcher} defines when the request will run: usually + * immediately unless there are several other requests currently being executed. * - *

This client will later call back {@code responseCallback} with either - * an HTTP response or a failure exception. If you {@link #cancel} a request - * before it completes the callback will not be invoked. + *

This client will later call back {@code responseCallback} with either an HTTP response or a + * failure exception. If you {@link #cancel} a request before it completes the callback will not + * be invoked. * * @throws IllegalStateException when the call has already been executed. */ void enqueue(Callback responseCallback); - /** - * Cancels the request, if possible. Requests that are already complete - * cannot be canceled. - */ + /** Cancels the request, if possible. Requests that are already complete cannot be canceled. */ void cancel(); /** diff --git a/okhttp/src/main/java/okhttp3/Callback.java b/okhttp/src/main/java/okhttp3/Callback.java index 6c267364e..32407ff60 100644 --- a/okhttp/src/main/java/okhttp3/Callback.java +++ b/okhttp/src/main/java/okhttp3/Callback.java @@ -19,24 +19,21 @@ import java.io.IOException; public interface Callback { /** - * Called when the request could not be executed due to cancellation, a - * connectivity problem or timeout. Because networks can fail during an - * exchange, it is possible that the remote server accepted the request - * before the failure. + * Called when the request could not be executed due to cancellation, a connectivity problem or + * timeout. Because networks can fail during an exchange, it is possible that the remote server + * accepted the request before the failure. */ void onFailure(Request request, IOException e); /** - * Called when the HTTP response was successfully returned by the remote - * server. The callback may proceed to read the response body with {@link - * Response#body}. The response is still live until its response body is - * closed with {@code response.body().close()}. The recipient of the callback + * Called when the HTTP response was successfully returned by the remote server. The callback may + * proceed to read the response body with {@link Response#body}. The response is still live until + * its response body is closed with {@code response.body().close()}. The recipient of the callback * may even consume the response body on another thread. * - *

Note that transport-layer success (receiving a HTTP response code, - * headers and body) does not necessarily indicate application-layer - * success: {@code response} may still indicate an unhappy HTTP response - * code like 404 or 500. + *

Note that transport-layer success (receiving a HTTP response code, headers and body) does + * not necessarily indicate application-layer success: {@code response} may still indicate an + * unhappy HTTP response code like 404 or 500. */ void onResponse(Response response) throws IOException; } diff --git a/okhttp/src/main/java/okhttp3/CertificatePinner.java b/okhttp/src/main/java/okhttp3/CertificatePinner.java index 78f774232..4c56d6c14 100644 --- a/okhttp/src/main/java/okhttp3/CertificatePinner.java +++ b/okhttp/src/main/java/okhttp3/CertificatePinner.java @@ -15,7 +15,6 @@ */ package okhttp3; -import okhttp3.internal.Util; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.Arrays; @@ -25,28 +24,27 @@ import java.util.List; import java.util.Map; import java.util.Set; import javax.net.ssl.SSLPeerUnverifiedException; +import okhttp3.internal.Util; import okio.ByteString; import static java.util.Collections.unmodifiableSet; /** - * Constrains which certificates are trusted. Pinning certificates defends - * against attacks on certificate authorities. It also prevents connections - * through man-in-the-middle certificate authorities either known or unknown to - * the application's user. + * Constrains which certificates are trusted. Pinning certificates defends against attacks on + * certificate authorities. It also prevents connections through man-in-the-middle certificate + * authorities either known or unknown to the application's user. * - *

This class currently pins a certificate's Subject Public Key Info as - * described on Adam Langley's Weblog. Pins - * are base-64 SHA-1 hashes, consistent with the format Chromium uses for static certificates. See Chromium's pinsets for hostnames that are pinned in that + *

This class currently pins a certificate's Subject Public Key Info as described on Adam Langley's Weblog. Pins are base-64 SHA-1 hashes, consistent + * with the format Chromium uses for static certificates. See + * Chromium's pinsets for hostnames that are pinned in that * browser. * *

Setting up Certificate Pinning

- * The easiest way to pin a host is turn on pinning with a broken configuration - * and read the expected configuration when the connection fails. Be sure to - * do this on a trusted network, and without man-in-the-middle tools like Charles or The easiest way to pin a host is turn on pinning with a broken configuration and read the + * expected configuration when the connection fails. Be sure to do this on a trusted network, and + * without man-in-the-middle tools like Charles or Fiddler. * *

For example, to pin {@code https://publicobject.com}, start with a broken @@ -92,42 +90,39 @@ import static java.util.Collections.unmodifiableSet; * .build(); * }

* - * Pinning is per-hostname and/or per-wildcard pattern. To pin both - * {@code publicobject.com} and {@code www.publicobject.com}, you must - * configure both hostnames. + * Pinning is per-hostname and/or per-wildcard pattern. To pin both {@code publicobject.com} and + * {@code www.publicobject.com}, you must configure both hostnames. * *

Wildcard pattern rules: *

    - *
  1. Asterisk {@code *} is only permitted in the left-most - * domain name label and must be the only character in that label - * (i.e., must match the whole left-most label). For example, - * {@code *.example.com} is permitted, while {@code *a.example.com}, - * {@code a*.example.com}, {@code a*b.example.com}, {@code a.*.example.com} - * are not permitted. - *
  2. Asterisk {@code *} cannot match across domain name labels. - * For example, {@code *.example.com} matches {@code test.example.com} - * but does not match {@code sub.test.example.com}. - *
  3. Wildcard patterns for single-label domain names are not permitted. + *
  4. Asterisk {@code *} is only permitted in the left-most domain name label and must be the + * only character in that label (i.e., must match the whole left-most label). For example, + * {@code *.example.com} is permitted, while {@code *a.example.com}, {@code a*.example.com}, + * {@code a*b.example.com}, {@code a.*.example.com} are not permitted. + *
  5. Asterisk {@code *} cannot match across domain name labels. For example, + * {@code *.example.com} matches {@code test.example.com} but does not match + * {@code sub.test.example.com}. + *
  6. Wildcard patterns for single-label domain names are not permitted. *
* - * If hostname pinned directly and via wildcard pattern, both - * direct and wildcard pins will be used. For example: {@code *.example.com} pinned - * with {@code pin1} and {@code a.example.com} pinned with {@code pin2}, - * to check {@code a.example.com} both {@code pin1} and {@code pin2} will be used. + * If hostname pinned directly and via wildcard pattern, both direct and wildcard pins will be used. + * For example: {@code *.example.com} pinned with {@code pin1} and {@code a.example.com} pinned with + * {@code pin2}, to check {@code a.example.com} both {@code pin1} and {@code pin2} will be used. * *

Warning: Certificate Pinning is Dangerous!

- * Pinning certificates limits your server team's abilities to update their TLS - * certificates. By pinning certificates, you take on additional operational - * complexity and limit your ability to migrate between certificate authorities. - * Do not use certificate pinning without the blessing of your server's TLS - * administrator! + * + *

Pinning certificates limits your server team's abilities to update their TLS certificates. By + * pinning certificates, you take on additional operational complexity and limit your ability to + * migrate between certificate authorities. Do not use certificate pinning without the blessing of + * your server's TLS administrator! * *

Note about self-signed certificates

- * {@link CertificatePinner} can not be used to pin self-signed certificate - * if such certificate is not accepted by {@link javax.net.ssl.TrustManager}. * - * @see - * OWASP: Certificate and Public Key Pinning + *

{@link CertificatePinner} can not be used to pin self-signed certificate if such certificate + * is not accepted by {@link javax.net.ssl.TrustManager}. + * + * @see OWASP: + * Certificate and Public Key Pinning */ public final class CertificatePinner { public static final CertificatePinner DEFAULT = new Builder().build(); @@ -139,13 +134,12 @@ public final class CertificatePinner { } /** - * Confirms that at least one of the certificates pinned for {@code hostname} - * is in {@code peerCertificates}. Does nothing if there are no certificates - * pinned for {@code hostname}. OkHttp calls this after a successful TLS - * handshake, but before the connection is used. + * Confirms that at least one of the certificates pinned for {@code hostname} is in {@code + * peerCertificates}. Does nothing if there are no certificates pinned for {@code hostname}. + * OkHttp calls this after a successful TLS handshake, but before the connection is used. * - * @throws SSLPeerUnverifiedException if {@code peerCertificates} don't match - * the certificates pinned for {@code hostname}. + * @throws SSLPeerUnverifiedException if {@code peerCertificates} don't match the certificates + * pinned for {@code hostname}. */ public void check(String hostname, List peerCertificates) throws SSLPeerUnverifiedException { @@ -182,15 +176,15 @@ public final class CertificatePinner { } /** - * Returns list of matching certificates' pins for the hostname - * or {@code null} if hostname does not have pinned certificates. + * Returns list of matching certificates' pins for the hostname or {@code null} if hostname does + * not have pinned certificates. */ Set findMatchingPins(String hostname) { - Set directPins = hostnameToPins.get(hostname); + Set directPins = hostnameToPins.get(hostname); Set wildcardPins = null; int indexOfFirstDot = hostname.indexOf('.'); - int indexOfLastDot = hostname.lastIndexOf('.'); + int indexOfLastDot = hostname.lastIndexOf('.'); // Skip hostnames with one dot symbol for wildcard pattern search // example.com will be skipped @@ -215,9 +209,9 @@ public final class CertificatePinner { } /** - * Returns the SHA-1 of {@code certificate}'s public key. This uses the - * mechanism Moxie Marlinspike describes in Android Pinning. + * Returns the SHA-1 of {@code certificate}'s public key. This uses the mechanism Moxie + * Marlinspike describes in Android + * Pinning. */ public static String pin(Certificate certificate) { if (!(certificate instanceof X509Certificate)) { @@ -238,9 +232,8 @@ public final class CertificatePinner { * Pins certificates for {@code hostname}. * * @param hostname lower-case host name or wildcard pattern such as {@code *.example.com}. - * @param pins SHA-1 hashes. Each pin is a SHA-1 hash of a - * certificate's Subject Public Key Info, base64-encoded and prefixed with - * {@code sha1/}. + * @param pins SHA-1 hashes. Each pin is a SHA-1 hash of a certificate's Subject Public Key + * Info, base64-encoded and prefixed with {@code sha1/}. */ public Builder add(String hostname, String... pins) { if (hostname == null) throw new IllegalArgumentException("hostname == null"); diff --git a/okhttp/src/main/java/okhttp3/CipherSuite.java b/okhttp/src/main/java/okhttp3/CipherSuite.java index ed4167c98..6697cad84 100644 --- a/okhttp/src/main/java/okhttp3/CipherSuite.java +++ b/okhttp/src/main/java/okhttp3/CipherSuite.java @@ -356,7 +356,7 @@ public enum CipherSuite { /** * @param javaName the name used by Java APIs for this cipher suite. Different than the IANA name - * for older cipher suites because the prefix is {@code SSL_} instead of {@code TLS_}. + * for older cipher suites because the prefix is {@code SSL_} instead of {@code TLS_}. * @param value the integer identifier for this cipher suite. (Documentation only.) * @param rfc the RFC describing this cipher suite. (Documentation only.) * @param sinceJavaVersion the first major Java release supporting this cipher suite. diff --git a/okhttp/src/main/java/okhttp3/Connection.java b/okhttp/src/main/java/okhttp3/Connection.java index 7bb741173..de3c22d98 100644 --- a/okhttp/src/main/java/okhttp3/Connection.java +++ b/okhttp/src/main/java/okhttp3/Connection.java @@ -30,19 +30,23 @@ import java.net.Socket; * connection as a single request/response exchange. * *

Modern TLS

- * There are tradeoffs when selecting which options to include when negotiating a secure connection - * to a remote host. Newer TLS options are quite useful: + * + *

There are tradeoffs when selecting which options to include when negotiating a secure + * connection to a remote host. Newer TLS options are quite useful: + * *

    - *
  • Server Name Indication (SNI) enables one IP address to negotiate secure connections for - * multiple domain names. - *
  • Application Layer Protocol Negotiation (ALPN) enables the HTTPS port (443) to be used for - * different HTTP and SPDY protocols. + *
  • Server Name Indication (SNI) enables one IP address to negotiate secure connections for + * multiple domain names. + *
  • Application Layer Protocol Negotiation (ALPN) enables the HTTPS port (443) to be used for + * different HTTP and SPDY protocols. *
- * Unfortunately, older HTTPS servers refuse to connect when such options are presented. Rather than - * avoiding these options entirely, this class allows a connection to be attempted with modern + * + *

Unfortunately, older HTTPS servers refuse to connect when such options are presented. Rather + * than avoiding these options entirely, this class allows a connection to be attempted with modern * options and then retried without them should the attempt fail. * *

Connection Reuse

+ * *

Each connection can carry a varying number streams, depending on the underlying protocol being * used. HTTP/1.x connections can carry either zero or one streams. HTTP/2 connections can carry any * number of streams, dynamically configured with {@code SETTINGS_MAX_CONCURRENT_STREAMS}. A @@ -53,8 +57,8 @@ import java.net.Socket; * challenges, we prefer to use the same physical connection for all streams in the sequence. There * are potential performance and behavior consequences to this preference. To support this feature, * this class separates allocations from streams. An allocation is created by a call, - * used for one or more streams, and then released. An allocated connection won't be stolen by - * other calls while a redirect or authorization challenge is being handled. + * used for one or more streams, and then released. An allocated connection won't be stolen by other + * calls while a redirect or authorization challenge is being handled. * *

When the maximum concurrent streams limit is reduced, some allocations will be rescinded. * Attempting to create new streams on these allocations will fail. diff --git a/okhttp/src/main/java/okhttp3/ConnectionPool.java b/okhttp/src/main/java/okhttp3/ConnectionPool.java index 1ef4cbc95..e10935c3c 100644 --- a/okhttp/src/main/java/okhttp3/ConnectionPool.java +++ b/okhttp/src/main/java/okhttp3/ConnectionPool.java @@ -16,11 +16,6 @@ */ package okhttp3; -import okhttp3.internal.Internal; -import okhttp3.internal.RouteDatabase; -import okhttp3.internal.Util; -import okhttp3.internal.http.StreamAllocation; -import okhttp3.internal.io.RealConnection; import java.lang.ref.Reference; import java.util.ArrayDeque; import java.util.ArrayList; @@ -31,31 +26,34 @@ import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import okhttp3.internal.Internal; +import okhttp3.internal.RouteDatabase; +import okhttp3.internal.Util; +import okhttp3.internal.http.StreamAllocation; +import okhttp3.internal.io.RealConnection; import static okhttp3.internal.Util.closeQuietly; /** - * Manages reuse of HTTP and SPDY connections for reduced network latency. HTTP - * requests that share the same {@link Address} may share a - * {@link Connection}. This class implements the policy of which connections to - * keep open for future use. + * Manages reuse of HTTP and SPDY connections for reduced network latency. HTTP requests that share + * the same {@link Address} may share a {@link Connection}. This class implements the policy of + * which connections to keep open for future use. + * + *

The {@link #getDefault() system-wide default} uses system properties for tuning parameters: * - *

The {@link #getDefault() system-wide default} uses system properties for - * tuning parameters: *

    - *
  • {@code http.keepAlive} true if HTTP and SPDY connections should be - * pooled at all. Default is true. - *
  • {@code http.maxConnections} maximum number of idle connections to - * each to keep in the pool. Default is 5. - *
  • {@code http.keepAliveDuration} Time in milliseconds to keep the - * connection alive in the pool before closing it. Default is 5 minutes. - * This property isn't used by {@code HttpURLConnection}. + *
  • {@code http.keepAlive} true if HTTP and SPDY connections should be pooled at all. Default + * is true. + *
  • {@code http.maxConnections} maximum number of idle connections to each to keep in the + * pool. Default is 5. + *
  • {@code http.keepAliveDuration} Time in milliseconds to keep the connection alive in the + * pool before closing it. Default is 5 minutes. This property isn't used by {@code + * HttpURLConnection}. *
* - *

The default instance doesn't adjust its configuration as system - * properties are changed. This assumes that the applications that set these - * parameters do so before making HTTP connections, and that this class is - * initialized lazily. + *

The default instance doesn't adjust its configuration as system properties are changed. + * This assumes that the applications that set these parameters do so before making HTTP + * connections, and that this class is initialized lazily. */ public final class ConnectionPool { private static final long DEFAULT_KEEP_ALIVE_DURATION_MS = 5 * 60 * 1000; // 5 min @@ -80,8 +78,8 @@ public final class ConnectionPool { /** * A background thread is used to cleanup expired connections. There will be, at most, a single - * thread running per connection pool. We use a thread pool executor because it can shrink to - * zero threads, permitting this pool to be garbage collected. + * thread running per connection pool. We use a thread pool executor because it can shrink to zero + * threads, permitting this pool to be garbage collected. */ private final Executor executor = new ThreadPoolExecutor( 0 /* corePoolSize */, 1 /* maximumPoolSize */, 60L /* keepAliveTime */, TimeUnit.SECONDS, @@ -188,8 +186,8 @@ public final class ConnectionPool { } /** - * Notify this pool that {@code connection} has become idle. Returns true if the connection - * has been removed from the pool and should be closed. + * Notify this pool that {@code connection} has become idle. Returns true if the connection has + * been removed from the pool and should be closed. */ boolean connectionBecameIdle(RealConnection connection) { assert (Thread.holdsLock(this)); @@ -225,8 +223,8 @@ public final class ConnectionPool { * Performs maintenance on this pool, evicting the connection that has been idle the longest if * either it has exceeded the keep alive limit or the idle connections limit. * - *

Returns the duration in nanos to sleep until the next scheduled call to this method. - * Returns -1 if no further cleanups are required. + *

Returns the duration in nanos to sleep until the next scheduled call to this method. Returns + * -1 if no further cleanups are required. */ long cleanup(long now) { int inUseConnectionCount = 0; @@ -260,15 +258,12 @@ public final class ConnectionPool { // We've found a connection to evict. Remove it from the list, then close it below (outside // of the synchronized block). connections.remove(longestIdleConnection); - } else if (idleConnectionCount > 0) { // A connection will be ready to evict soon. return keepAliveDurationNs - longestIdleDurationNs; - } else if (inUseConnectionCount > 0) { // All connections are in use. It'll be at least the keep alive duration 'til we run again. return keepAliveDurationNs; - } else { // No connections, idle or in use. return -1; diff --git a/okhttp/src/main/java/okhttp3/ConnectionSpec.java b/okhttp/src/main/java/okhttp3/ConnectionSpec.java index 9b7569495..8c99932f9 100644 --- a/okhttp/src/main/java/okhttp3/ConnectionSpec.java +++ b/okhttp/src/main/java/okhttp3/ConnectionSpec.java @@ -162,8 +162,8 @@ public final class ConnectionSpec { } /** - * Returns {@code true} if the socket, as currently configured, supports this connection spec. - * In order for a socket to be compatible the enabled cipher suites and protocols must intersect. + * Returns {@code true} if the socket, as currently configured, supports this connection spec. In + * order for a socket to be compatible the enabled cipher suites and protocols must intersect. * *

For cipher suites, at least one of the {@link #cipherSuites() required cipher suites} must * match the socket's enabled cipher suites. If there are no required cipher suites the socket @@ -191,9 +191,9 @@ public final class ConnectionSpec { } /** - * An N*M intersection that terminates if any intersection is found. The sizes of both - * arguments are assumed to be so small, and the likelihood of an intersection so great, that it - * is not worth the CPU cost of sorting or the memory cost of hashing. + * An N*M intersection that terminates if any intersection is found. The sizes of both arguments + * are assumed to be so small, and the likelihood of an intersection so great, that it is not + * worth the CPU cost of sorting or the memory cost of hashing. */ private static boolean nonEmptyIntersection(String[] a, String[] b) { if (a == null || b == null || a.length == 0 || b.length == 0) { diff --git a/okhttp/src/main/java/okhttp3/Dispatcher.java b/okhttp/src/main/java/okhttp3/Dispatcher.java index 084a5cd9d..103ca788f 100644 --- a/okhttp/src/main/java/okhttp3/Dispatcher.java +++ b/okhttp/src/main/java/okhttp3/Dispatcher.java @@ -15,9 +15,6 @@ */ package okhttp3; -import okhttp3.RealCall.AsyncCall; -import okhttp3.internal.Util; -import okhttp3.internal.http.HttpEngine; import java.util.ArrayDeque; import java.util.Deque; import java.util.Iterator; @@ -25,13 +22,16 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import okhttp3.RealCall.AsyncCall; +import okhttp3.internal.Util; +import okhttp3.internal.http.HttpEngine; /** * Policy on when async requests are executed. * - *

Each dispatcher uses an {@link ExecutorService} to run calls internally. If you - * supply your own executor, it should be able to run {@linkplain #getMaxRequests the - * configured maximum} number of calls concurrently. + *

Each dispatcher uses an {@link ExecutorService} to run calls internally. If you supply your + * own executor, it should be able to run {@linkplain #getMaxRequests the configured maximum} number + * of calls concurrently. */ public final class Dispatcher { private int maxRequests = 64; @@ -65,11 +65,11 @@ public final class Dispatcher { } /** - * Set the maximum number of requests to execute concurrently. Above this - * requests queue in memory, waiting for the running calls to complete. + * Set the maximum number of requests to execute concurrently. Above this requests queue in + * memory, waiting for the running calls to complete. * - *

If more than {@code maxRequests} requests are in flight when this is - * invoked, those requests will remain in flight. + *

If more than {@code maxRequests} requests are in flight when this is invoked, those requests + * will remain in flight. */ public synchronized void setMaxRequests(int maxRequests) { if (maxRequests < 1) { @@ -84,13 +84,13 @@ public final class Dispatcher { } /** - * Set the maximum number of requests for each host to execute concurrently. - * This limits requests by the URL's host name. Note that concurrent requests - * to a single IP address may still exceed this limit: multiple hostnames may - * share an IP address or be routed through the same HTTP proxy. + * Set the maximum number of requests for each host to execute concurrently. This limits requests + * by the URL's host name. Note that concurrent requests to a single IP address may still exceed + * this limit: multiple hostnames may share an IP address or be routed through the same HTTP + * proxy. * - *

If more than {@code maxRequestsPerHost} requests are in flight when this - * is invoked, those requests will remain in flight. + *

If more than {@code maxRequestsPerHost} requests are in flight when this is invoked, those + * requests will remain in flight. */ public synchronized void setMaxRequestsPerHost(int maxRequestsPerHost) { if (maxRequestsPerHost < 1) { diff --git a/okhttp/src/main/java/okhttp3/Dns.java b/okhttp/src/main/java/okhttp3/Dns.java index 37cb31e31..a2e6db591 100644 --- a/okhttp/src/main/java/okhttp3/Dns.java +++ b/okhttp/src/main/java/okhttp3/Dns.java @@ -41,10 +41,9 @@ public interface Dns { }; /** - * Returns the IP addresses of {@code hostname}, in the order they will be attempted by OkHttp. - * If a connection to an address fails, OkHttp will retry the connection with the next address - * until either a connection is made, the set of IP addresses is exhausted, or a limit is - * exceeded. + * Returns the IP addresses of {@code hostname}, in the order they will be attempted by OkHttp. If + * a connection to an address fails, OkHttp will retry the connection with the next address until + * either a connection is made, the set of IP addresses is exhausted, or a limit is exceeded. */ List lookup(String hostname) throws UnknownHostException; } diff --git a/okhttp/src/main/java/okhttp3/FormBody.java b/okhttp/src/main/java/okhttp3/FormBody.java index fce955edd..95181b1f7 100644 --- a/okhttp/src/main/java/okhttp3/FormBody.java +++ b/okhttp/src/main/java/okhttp3/FormBody.java @@ -15,10 +15,10 @@ */ package okhttp3; -import okhttp3.internal.Util; import java.io.IOException; import java.util.ArrayList; import java.util.List; +import okhttp3.internal.Util; import okio.Buffer; import okio.BufferedSink; @@ -72,8 +72,8 @@ public final class FormBody extends RequestBody { /** * Either writes this request to {@code sink} or measures its content length. We have one method - * do double-duty to make sure the counting and content are consistent, particularly when it - * comes to awkward operations like measuring the encoded length of header strings, or the + * do double-duty to make sure the counting and content are consistent, particularly when it comes + * to awkward operations like measuring the encoded length of header strings, or the * length-in-digits of an encoded integer. */ private long writeOrCountBytes(BufferedSink sink, boolean countBytes) { diff --git a/okhttp/src/main/java/okhttp3/Handshake.java b/okhttp/src/main/java/okhttp3/Handshake.java index 7b4bff0f1..c3b8190df 100644 --- a/okhttp/src/main/java/okhttp3/Handshake.java +++ b/okhttp/src/main/java/okhttp3/Handshake.java @@ -26,11 +26,11 @@ import javax.net.ssl.SSLSession; import okhttp3.internal.Util; /** - * A record of a TLS handshake. For HTTPS clients, the client is local - * and the remote server is its peer. + * A record of a TLS handshake. For HTTPS clients, the client is local and the remote server + * is its peer. * - *

This value object describes a completed handshake. Use {@link - * javax.net.ssl.SSLSocketFactory} to set policy for new handshakes. + *

This value object describes a completed handshake. Use {@link javax.net.ssl.SSLSocketFactory} + * to set policy for new handshakes. */ public final class Handshake { private final TlsVersion tlsVersion; diff --git a/okhttp/src/main/java/okhttp3/Headers.java b/okhttp/src/main/java/okhttp3/Headers.java index 42cbd17ab..43f1dd1d4 100644 --- a/okhttp/src/main/java/okhttp3/Headers.java +++ b/okhttp/src/main/java/okhttp3/Headers.java @@ -17,7 +17,6 @@ package okhttp3; -import okhttp3.internal.http.HttpDate; import java.util.ArrayList; import java.util.Collections; import java.util.Date; @@ -26,24 +25,23 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; +import okhttp3.internal.http.HttpDate; /** - * The header fields of a single HTTP message. Values are uninterpreted strings; - * use {@code Request} and {@code Response} for interpreted headers. This class - * maintains the order of the header fields within the HTTP message. + * The header fields of a single HTTP message. Values are uninterpreted strings; use {@code Request} + * and {@code Response} for interpreted headers. This class maintains the order of the header fields + * within the HTTP message. * - *

This class tracks header values line-by-line. A field with multiple comma- - * separated values on the same line will be treated as a field with a single - * value by this class. It is the caller's responsibility to detect and split - * on commas if their field permits multiple values. This simplifies use of - * single-valued fields whose values routinely contain commas, such as cookies - * or dates. + *

This class tracks header values line-by-line. A field with multiple comma- separated values on + * the same line will be treated as a field with a single value by this class. It is the caller's + * responsibility to detect and split on commas if their field permits multiple values. This + * simplifies use of single-valued fields whose values routinely contain commas, such as cookies or + * dates. * - *

This class trims whitespace from values. It never returns values with - * leading or trailing whitespace. + *

This class trims whitespace from values. It never returns values with leading or trailing + * whitespace. * - *

Instances of this class are immutable. Use {@link Builder} to create - * instances. + *

Instances of this class are immutable. Use {@link Builder} to create instances. */ public final class Headers { private final String[] namesAndValues; @@ -62,9 +60,8 @@ public final class Headers { } /** - * Returns the last value corresponding to the specified field parsed as an - * HTTP date, or null if either the field is absent or cannot be parsed as a - * date. + * Returns the last value corresponding to the specified field parsed as an HTTP date, or null if + * either the field is absent or cannot be parsed as a date. */ public Date getDate(String name) { String value = get(name); @@ -155,9 +152,8 @@ public final class Headers { } /** - * Returns headers for the alternating header names and values. There must be - * an even number of arguments, and they must alternate between header names - * and values. + * Returns headers for the alternating header names and values. There must be an even number of + * arguments, and they must alternate between header names and values. */ public static Headers of(String... namesAndValues) { if (namesAndValues == null || namesAndValues.length % 2 != 0) { @@ -247,8 +243,8 @@ public final class Headers { } /** - * Add a field with the specified value without any validation. Only - * appropriate for headers from the remote peer or cache. + * Add a field with the specified value without any validation. Only appropriate for headers + * from the remote peer or cache. */ Builder addLenient(String name, String value) { namesAndValues.add(name); @@ -268,8 +264,8 @@ public final class Headers { } /** - * Set a field with the specified value. If the field is not found, it is - * added. If the field is found, the existing values are replaced. + * Set a field with the specified value. If the field is not found, it is added. If the field is + * found, the existing values are replaced. */ public Builder set(String name, String value) { checkNameAndValue(name, value); diff --git a/okhttp/src/main/java/okhttp3/HttpUrl.java b/okhttp/src/main/java/okhttp3/HttpUrl.java index e3d906a83..7259a9f01 100644 --- a/okhttp/src/main/java/okhttp3/HttpUrl.java +++ b/okhttp/src/main/java/okhttp3/HttpUrl.java @@ -84,58 +84,67 @@ import okio.Buffer; * A URL has several components. * *

Scheme

- * Sometimes referred to as protocol, A URL's scheme describes what mechanism should be used - * to retrieve the resource. Although URLs have many schemes ({@code mailto}, {@code file}, {@code - * ftp}), this class only supports {@code http} and {@code https}. Use {@link URI java.net.URI} for - * URLs with arbitrary schemes. + * + *

Sometimes referred to as protocol, A URL's scheme describes what mechanism should be + * used to retrieve the resource. Although URLs have many schemes ({@code mailto}, {@code file}, + * {@code ftp}), this class only supports {@code http} and {@code https}. Use {@link URI + * java.net.URI} for URLs with arbitrary schemes. * *

Username and Password

- * Username and password are either present, or the empty string {@code ""} if absent. This class + * + *

Username and password are either present, or the empty string {@code ""} if absent. This class * offers no mechanism to differentiate empty from absent. Neither of these components are popular * in practice. Typically HTTP applications use other mechanisms for user identification and * authentication. * *

Host

- * The host identifies the webserver that serves the URL's resource. It is either a hostname like + * + *

The host identifies the webserver that serves the URL's resource. It is either a hostname like * {@code square.com} or {@code localhost}, an IPv4 address like {@code 192.168.0.1}, or an IPv6 * address like {@code ::1}. * *

Usually a webserver is reachable with multiple identifiers: its IP addresses, registered * domain names, and even {@code localhost} when connecting from the server itself. Each of a - * webserver's names is a distinct URL and they are not interchangeable. For example, even if - * {@code http://square.github.io/dagger} and {@code http://google.github.io/dagger} are served by - * the same IP address, the two URLs identify different resources. + * webserver's names is a distinct URL and they are not interchangeable. For example, even if {@code + * http://square.github.io/dagger} and {@code http://google.github.io/dagger} are served by the same + * IP address, the two URLs identify different resources. * *

Port

- * The port used to connect to the webserver. By default this is 80 for HTTP and 443 for HTTPS. This - * class never returns -1 for the port: if no port is explicitly specified in the URL then the + * + *

The port used to connect to the webserver. By default this is 80 for HTTP and 443 for HTTPS. + * This class never returns -1 for the port: if no port is explicitly specified in the URL then the * scheme's default is used. * *

Path

- * The path identifies a specific resource on the host. Paths have a hierarchical structure like + * + *

The path identifies a specific resource on the host. Paths have a hierarchical structure like * "/square/okhttp/issues/1486". Each path segment is prefixed with "/". This class offers methods * to compose and decompose paths by segment. If a path's last segment is the empty string, then the * path ends with "/". This class always builds non-empty paths: if the path is omitted it defaults * to "/", which is a path whose only segment is the empty string. * *

Query

- * The query is optional: it can be null, empty, or non-empty. For many HTTP URLs the query string - * is subdivided into a collection of name-value parameters. This class offers methods to set the - * query as the single string, or as individual name-value parameters. With name-value parameters - * the values are optional and names may be repeated. + * + *

The query is optional: it can be null, empty, or non-empty. For many HTTP URLs the query + * string is subdivided into a collection of name-value parameters. This class offers methods to set + * the query as the single string, or as individual name-value parameters. With name-value + * parameters the values are optional and names may be repeated. * *

Fragment

- * The fragment is optional: it can be null, empty, or non-empty. Unlike host, port, path, and query - * the fragment is not sent to the webserver: it's private to the client. + * + *

The fragment is optional: it can be null, empty, or non-empty. Unlike host, port, path, and + * query the fragment is not sent to the webserver: it's private to the client. * *

Encoding

- * Each component must be encoded before it is embedded in the complete URL. As we saw above, the + * + *

Each component must be encoded before it is embedded in the complete URL. As we saw above, the * string {@code cute #puppies} is encoded as {@code cute%20%23puppies} when used as a query * parameter value. * *

Percent encoding

- * Percent encoding replaces a character (like {@code \ud83c\udf69}) with its UTF-8 hex bytes (like - * {@code %F0%9F%8D%A9}). This approach works for whitespace characters, control characters, + * + *

Percent encoding replaces a character (like {@code \ud83c\udf69}) with its UTF-8 hex bytes + * (like {@code %F0%9F%8D%A9}). This approach works for whitespace characters, control characters, * non-ASCII characters, and characters that already have another meaning in a particular context. * *

Percent encoding is used in every URL component except for the hostname. But the set of @@ -161,11 +170,12 @@ import okio.Buffer; * the offending characters. * *

IDNA Mapping and Punycode encoding

- * Hostnames have different requirements and use a different encoding scheme. It consists of IDNA + * + *

Hostnames have different requirements and use a different encoding scheme. It consists of IDNA * mapping and Punycode encoding. * - *

In order to avoid confusion and discourage phishing attacks, - * IDNA Mapping transforms names to avoid + *

In order to avoid confusion and discourage phishing attacks, IDNA Mapping transforms names to avoid * confusing characters. This includes basic case folding: transforming shouting {@code SQUARE.COM} * into cool and casual {@code square.com}. It also handles more exotic characters. For example, the * Unicode trademark sign (â„¢) could be confused for the letters "TM" in {@code http://hoâ„¢mail.com}. @@ -174,21 +184,25 @@ import okio.Buffer; * not mapped and cannot be used in a hostname. * *

Punycode converts a Unicode string to an ASCII - * string to make international domain names work everywhere. For example, "σ" encodes as - * "xn--4xa". The encoded string is not human readable, but can be used with classes like {@link - * InetAddress} to establish connections. + * string to make international domain names work everywhere. For example, "σ" encodes as "xn--4xa". + * The encoded string is not human readable, but can be used with classes like {@link InetAddress} + * to establish connections. * *

Why another URL model?

- * Java includes both {@link URL java.net.URL} and {@link URI java.net.URI}. We offer a new URL + * + *

Java includes both {@link URL java.net.URL} and {@link URI java.net.URI}. We offer a new URL * model to address problems that the others don't. * *

Different URLs should be different

- * Although they have different content, {@code java.net.URL} considers the following two URLs + * + *

Although they have different content, {@code java.net.URL} considers the following two URLs * equal, and the {@link Object#equals equals()} method between them returns true: + * *

    *
  • http://square.github.io/ *
  • http://google.github.io/ *
+ * * This is because those two hosts share the same IP address. This is an old, bad design decision * that makes {@code java.net.URL} unusable for many things. It shouldn't be used as a {@link * java.util.Map Map} key or in a {@link Set}. Doing so is both inefficient because equality may @@ -196,11 +210,14 @@ import okio.Buffer; * hosted. * *

Equal URLs should be equal

- * These two URLs are semantically identical, but {@code java.net.URI} disagrees: + * + *

These two URLs are semantically identical, but {@code java.net.URI} disagrees: + * *

    *
  • http://host:80/ *
  • http://host *
+ * * Both the unnecessary port specification ({@code :80}) and the absent trailing slash ({@code /}) * cause URI to bucket the two URLs separately. This harms URI's usefulness in collections. Any * application that stores information-per-URL will need to either canonicalize manually, or suffer @@ -226,21 +243,24 @@ import okio.Buffer; * }
* *

If it works on the web, it should work in your application

- * The {@code java.net.URI} class is strict around what URLs it accepts. It rejects URLs like + * + *

The {@code java.net.URI} class is strict around what URLs it accepts. It rejects URLs like * "http://example.com/abc|def" because the '|' character is unsupported. This class is more * forgiving: it will automatically percent-encode the '|', yielding "http://example.com/abc%7Cdef". * This kind behavior is consistent with web browsers. {@code HttpUrl} prefers consistency with * major web browsers over consistency with obsolete specifications. * *

Paths and Queries should decompose

- * Neither of the built-in URL models offer direct access to path segments or query parameters. + * + *

Neither of the built-in URL models offer direct access to path segments or query parameters. * Manually using {@code StringBuilder} to assemble these components is cumbersome: do '+' * characters get silently replaced with spaces? If a query parameter contains a '&', does that * get escaped? By offering methods to read and write individual query parameters directly, * application developers are saved from the hassles of encoding and decoding. * *

Plus a modern API

- * The URL (JDK1.0) and URI (Java 1.4) classes predate builders and instead use telescoping + * + *

The URL (JDK1.0) and URI (Java 1.4) classes predate builders and instead use telescoping * constructors. For example, there's no API to compose a URI with a custom port without also * providing a query and fragment. * @@ -254,7 +274,7 @@ import okio.Buffer; */ public final class HttpUrl { private static final char[] HEX_DIGITS = - { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; static final String USERNAME_ENCODE_SET = " \"':;<=>@[]^`{}|/\\?#"; static final String PASSWORD_ENCODE_SET = " \"':;<=>@[]^`{}|/\\?#"; static final String PATH_SEGMENT_ENCODE_SET = " \"<>^`{}|/\\?#"; @@ -282,9 +302,9 @@ public final class HttpUrl { private final int port; /** - * A list of canonical path segments. This list always contains at least one element, which may - * be the empty string. Each segment is formatted with a leading '/', so if path segments were - * ["a", "b", ""], then the encoded path would be "/a/b/". + * A list of canonical path segments. This list always contains at least one element, which may be + * the empty string. Each segment is formatted with a leading '/', so if path segments were ["a", + * "b", ""], then the encoded path would be "/a/b/". */ private final List pathSegments; @@ -329,10 +349,11 @@ public final class HttpUrl { /** * Returns this URL as a {@link URI java.net.URI}. Because {@code URI} is more strict than this * class, the returned URI may be semantically different from this URL: + * *

    - *
  • Characters forbidden by URI like {@code [} and {@code |} will be escaped. - *
  • Invalid percent-encoded sequences like {@code %xx} will be encoded like {@code %25xx}. - *
  • Whitespace and control characters in the fragment will be stripped. + *
  • Characters forbidden by URI like {@code [} and {@code |} will be escaped. + *
  • Invalid percent-encoded sequences like {@code %xx} will be encoded like {@code %25xx}. + *
  • Whitespace and control characters in the fragment will be stripped. *
* *

These differences may have a significant consequence when the URI is interpretted by a @@ -390,6 +411,7 @@ public final class HttpUrl { /** * Returns the host address suitable for use with {@link InetAddress#getAllByName(String)}. May * be: + * *

    *
  • A regular host name, like {@code android.com}. *
  • An IPv4 address, like {@code 127.0.0.1}. @@ -429,8 +451,8 @@ public final class HttpUrl { } /** - * Returns the entire path of this URL, encoded for use in HTTP resource resolution. The - * returned path is always nonempty and is prefixed with {@code /}. + * Returns the entire path of this URL, encoded for use in HTTP resource resolution. The returned + * path is always nonempty and is prefixed with {@code /}. */ public String encodedPath() { int pathStart = url.indexOf('/', scheme.length() + 3); // "://".length() == 3. @@ -488,10 +510,10 @@ public final class HttpUrl { } /** - * Cuts {@code encodedQuery} up into alternating parameter names and values. This divides a - * query string like {@code subject=math&easy&problem=5-2=3} into the list {@code ["subject", - * "math", "easy", null, "problem", "5-2=3"]}. Note that values may be null and may contain - * '=' characters. + * Cuts {@code encodedQuery} up into alternating parameter names and values. This divides a query + * string like {@code subject=math&easy&problem=5-2=3} into the list {@code ["subject", "math", + * "easy", null, "problem", "5-2=3"]}. Note that values may be null and may contain '=' + * characters. */ static List queryStringToNamesAndValues(String encodedQuery) { List result = new ArrayList<>(); @@ -709,7 +731,7 @@ public final class HttpUrl { /** * @param host either a regular hostname, International Domain Name, IPv4 address, or IPv6 - * address. + * address. */ public Builder host(String host) { if (host == null) throw new IllegalArgumentException("host == null"); @@ -787,7 +809,7 @@ public final class HttpUrl { public Builder query(String query) { this.encodedQueryNamesAndValues = query != null ? queryStringToNamesAndValues(canonicalize( - query, QUERY_ENCODE_SET, false, false, true, true)) + query, QUERY_ENCODE_SET, false, false, true, true)) : null; return this; } @@ -795,7 +817,7 @@ public final class HttpUrl { public Builder encodedQuery(String encodedQuery) { this.encodedQueryNamesAndValues = encodedQuery != null ? queryStringToNamesAndValues( - canonicalize(encodedQuery, QUERY_ENCODE_SET, true, false, true, true)) + canonicalize(encodedQuery, QUERY_ENCODE_SET, true, false, true, true)) : null; return this; } @@ -1150,8 +1172,8 @@ public final class HttpUrl { * Removes a path segment. When this method returns the last segment is always "", which means * the encoded path will have a trailing '/'. * - *

    Popping "/a/b/c/" yields "/a/b/". In this case the list of path segments goes from - * ["a", "b", "c", ""] to ["a", "b", ""]. + *

    Popping "/a/b/c/" yields "/a/b/". In this case the list of path segments goes from ["a", + * "b", "c", ""] to ["a", "b", ""]. * *

    Popping "/a/b/c" also yields "/a/b/". The list of path segments goes from ["a", "b", "c"] * to ["a", "b", ""]. diff --git a/okhttp/src/main/java/okhttp3/Interceptor.java b/okhttp/src/main/java/okhttp3/Interceptor.java index e18440cc7..94effbdf4 100644 --- a/okhttp/src/main/java/okhttp3/Interceptor.java +++ b/okhttp/src/main/java/okhttp3/Interceptor.java @@ -27,7 +27,9 @@ public interface Interceptor { interface Chain { Request request(); + Response proceed(Request request) throws IOException; + Connection connection(); } } diff --git a/okhttp/src/main/java/okhttp3/MediaType.java b/okhttp/src/main/java/okhttp3/MediaType.java index 805d1c7d6..bbdcedf68 100644 --- a/okhttp/src/main/java/okhttp3/MediaType.java +++ b/okhttp/src/main/java/okhttp3/MediaType.java @@ -21,8 +21,8 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; /** - * An RFC 2045 Media Type, - * appropriate to describe the content type of an HTTP request or response body. + * An RFC 2045 Media Type, appropriate to describe + * the content type of an HTTP request or response body. */ public final class MediaType { private static final String TOKEN = "([a-zA-Z0-9-!#$%&'*+.^_`{|}~]+)"; @@ -44,8 +44,8 @@ public final class MediaType { } /** - * Returns a media type for {@code string}, or null if {@code string} is not a - * well-formed media type. + * Returns a media type for {@code string}, or null if {@code string} is not a well-formed media + * type. */ public static MediaType parse(String string) { Matcher typeSubtype = TYPE_SUBTYPE.matcher(string); @@ -74,40 +74,38 @@ public final class MediaType { } /** - * Returns the high-level media type, such as "text", "image", "audio", - * "video", or "application". + * Returns the high-level media type, such as "text", "image", "audio", "video", or + * "application". */ public String type() { return type; } /** - * Returns a specific media subtype, such as "plain" or "png", "mpeg", - * "mp4" or "xml". + * Returns a specific media subtype, such as "plain" or "png", "mpeg", "mp4" or "xml". */ public String subtype() { return subtype; } /** - * Returns the charset of this media type, or null if this media type doesn't - * specify a charset. + * Returns the charset of this media type, or null if this media type doesn't specify a charset. */ public Charset charset() { return charset != null ? Charset.forName(charset) : null; } /** - * Returns the charset of this media type, or {@code defaultValue} if this - * media type doesn't specify a charset. + * Returns the charset of this media type, or {@code defaultValue} if this media type doesn't + * specify a charset. */ public Charset charset(Charset defaultValue) { return charset != null ? Charset.forName(charset) : defaultValue; } /** - * Returns the encoded media type, like "text/plain; charset=utf-8", - * appropriate for use in a Content-Type header. + * Returns the encoded media type, like "text/plain; charset=utf-8", appropriate for use in a + * Content-Type header. */ @Override public String toString() { return mediaType; diff --git a/okhttp/src/main/java/okhttp3/MultipartBody.java b/okhttp/src/main/java/okhttp3/MultipartBody.java index 57f6095d4..7ac584d1d 100644 --- a/okhttp/src/main/java/okhttp3/MultipartBody.java +++ b/okhttp/src/main/java/okhttp3/MultipartBody.java @@ -15,11 +15,11 @@ */ package okhttp3; -import okhttp3.internal.Util; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.UUID; +import okhttp3.internal.Util; import okio.Buffer; import okio.BufferedSink; import okio.ByteString; @@ -27,46 +27,42 @@ import okio.ByteString; /** An RFC 2387-compliant request body. */ public final class MultipartBody extends RequestBody { /** - * The "mixed" subtype of "multipart" is intended for use when the body - * parts are independent and need to be bundled in a particular order. Any - * "multipart" subtypes that an implementation does not recognize must be - * treated as being of subtype "mixed". + * The "mixed" subtype of "multipart" is intended for use when the body parts are independent and + * need to be bundled in a particular order. Any "multipart" subtypes that an implementation does + * not recognize must be treated as being of subtype "mixed". */ public static final MediaType MIXED = MediaType.parse("multipart/mixed"); /** - * The "multipart/alternative" type is syntactically identical to - * "multipart/mixed", but the semantics are different. In particular, each - * of the body parts is an "alternative" version of the same information. + * The "multipart/alternative" type is syntactically identical to "multipart/mixed", but the + * semantics are different. In particular, each of the body parts is an "alternative" version of + * the same information. */ public static final MediaType ALTERNATIVE = MediaType.parse("multipart/alternative"); /** - * This type is syntactically identical to "multipart/mixed", but the - * semantics are different. In particular, in a digest, the default {@code - * Content-Type} value for a body part is changed from "text/plain" to - * "message/rfc822". + * This type is syntactically identical to "multipart/mixed", but the semantics are different. In + * particular, in a digest, the default {@code Content-Type} value for a body part is changed from + * "text/plain" to "message/rfc822". */ public static final MediaType DIGEST = MediaType.parse("multipart/digest"); /** - * This type is syntactically identical to "multipart/mixed", but the - * semantics are different. In particular, in a parallel entity, the order - * of body parts is not significant. + * This type is syntactically identical to "multipart/mixed", but the semantics are different. In + * particular, in a parallel entity, the order of body parts is not significant. */ public static final MediaType PARALLEL = MediaType.parse("multipart/parallel"); /** - * The media-type multipart/form-data follows the rules of all multipart - * MIME data streams as outlined in RFC 2046. In forms, there are a series - * of fields to be supplied by the user who fills out the form. Each field - * has a name. Within a given form, the names are unique. + * The media-type multipart/form-data follows the rules of all multipart MIME data streams as + * outlined in RFC 2046. In forms, there are a series of fields to be supplied by the user who + * fills out the form. Each field has a name. Within a given form, the names are unique. */ public static final MediaType FORM = MediaType.parse("multipart/form-data"); - private static final byte[] COLONSPACE = { ':', ' ' }; - private static final byte[] CRLF = { '\r', '\n' }; - private static final byte[] DASHDASH = { '-', '-' }; + private static final byte[] COLONSPACE = {':', ' '}; + private static final byte[] CRLF = {'\r', '\n'}; + private static final byte[] DASHDASH = {'-', '-'}; private final ByteString boundary; private final MediaType originalType; @@ -119,8 +115,8 @@ public final class MultipartBody extends RequestBody { /** * Either writes this request to {@code sink} or measures its content length. We have one method - * do double-duty to make sure the counting and content are consistent, particularly when it - * comes to awkward operations like measuring the encoded length of header strings, or the + * do double-duty to make sure the counting and content are consistent, particularly when it comes + * to awkward operations like measuring the encoded length of header strings, or the * length-in-digits of an encoded integer. */ private long writeOrCountBytes(BufferedSink sink, boolean countBytes) throws IOException { @@ -194,13 +190,12 @@ public final class MultipartBody extends RequestBody { /** * Appends a quoted-string to a StringBuilder. * - *

    RFC 2388 is rather vague about how one should escape special characters - * in form-data parameters, and as it turns out Firefox and Chrome actually - * do rather different things, and both say in their comments that they're - * not really sure what the right approach is. We go with Chrome's behavior - * (which also experimentally seems to match what IE does), but if you - * actually want to have a good chance of things working, please avoid - * double-quotes, newlines, percent signs, and the like in your field names. + *

    RFC 2388 is rather vague about how one should escape special characters in form-data + * parameters, and as it turns out Firefox and Chrome actually do rather different things, and + * both say in their comments that they're not really sure what the right approach is. We go with + * Chrome's behavior (which also experimentally seems to match what IE does), but if you actually + * want to have a good chance of things working, please avoid double-quotes, newlines, percent + * signs, and the like in your field names. */ static StringBuilder appendQuotedString(StringBuilder target, String key) { target.append('"'); @@ -225,7 +220,6 @@ public final class MultipartBody extends RequestBody { return target; } - public static final class Part { public static Part create(RequestBody body) { return create(null, body); @@ -286,9 +280,8 @@ public final class MultipartBody extends RequestBody { } /** - * Set the MIME type. Expected values for {@code type} are {@link #MIXED} (the - * default), {@link #ALTERNATIVE}, {@link #DIGEST}, {@link #PARALLEL} and - * {@link #FORM}. + * Set the MIME type. Expected values for {@code type} are {@link #MIXED} (the default), {@link + * #ALTERNATIVE}, {@link #DIGEST}, {@link #PARALLEL} and {@link #FORM}. */ public Builder setType(MediaType type) { if (type == null) { diff --git a/okhttp/src/main/java/okhttp3/OkHttpClient.java b/okhttp/src/main/java/okhttp3/OkHttpClient.java index 416df41ce..673b35b89 100644 --- a/okhttp/src/main/java/okhttp3/OkHttpClient.java +++ b/okhttp/src/main/java/okhttp3/OkHttpClient.java @@ -40,15 +40,14 @@ import okhttp3.internal.io.RealConnection; import okhttp3.internal.tls.OkHostnameVerifier; /** - * Configures and creates HTTP connections. Most applications can use a single - * OkHttpClient for all of their HTTP requests - benefiting from a shared - * response cache, thread pool, connection re-use, etc. + * Configures and creates HTTP connections. Most applications can use a single OkHttpClient for all + * of their HTTP requests - benefiting from a shared response cache, thread pool, connection re-use, + * etc. * - *

    Instances of OkHttpClient are intended to be fully configured before they're - * shared - once shared they should be treated as immutable and can safely be used - * to concurrently open new connections. If required, threads can call - * {@link #clone()} to make a shallow copy of the OkHttpClient that can be - * safely modified with further configuration changes. + *

    Instances of OkHttpClient are intended to be fully configured before they're shared - once + * shared they should be treated as immutable and can safely be used to concurrently open new + * connections. If required, threads can call {@link #clone()} to make a shallow copy of the + * OkHttpClient that can be safely modified with further configuration changes. */ public class OkHttpClient implements Cloneable, Call.Factory { private static final List DEFAULT_PROTOCOLS = Util.immutableList( @@ -241,10 +240,9 @@ public class OkHttpClient implements Cloneable, Call.Factory { } /** - * Sets the HTTP proxy that will be used by connections created by this - * client. This takes precedence over {@link #setProxySelector}, which is - * only honored when this proxy is null (which it is by default). To disable - * proxy use completely, call {@code setProxy(Proxy.NO_PROXY)}. + * Sets the HTTP proxy that will be used by connections created by this client. This takes + * precedence over {@link #setProxySelector}, which is only honored when this proxy is null (which + * it is by default). To disable proxy use completely, call {@code setProxy(Proxy.NO_PROXY)}. */ public OkHttpClient setProxy(Proxy proxy) { this.proxy = proxy; @@ -256,13 +254,12 @@ public class OkHttpClient implements Cloneable, Call.Factory { } /** - * Sets the proxy selection policy to be used if no {@link #setProxy proxy} - * is specified explicitly. The proxy selector may return multiple proxies; - * in that case they will be tried in sequence until a successful connection - * is established. + * Sets the proxy selection policy to be used if no {@link #setProxy proxy} is specified + * explicitly. The proxy selector may return multiple proxies; in that case they will be tried in + * sequence until a successful connection is established. * - *

    If unset, the {@link ProxySelector#getDefault() system-wide default} - * proxy selector will be used. + *

    If unset, the {@link ProxySelector#getDefault() system-wide default} proxy selector will be + * used. */ public OkHttpClient setProxySelector(ProxySelector proxySelector) { this.proxySelector = proxySelector; @@ -274,11 +271,10 @@ public class OkHttpClient implements Cloneable, Call.Factory { } /** - * Sets the cookie handler to be used to read outgoing cookies and write - * incoming cookies. + * Sets the cookie handler to be used to read outgoing cookies and write incoming cookies. * - *

    If unset, the {@link CookieHandler#getDefault() system-wide default} - * cookie handler will be used. + *

    If unset, the {@link CookieHandler#getDefault() system-wide default} cookie handler will be + * used. */ public OkHttpClient setCookieHandler(CookieHandler cookieHandler) { this.cookieHandler = cookieHandler; @@ -324,13 +320,12 @@ public class OkHttpClient implements Cloneable, Call.Factory { } /** - * Sets the socket factory used to create connections. OkHttp only uses - * the parameterless {@link SocketFactory#createSocket() createSocket()} - * method to create unconnected sockets. Overriding this method, - * e. g., allows the socket to be bound to a specific local address. + * Sets the socket factory used to create connections. OkHttp only uses the parameterless {@link + * SocketFactory#createSocket() createSocket()} method to create unconnected sockets. Overriding + * this method, e. g., allows the socket to be bound to a specific local address. * - *

    If unset, the {@link SocketFactory#getDefault() system-wide default} - * socket factory will be used. + *

    If unset, the {@link SocketFactory#getDefault() system-wide default} socket factory will be + * used. */ public OkHttpClient setSocketFactory(SocketFactory socketFactory) { this.socketFactory = socketFactory; @@ -356,8 +351,8 @@ public class OkHttpClient implements Cloneable, Call.Factory { } /** - * Sets the verifier used to confirm that response certificates apply to - * requested hostnames for HTTPS connections. + * Sets the verifier used to confirm that response certificates apply to requested hostnames for + * HTTPS connections. * *

    If unset, a default hostname verifier will be used. */ @@ -371,10 +366,9 @@ public class OkHttpClient implements Cloneable, Call.Factory { } /** - * Sets the certificate pinner that constrains which certificates are trusted. - * By default HTTPS connections rely on only the {@link #setSslSocketFactory - * SSL socket factory} to establish trust. Pinning certificates avoids the - * need to trust certificate authorities. + * Sets the certificate pinner that constrains which certificates are trusted. By default HTTPS + * connections rely on only the {@link #setSslSocketFactory SSL socket factory} to establish + * trust. Pinning certificates avoids the need to trust certificate authorities. */ public OkHttpClient setCertificatePinner(CertificatePinner certificatePinner) { this.certificatePinner = certificatePinner; @@ -420,8 +414,8 @@ public class OkHttpClient implements Cloneable, Call.Factory { /** * Sets the connection pool used to recycle HTTP and HTTPS connections. * - *

    If unset, the {@link ConnectionPool#getDefault() system-wide - * default} connection pool will be used. + *

    If unset, the {@link ConnectionPool#getDefault() system-wide default} connection pool will + * be used. */ public OkHttpClient setConnectionPool(ConnectionPool connectionPool) { this.connectionPool = connectionPool; @@ -433,11 +427,10 @@ public class OkHttpClient implements Cloneable, Call.Factory { } /** - * Configure this client to follow redirects from HTTPS to HTTP and from HTTP - * to HTTPS. + * Configure this client to follow redirects from HTTPS to HTTP and from HTTP to HTTPS. * - *

    If unset, protocol redirects will be followed. This is different than - * the built-in {@code HttpURLConnection}'s default. + *

    If unset, protocol redirects will be followed. This is different than the built-in {@code + * HttpURLConnection}'s default. */ public OkHttpClient setFollowSslRedirects(boolean followProtocolRedirects) { this.followSslRedirects = followProtocolRedirects; @@ -490,8 +483,7 @@ public class OkHttpClient implements Cloneable, Call.Factory { } /** - * Sets the dispatcher used to set policy and execute asynchronous requests. - * Must not be null. + * Sets the dispatcher used to set policy and execute asynchronous requests. Must not be null. */ public OkHttpClient setDispatcher(Dispatcher dispatcher) { if (dispatcher == null) throw new IllegalArgumentException("dispatcher == null"); @@ -504,34 +496,32 @@ public class OkHttpClient implements Cloneable, Call.Factory { } /** - * Configure the protocols used by this client to communicate with remote - * servers. By default this client will prefer the most efficient transport - * available, falling back to more ubiquitous protocols. Applications should - * only call this method to avoid specific compatibility problems, such as web - * servers that behave incorrectly when SPDY is enabled. + * Configure the protocols used by this client to communicate with remote servers. By default this + * client will prefer the most efficient transport available, falling back to more ubiquitous + * protocols. Applications should only call this method to avoid specific compatibility problems, + * such as web servers that behave incorrectly when SPDY is enabled. * *

    The following protocols are currently supported: + * *

    * - *

    This is an evolving set. Future releases include - * support for transitional protocols. The http/1.1 transport will never be - * dropped. + *

    This is an evolving set. Future releases include support for transitional + * protocols. The http/1.1 transport will never be dropped. * *

    If multiple protocols are specified, ALPN - * will be used to negotiate a transport. + * href="http://tools.ietf.org/html/draft-ietf-tls-applayerprotoneg">ALPN will be used to + * negotiate a transport. * - *

    {@link Protocol#HTTP_1_0} is not supported in this set. Requests are - * initiated with {@code HTTP/1.1} only. If the server responds with {@code - * HTTP/1.0}, that will be exposed by {@link Response#protocol()}. + *

    {@link Protocol#HTTP_1_0} is not supported in this set. Requests are initiated with {@code + * HTTP/1.1} only. If the server responds with {@code HTTP/1.0}, that will be exposed by {@link + * Response#protocol()}. * - * @param protocols the protocols to use, in order of preference. The list - * must contain {@link Protocol#HTTP_1_1}. It must not contain null or - * {@link Protocol#HTTP_1_0}. + * @param protocols the protocols to use, in order of preference. The list must contain {@link + * Protocol#HTTP_1_1}. It must not contain null or {@link Protocol#HTTP_1_0}. */ public OkHttpClient setProtocols(List protocols) { protocols = Util.immutableList(protocols); @@ -587,8 +577,8 @@ public class OkHttpClient implements Cloneable, Call.Factory { } /** - * Cancels all scheduled or in-flight calls tagged with {@code tag}. Requests - * that are already complete cannot be canceled. + * Cancels all scheduled or in-flight calls tagged with {@code tag}. Requests that are already + * complete cannot be canceled. */ public OkHttpClient cancel(Object tag) { getDispatcher().cancel(tag); @@ -596,8 +586,8 @@ public class OkHttpClient implements Cloneable, Call.Factory { } /** - * Returns a shallow copy of this OkHttpClient that uses the system-wide - * default for each field that hasn't been explicitly configured. + * Returns a shallow copy of this OkHttpClient that uses the system-wide default for each field + * that hasn't been explicitly configured. */ OkHttpClient copyWithDefaults() { OkHttpClient result = new OkHttpClient(this); @@ -641,15 +631,13 @@ public class OkHttpClient implements Cloneable, Call.Factory { } /** - * Java and Android programs default to using a single global SSL context, - * accessible to HTTP clients as {@link SSLSocketFactory#getDefault()}. If we - * used the shared SSL context, when OkHttp enables ALPN for its SPDY-related - * stuff, it would also enable ALPN for other usages, which might crash them - * because ALPN is enabled when it isn't expected to be. + * Java and Android programs default to using a single global SSL context, accessible to HTTP + * clients as {@link SSLSocketFactory#getDefault()}. If we used the shared SSL context, when + * OkHttp enables ALPN for its SPDY-related stuff, it would also enable ALPN for other usages, + * which might crash them because ALPN is enabled when it isn't expected to be. * - *

    This code avoids that by defaulting to an OkHttp-created SSL context. - * The drawback of this approach is that apps that customize the global SSL - * context will lose these customizations. + *

    This code avoids that by defaulting to an OkHttp-created SSL context. The drawback of this + * approach is that apps that customize the global SSL context will lose these customizations. */ private synchronized SSLSocketFactory getDefaultSSLSocketFactory() { if (defaultSslSocketFactory == null) { diff --git a/okhttp/src/main/java/okhttp3/Protocol.java b/okhttp/src/main/java/okhttp3/Protocol.java index 6bb47c6f3..eec1c1219 100644 --- a/okhttp/src/main/java/okhttp3/Protocol.java +++ b/okhttp/src/main/java/okhttp3/Protocol.java @@ -19,52 +19,45 @@ import java.io.IOException; /** * Protocols that OkHttp implements for ALPN - * selection. + * href="http://tools.ietf.org/html/draft-ietf-tls-applayerprotoneg">ALPN selection. * - *

    Protocol vs Scheme

    - * Despite its name, {@link java.net.URL#getProtocol()} returns the - * {@linkplain java.net.URI#getScheme() scheme} (http, https, etc.) of the URL, not - * the protocol (http/1.1, spdy/3.1, etc.). OkHttp uses the word protocol - * to identify how HTTP messages are framed. + *

    Protocol vs Scheme

    Despite its name, {@link java.net.URL#getProtocol()} returns the + * {@linkplain java.net.URI#getScheme() scheme} (http, https, etc.) of the URL, not the protocol + * (http/1.1, spdy/3.1, etc.). OkHttp uses the word protocol to identify how HTTP messages + * are framed. */ public enum Protocol { /** - * An obsolete plaintext framing that does not use persistent sockets by - * default. + * An obsolete plaintext framing that does not use persistent sockets by default. */ HTTP_1_0("http/1.0"), /** * A plaintext framing that includes persistent connections. * - *

    This version of OkHttp implements RFC 2616, and tracks - * revisions to that spec. + *

    This version of OkHttp implements RFC + * 2616, and tracks revisions to that spec. */ HTTP_1_1("http/1.1"), /** - * Chromium's binary-framed protocol that includes header compression, - * multiplexing multiple requests on the same socket, and server-push. - * HTTP/1.1 semantics are layered on SPDY/3. + * Chromium's binary-framed protocol that includes header compression, multiplexing multiple + * requests on the same socket, and server-push. HTTP/1.1 semantics are layered on SPDY/3. * *

    This version of OkHttp implements SPDY 3 draft - * 3.1. Future releases of OkHttp may use this identifier for a newer draft - * of the SPDY spec. + * href="http://dev.chromium.org/spdy/spdy-protocol/spdy-protocol-draft3-1">draft 3.1. Future + * releases of OkHttp may use this identifier for a newer draft of the SPDY spec. */ SPDY_3("spdy/3.1"), /** - * The IETF's binary-framed protocol that includes header compression, - * multiplexing multiple requests on the same socket, and server-push. - * HTTP/1.1 semantics are layered on HTTP/2. + * The IETF's binary-framed protocol that includes header compression, multiplexing multiple + * requests on the same socket, and server-push. HTTP/1.1 semantics are layered on HTTP/2. * - *

    HTTP/2 requires deployments of HTTP/2 that use TLS 1.2 support - * {@linkplain CipherSuite#TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256} - * , present in Java 8+ and Android 5+. Servers that enforce this may send an - * exception message including the string {@code INADEQUATE_SECURITY}. + *

    HTTP/2 requires deployments of HTTP/2 that use TLS 1.2 support {@linkplain + * CipherSuite#TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256} , present in Java 8+ and Android 5+. Servers + * that enforce this may send an exception message including the string {@code + * INADEQUATE_SECURITY}. */ HTTP_2("h2"); @@ -76,6 +69,7 @@ public enum Protocol { /** * Returns the protocol identified by {@code protocol}. + * * @throws IOException if {@code protocol} is unknown. */ public static Protocol get(String protocol) throws IOException { @@ -88,8 +82,8 @@ public enum Protocol { } /** - * Returns the string used to identify this protocol for ALPN, like - * "http/1.1", "spdy/3.1" or "h2". + * Returns the string used to identify this protocol for ALPN, like "http/1.1", "spdy/3.1" or + * "h2". */ @Override public String toString() { return protocol; diff --git a/okhttp/src/main/java/okhttp3/RealCall.java b/okhttp/src/main/java/okhttp3/RealCall.java index ab8202819..302ab001a 100644 --- a/okhttp/src/main/java/okhttp3/RealCall.java +++ b/okhttp/src/main/java/okhttp3/RealCall.java @@ -199,8 +199,7 @@ final class RealCall implements Call { } /** - * Performs the request and returns the response. May return null if this - * call was canceled. + * Performs the request and returns the response. May return null if this call was canceled. */ Response getResponse(Request request, boolean forWebSocket) throws IOException { // Copy body metadata to the appropriate request headers. diff --git a/okhttp/src/main/java/okhttp3/Request.java b/okhttp/src/main/java/okhttp3/Request.java index 4ff870230..2daa0ab9b 100644 --- a/okhttp/src/main/java/okhttp3/Request.java +++ b/okhttp/src/main/java/okhttp3/Request.java @@ -15,14 +15,14 @@ */ package okhttp3; -import okhttp3.internal.http.HttpMethod; import java.net.URI; import java.net.URL; import java.util.List; +import okhttp3.internal.http.HttpMethod; /** - * An HTTP request. Instances of this class are immutable if their {@link #body} - * is null or itself immutable. + * An HTTP request. Instances of this class are immutable if their {@link #body} is null or itself + * immutable. */ public final class Request { private final HttpUrl url; @@ -75,8 +75,8 @@ public final class Request { } /** - * Returns the cache control directives for this response. This is never null, - * even if this response contains no {@code Cache-Control} header. + * Returns the cache control directives for this response. This is never null, even if this + * response contains no {@code Cache-Control} header. */ public CacheControl cacheControl() { CacheControl result = cacheControl; @@ -127,7 +127,7 @@ public final class Request { * Sets the URL target of this request. * * @throws IllegalArgumentException if {@code url} is not a valid HTTP or HTTPS URL. Avoid this - * exception by calling {@link HttpUrl#parse}; it returns null for invalid URLs. + * exception by calling {@link HttpUrl#parse}; it returns null for invalid URLs. */ public Builder url(String url) { if (url == null) throw new IllegalArgumentException("url == null"); @@ -148,7 +148,7 @@ public final class Request { * Sets the URL target of this request. * * @throws IllegalArgumentException if the scheme of {@code url} is not {@code http} or {@code - * https}. + * https}. */ public Builder url(URL url) { if (url == null) throw new IllegalArgumentException("url == null"); @@ -158,8 +158,8 @@ public final class Request { } /** - * Sets the header named {@code name} to {@code value}. If this request - * already has any headers with that name, they are all replaced. + * Sets the header named {@code name} to {@code value}. If this request already has any headers + * with that name, they are all replaced. */ public Builder header(String name, String value) { headers.set(name, value); @@ -167,8 +167,8 @@ public final class Request { } /** - * Adds a header with {@code name} and {@code value}. Prefer this method for - * multiply-valued headers like "Cookie". + * Adds a header with {@code name} and {@code value}. Prefer this method for multiply-valued + * headers like "Cookie". * *

    Note that for some headers including {@code Content-Length} and {@code Content-Encoding}, * OkHttp may replace {@code value} with a header derived from the request body. @@ -190,9 +190,9 @@ public final class Request { } /** - * Sets this request's {@code Cache-Control} header, replacing any cache - * control headers already present. If {@code cacheControl} doesn't define - * any directives, this clears this request's cache-control headers. + * Sets this request's {@code Cache-Control} header, replacing any cache control headers already + * present. If {@code cacheControl} doesn't define any directives, this clears this request's + * cache-control headers. */ public Builder cacheControl(CacheControl cacheControl) { String value = cacheControl.toString(); @@ -244,9 +244,8 @@ public final class Request { } /** - * Attaches {@code tag} to the request. It can be used later to cancel the - * request. If the tag is unspecified or null, the request is canceled by - * using the request itself as the tag. + * Attaches {@code tag} to the request. It can be used later to cancel the request. If the tag + * is unspecified or null, the request is canceled by using the request itself as the tag. */ public Builder tag(Object tag) { this.tag = tag; diff --git a/okhttp/src/main/java/okhttp3/RequestBody.java b/okhttp/src/main/java/okhttp3/RequestBody.java index 572a45fc8..136cfdc4e 100644 --- a/okhttp/src/main/java/okhttp3/RequestBody.java +++ b/okhttp/src/main/java/okhttp3/RequestBody.java @@ -15,10 +15,10 @@ */ package okhttp3; -import okhttp3.internal.Util; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; +import okhttp3.internal.Util; import okio.BufferedSink; import okio.ByteString; import okio.Okio; @@ -29,8 +29,8 @@ public abstract class RequestBody { public abstract MediaType contentType(); /** - * Returns the number of bytes that will be written to {@code out} in a call - * to {@link #writeTo}, or -1 if that count is unknown. + * Returns the number of bytes that will be written to {@code out} in a call to {@link #writeTo}, + * or -1 if that count is unknown. */ public long contentLength() throws IOException { return -1; @@ -40,8 +40,8 @@ public abstract class RequestBody { public abstract void writeTo(BufferedSink sink) throws IOException; /** - * Returns a new request body that transmits {@code content}. If {@code - * contentType} is non-null and lacks a charset, this will use UTF-8. + * Returns a new request body that transmits {@code content}. If {@code contentType} is non-null + * and lacks a charset, this will use UTF-8. */ public static RequestBody create(MediaType contentType, String content) { Charset charset = Util.UTF_8; diff --git a/okhttp/src/main/java/okhttp3/Response.java b/okhttp/src/main/java/okhttp3/Response.java index ccdca395f..f1a9f5ffc 100644 --- a/okhttp/src/main/java/okhttp3/Response.java +++ b/okhttp/src/main/java/okhttp3/Response.java @@ -15,23 +15,22 @@ */ package okhttp3; -import okhttp3.internal.http.OkHeaders; import java.util.Collections; import java.util.List; +import okhttp3.internal.http.OkHeaders; -import static okhttp3.internal.http.StatusLine.HTTP_PERM_REDIRECT; -import static okhttp3.internal.http.StatusLine.HTTP_TEMP_REDIRECT; import static java.net.HttpURLConnection.HTTP_MOVED_PERM; import static java.net.HttpURLConnection.HTTP_MOVED_TEMP; import static java.net.HttpURLConnection.HTTP_MULT_CHOICE; import static java.net.HttpURLConnection.HTTP_PROXY_AUTH; import static java.net.HttpURLConnection.HTTP_SEE_OTHER; import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; +import static okhttp3.internal.http.StatusLine.HTTP_PERM_REDIRECT; +import static okhttp3.internal.http.StatusLine.HTTP_TEMP_REDIRECT; /** - * An HTTP response. Instances of this class are not immutable: the response - * body is a one-shot value that may be consumed only once. All other properties - * are immutable. + * An HTTP response. Instances of this class are not immutable: the response body is a one-shot + * value that may be consumed only once. All other properties are immutable. */ public final class Response { private final Request request; @@ -63,6 +62,7 @@ public final class Response { /** * The wire-level request that initiated this HTTP response. This is not * necessarily the same request issued by the application: + * *

      *
    • It may be transformed by the HTTP client. For example, the client * may copy headers like {@code Content-Length} from the request body. @@ -76,8 +76,7 @@ public final class Response { } /** - * Returns the HTTP protocol, such as {@link Protocol#HTTP_1_1} or {@link - * Protocol#HTTP_1_0}. + * Returns the HTTP protocol, such as {@link Protocol#HTTP_1_1} or {@link Protocol#HTTP_1_0}. */ public Protocol protocol() { return protocol; @@ -89,8 +88,8 @@ public final class Response { } /** - * Returns true if the code is in [200..300), which means the request was - * successfully received, understood, and accepted. + * Returns true if the code is in [200..300), which means the request was successfully received, + * understood, and accepted. */ public boolean isSuccessful() { return code >= 200 && code < 300; @@ -102,8 +101,8 @@ public final class Response { } /** - * Returns the TLS handshake of the connection that carried this response, or - * null if the response was received without TLS. + * Returns the TLS handshake of the connection that carried this response, or null if the response + * was received without TLS. */ public Handshake handshake() { return handshake; @@ -150,40 +149,38 @@ public final class Response { } /** - * Returns the raw response received from the network. Will be null if this - * response didn't use the network, such as when the response is fully cached. - * The body of the returned response should not be read. + * Returns the raw response received from the network. Will be null if this response didn't use + * the network, such as when the response is fully cached. The body of the returned response + * should not be read. */ public Response networkResponse() { return networkResponse; } /** - * Returns the raw response received from the cache. Will be null if this - * response didn't use the cache. For conditional get requests the cache - * response and network response may both be non-null. The body of the - * returned response should not be read. + * Returns the raw response received from the cache. Will be null if this response didn't use the + * cache. For conditional get requests the cache response and network response may both be + * non-null. The body of the returned response should not be read. */ public Response cacheResponse() { return cacheResponse; } /** - * Returns the response for the HTTP redirect or authorization challenge that - * triggered this response, or null if this response wasn't triggered by an - * automatic retry. The body of the returned response should not be read - * because it has already been consumed by the redirecting client. + * Returns the response for the HTTP redirect or authorization challenge that triggered this + * response, or null if this response wasn't triggered by an automatic retry. The body of the + * returned response should not be read because it has already been consumed by the redirecting + * client. */ public Response priorResponse() { return priorResponse; } /** - * Returns the authorization challenges appropriate for this response's code. - * If the response code is 401 unauthorized, this returns the - * "WWW-Authenticate" challenges. If the response code is 407 proxy - * unauthorized, this returns the "Proxy-Authenticate" challenges. Otherwise - * this returns an empty list of challenges. + * Returns the authorization challenges appropriate for this response's code. If the response code + * is 401 unauthorized, this returns the "WWW-Authenticate" challenges. If the response code is + * 407 proxy unauthorized, this returns the "Proxy-Authenticate" challenges. Otherwise this + * returns an empty list of challenges. */ public List challenges() { String responseField; @@ -198,8 +195,8 @@ public final class Response { } /** - * Returns the cache control directives for this response. This is never null, - * even if this response contains no {@code Cache-Control} header. + * Returns the cache control directives for this response. This is never null, even if this + * response contains no {@code Cache-Control} header. */ public CacheControl cacheControl() { CacheControl result = cacheControl; @@ -273,8 +270,8 @@ public final class Response { } /** - * Sets the header named {@code name} to {@code value}. If this request - * already has any headers with that name, they are all replaced. + * Sets the header named {@code name} to {@code value}. If this request already has any headers + * with that name, they are all replaced. */ public Builder header(String name, String value) { headers.set(name, value); @@ -282,8 +279,8 @@ public final class Response { } /** - * Adds a header with {@code name} and {@code value}. Prefer this method for - * multiply-valued headers like "Set-Cookie". + * Adds a header with {@code name} and {@code value}. Prefer this method for multiply-valued + * headers like "Set-Cookie". */ public Builder addHeader(String name, String value) { headers.add(name, value); diff --git a/okhttp/src/main/java/okhttp3/ResponseBody.java b/okhttp/src/main/java/okhttp3/ResponseBody.java index 22fb4d629..0ae2daa22 100644 --- a/okhttp/src/main/java/okhttp3/ResponseBody.java +++ b/okhttp/src/main/java/okhttp3/ResponseBody.java @@ -15,13 +15,13 @@ */ package okhttp3; -import okhttp3.internal.Util; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.Charset; +import okhttp3.internal.Util; import okio.Buffer; import okio.BufferedSource; @@ -34,8 +34,8 @@ public abstract class ResponseBody implements Closeable { public abstract MediaType contentType(); /** - * Returns the number of bytes in that will returned by {@link #bytes}, or - * {@link #byteStream}, or -1 if unknown. + * Returns the number of bytes in that will returned by {@link #bytes}, or {@link #byteStream}, or + * -1 if unknown. */ public abstract long contentLength(); @@ -65,9 +65,9 @@ public abstract class ResponseBody implements Closeable { } /** - * Returns the response as a character stream decoded with the charset - * of the Content-Type header. If that header is either absent or lacks a - * charset, this will attempt to decode the response body as UTF-8. + * Returns the response as a character stream decoded with the charset of the Content-Type header. + * If that header is either absent or lacks a charset, this will attempt to decode the response + * body as UTF-8. */ public final Reader charStream() { Reader r = reader; @@ -75,9 +75,9 @@ public abstract class ResponseBody implements Closeable { } /** - * Returns the response as a string decoded with the charset of the - * Content-Type header. If that header is either absent or lacks a charset, - * this will attempt to decode the response body as UTF-8. + * Returns the response as a string decoded with the charset of the Content-Type header. If that + * header is either absent or lacks a charset, this will attempt to decode the response body as + * UTF-8. */ public final String string() throws IOException { return new String(bytes(), charset().name()); @@ -93,8 +93,8 @@ public abstract class ResponseBody implements Closeable { } /** - * Returns a new response body that transmits {@code content}. If {@code - * contentType} is non-null and lacks a charset, this will use UTF-8. + * Returns a new response body that transmits {@code content}. If {@code contentType} is non-null + * and lacks a charset, this will use UTF-8. */ public static ResponseBody create(MediaType contentType, String content) { Charset charset = UTF_8; diff --git a/okhttp/src/main/java/okhttp3/Route.java b/okhttp/src/main/java/okhttp3/Route.java index 74e38f1aa..8aaa0f5b8 100644 --- a/okhttp/src/main/java/okhttp3/Route.java +++ b/okhttp/src/main/java/okhttp3/Route.java @@ -19,17 +19,19 @@ import java.net.InetSocketAddress; import java.net.Proxy; /** - * The concrete route used by a connection to reach an abstract origin server. - * When creating a connection the client has many options: + * The concrete route used by a connection to reach an abstract origin server. When creating a + * connection the client has many options: + * *
        - *
      • HTTP proxy: a proxy server may be explicitly - * configured for the client. Otherwise the {@linkplain java.net.ProxySelector - * proxy selector} is used. It may return multiple proxies to attempt. - *
      • IP address: whether connecting directly to an origin - * server or a proxy, opening a socket requires an IP address. The DNS - * server may return multiple IP addresses to attempt. + *
      • HTTP proxy: a proxy server may be explicitly configured for the client. + * Otherwise the {@linkplain java.net.ProxySelector proxy selector} is used. It may return + * multiple proxies to attempt. + *
      • IP address: whether connecting directly to an origin server or a proxy, + * opening a socket requires an IP address. The DNS server may return multiple IP addresses + * to attempt. *
      - * Each route is a specific selection of these options. + * + *

      Each route is a specific selection of these options. */ public final class Route { final Address address; @@ -58,9 +60,8 @@ public final class Route { /** * Returns the {@link Proxy} of this route. * - * Warning: This may disagree with {@link Address#proxy} - * when it is null. When the address's proxy is null, the proxy selector is - * used. + * Warning: This may disagree with {@link Address#proxy} when it is null. When + * the address's proxy is null, the proxy selector is used. */ public Proxy proxy() { return proxy; diff --git a/okhttp/src/main/java/okhttp3/TlsVersion.java b/okhttp/src/main/java/okhttp3/TlsVersion.java index 49b815c25..668cd9732 100644 --- a/okhttp/src/main/java/okhttp3/TlsVersion.java +++ b/okhttp/src/main/java/okhttp3/TlsVersion.java @@ -15,11 +15,9 @@ */ package okhttp3; -import javax.net.ssl.SSLSocket; - /** - * Versions of TLS that can be offered when negotiating a secure socket. See - * {@link SSLSocket#setEnabledProtocols}. + * Versions of TLS that can be offered when negotiating a secure socket. See {@link + * javax.net.ssl.SSLSocket#setEnabledProtocols}. */ public enum TlsVersion { TLS_1_2("TLSv1.2"), // 2008. @@ -36,10 +34,14 @@ public enum TlsVersion { public static TlsVersion forJavaName(String javaName) { switch (javaName) { - case "TLSv1.2": return TLS_1_2; - case "TLSv1.1": return TLS_1_1; - case "TLSv1": return TLS_1_0; - case "SSLv3": return SSL_3_0; + case "TLSv1.2": + return TLS_1_2; + case "TLSv1.1": + return TLS_1_1; + case "TLSv1": + return TLS_1_0; + case "SSLv3": + return SSL_3_0; } throw new IllegalArgumentException("Unexpected TLS version: " + javaName); } diff --git a/okhttp/src/main/java/okhttp3/internal/ConnectionSpecSelector.java b/okhttp/src/main/java/okhttp3/internal/ConnectionSpecSelector.java index 844010e15..3123eece2 100644 --- a/okhttp/src/main/java/okhttp3/internal/ConnectionSpecSelector.java +++ b/okhttp/src/main/java/okhttp3/internal/ConnectionSpecSelector.java @@ -16,7 +16,6 @@ package okhttp3.internal; -import okhttp3.ConnectionSpec; import java.io.IOException; import java.io.InterruptedIOException; import java.net.ProtocolException; @@ -28,11 +27,12 @@ import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLProtocolException; import javax.net.ssl.SSLSocket; +import okhttp3.ConnectionSpec; /** - * Handles the connection spec fallback strategy: When a secure socket connection fails - * due to a handshake / protocol problem the connection may be retried with different protocols. - * Instances are stateful and should be created and used for a single connection attempt. + * Handles the connection spec fallback strategy: When a secure socket connection fails due to a + * handshake / protocol problem the connection may be retried with different protocols. Instances + * are stateful and should be created and used for a single connection attempt. */ public final class ConnectionSpecSelector { @@ -81,11 +81,11 @@ public final class ConnectionSpecSelector { } /** - * Reports a failure to complete a connection. Determines the next {@link ConnectionSpec} to - * try, if any. + * Reports a failure to complete a connection. Determines the next {@link ConnectionSpec} to try, + * if any. * - * @return {@code true} if the connection should be retried using - * {@link #configureSecureSocket(SSLSocket)} or {@code false} if not + * @return {@code true} if the connection should be retried using {@link + * #configureSecureSocket(SSLSocket)} or {@code false} if not */ public boolean connectionFailed(IOException e) { // Any future attempt to connect using this strategy will be a fallback attempt. @@ -121,7 +121,6 @@ public final class ConnectionSpecSelector { return false; } - // On Android, SSLProtocolExceptions can be caused by TLS_FALLBACK_SCSV failures, which means we // retry those when we probably should not. return (e instanceof SSLHandshakeException || e instanceof SSLProtocolException); diff --git a/okhttp/src/main/java/okhttp3/internal/DiskLruCache.java b/okhttp/src/main/java/okhttp3/internal/DiskLruCache.java index 2b1f6aee5..70564087d 100644 --- a/okhttp/src/main/java/okhttp3/internal/DiskLruCache.java +++ b/okhttp/src/main/java/okhttp3/internal/DiskLruCache.java @@ -16,7 +16,6 @@ package okhttp3.internal; -import okhttp3.internal.io.FileSystem; import java.io.Closeable; import java.io.EOFException; import java.io.File; @@ -33,6 +32,7 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; +import okhttp3.internal.io.FileSystem; import okio.Buffer; import okio.BufferedSink; import okio.BufferedSource; @@ -42,48 +42,44 @@ import okio.Source; import okio.Timeout; /** - * A cache that uses a bounded amount of space on a filesystem. Each cache - * entry has a string key and a fixed number of values. Each key must match - * the regex [a-z0-9_-]{1,64}. Values are byte sequences, - * accessible as streams or files. Each value must be between {@code 0} and - * {@code Integer.MAX_VALUE} bytes in length. + * A cache that uses a bounded amount of space on a filesystem. Each cache entry has a string key + * and a fixed number of values. Each key must match the regex [a-z0-9_-]{1,64}. + * Values are byte sequences, accessible as streams or files. Each value must be between {@code 0} + * and {@code Integer.MAX_VALUE} bytes in length. * - *

      The cache stores its data in a directory on the filesystem. This - * directory must be exclusive to the cache; the cache may delete or overwrite - * files from its directory. It is an error for multiple processes to use the - * same cache directory at the same time. + *

      The cache stores its data in a directory on the filesystem. This directory must be exclusive + * to the cache; the cache may delete or overwrite files from its directory. It is an error for + * multiple processes to use the same cache directory at the same time. * - *

      This cache limits the number of bytes that it will store on the - * filesystem. When the number of stored bytes exceeds the limit, the cache will - * remove entries in the background until the limit is satisfied. The limit is - * not strict: the cache may temporarily exceed it while waiting for files to be - * deleted. The limit does not include filesystem overhead or the cache - * journal so space-sensitive applications should set a conservative limit. + *

      This cache limits the number of bytes that it will store on the filesystem. When the number of + * stored bytes exceeds the limit, the cache will remove entries in the background until the limit + * is satisfied. The limit is not strict: the cache may temporarily exceed it while waiting for + * files to be deleted. The limit does not include filesystem overhead or the cache journal so + * space-sensitive applications should set a conservative limit. + * + *

      Clients call {@link #edit} to create or update the values of an entry. An entry may have only + * one editor at one time; if a value is not available to be edited then {@link #edit} will return + * null. * - *

      Clients call {@link #edit} to create or update the values of an entry. An - * entry may have only one editor at one time; if a value is not available to be - * edited then {@link #edit} will return null. *

        - *
      • When an entry is being created it is necessary to - * supply a full set of values; the empty value should be used as a - * placeholder if necessary. - *
      • When an entry is being edited, it is not necessary - * to supply data for every value; values default to their previous - * value. + *
      • When an entry is being created it is necessary to supply a full set of + * values; the empty value should be used as a placeholder if necessary. + *
      • When an entry is being edited, it is not necessary to supply data for + * every value; values default to their previous value. *
      - * Every {@link #edit} call must be matched by a call to {@link Editor#commit} - * or {@link Editor#abort}. Committing is atomic: a read observes the full set - * of values as they were before or after the commit, but never a mix of values. * - *

      Clients call {@link #get} to read a snapshot of an entry. The read will - * observe the value at the time that {@link #get} was called. Updates and - * removals after the call do not impact ongoing reads. + *

      Every {@link #edit} call must be matched by a call to {@link Editor#commit} or {@link + * Editor#abort}. Committing is atomic: a read observes the full set of values as they were before + * or after the commit, but never a mix of values. * - *

      This class is tolerant of some I/O errors. If files are missing from the - * filesystem, the corresponding entries will be dropped from the cache. If - * an error occurs while writing a cache value, the edit will fail silently. - * Callers should handle other problems by catching {@code IOException} and - * responding appropriately. + *

      Clients call {@link #get} to read a snapshot of an entry. The read will observe the value at + * the time that {@link #get} was called. Updates and removals after the call do not impact ongoing + * reads. + * + *

      This class is tolerant of some I/O errors. If files are missing from the filesystem, the + * corresponding entries will be dropped from the cache. If an error occurs while writing a cache + * value, the edit will fail silently. Callers should handle other problems by catching {@code + * IOException} and responding appropriately. */ public final class DiskLruCache implements Closeable { static final String JOURNAL_FILE = "journal"; @@ -157,9 +153,9 @@ public final class DiskLruCache implements Closeable { private boolean closed; /** - * To differentiate between old and current snapshots, each entry is given - * a sequence number each time an edit is committed. A snapshot is stale if - * its sequence number is not equal to its entry's sequence number. + * To differentiate between old and current snapshots, each entry is given a sequence number each + * time an edit is committed. A snapshot is stale if its sequence number is not equal to its + * entry's sequence number. */ private long nextSequenceNumber = 0; @@ -348,8 +344,8 @@ public final class DiskLruCache implements Closeable { } /** - * Computes the initial size and collects garbage as a part of opening the - * cache. Dirty entries are assumed to be inconsistent and will be deleted. + * Computes the initial size and collects garbage as a part of opening the cache. Dirty entries + * are assumed to be inconsistent and will be deleted. */ private void processJournal() throws IOException { fileSystem.delete(journalFileTmp); @@ -371,8 +367,8 @@ public final class DiskLruCache implements Closeable { } /** - * Creates a new journal that omits redundant information. This replaces the - * current journal if it exists. + * Creates a new journal that omits redundant information. This replaces the current journal if it + * exists. */ private synchronized void rebuildJournal() throws IOException { if (journalWriter != null) { @@ -414,9 +410,8 @@ public final class DiskLruCache implements Closeable { } /** - * Returns a snapshot of the entry named {@code key}, or null if it doesn't - * exist is not currently readable. If a value is returned, it is moved to - * the head of the LRU queue. + * Returns a snapshot of the entry named {@code key}, or null if it doesn't exist is not currently + * readable. If a value is returned, it is moved to the head of the LRU queue. */ public synchronized Snapshot get(String key) throws IOException { initialize(); @@ -439,8 +434,7 @@ public final class DiskLruCache implements Closeable { } /** - * Returns an editor for the entry named {@code key}, or null if another - * edit is in progress. + * Returns an editor for the entry named {@code key}, or null if another edit is in progress. */ public Editor edit(String key) throws IOException { return edit(key, ANY_SEQUENCE_NUMBER); @@ -483,16 +477,15 @@ public final class DiskLruCache implements Closeable { } /** - * Returns the maximum number of bytes that this cache should use to store - * its data. + * Returns the maximum number of bytes that this cache should use to store its data. */ public synchronized long getMaxSize() { return maxSize; } /** - * Changes the maximum number of bytes the cache can store and queues a job - * to trim the existing store, if necessary. + * Changes the maximum number of bytes the cache can store and queues a job to trim the existing + * store, if necessary. */ public synchronized void setMaxSize(long maxSize) { this.maxSize = maxSize; @@ -502,9 +495,8 @@ public final class DiskLruCache implements Closeable { } /** - * Returns the number of bytes currently being used to store the values in - * this cache. This may be greater than the max size if a background - * deletion is pending. + * Returns the number of bytes currently being used to store the values in this cache. This may be + * greater than the max size if a background deletion is pending. */ public synchronized long size() throws IOException { initialize(); @@ -572,8 +564,8 @@ public final class DiskLruCache implements Closeable { } /** - * We only rebuild the journal when it will halve the size of the journal - * and eliminate at least 2000 ops. + * We only rebuild the journal when it will halve the size of the journal and eliminate at least + * 2000 ops. */ private boolean journalRebuildRequired() { final int redundantOpCompactThreshold = 2000; @@ -582,9 +574,8 @@ public final class DiskLruCache implements Closeable { } /** - * Drops the entry for {@code key} if it exists and can be removed. If the - * entry for {@code key} is currently being edited, that edit will complete - * normally but its value will not be stored. + * Drops the entry for {@code key} if it exists and can be removed. If the entry for {@code key} + * is currently being edited, that edit will complete normally but its value will not be stored. * * @return true if an entry was removed. */ @@ -666,9 +657,8 @@ public final class DiskLruCache implements Closeable { } /** - * Closes the cache and deletes all of its stored values. This will delete - * all files in the cache directory including files that weren't created by - * the cache. + * Closes the cache and deletes all of its stored values. This will delete all files in the cache + * directory including files that weren't created by the cache. */ public void delete() throws IOException { close(); @@ -676,8 +666,8 @@ public final class DiskLruCache implements Closeable { } /** - * Deletes all stored values from the cache. In-flight edits will complete - * normally but their values will not be stored. + * Deletes all stored values from the cache. In-flight edits will complete normally but their + * values will not be stored. */ public synchronized void evictAll() throws IOException { initialize(); @@ -781,9 +771,8 @@ public final class DiskLruCache implements Closeable { } /** - * Returns an editor for this snapshot's entry, or null if either the - * entry has changed since this snapshot was created or if another edit - * is in progress. + * Returns an editor for this snapshot's entry, or null if either the entry has changed since + * this snapshot was created or if another edit is in progress. */ public Editor edit() throws IOException { return DiskLruCache.this.edit(key, sequenceNumber); @@ -835,8 +824,8 @@ public final class DiskLruCache implements Closeable { } /** - * Returns an unbuffered input stream to read the last committed value, - * or null if no value has been committed. + * Returns an unbuffered input stream to read the last committed value, or null if no value has + * been committed. */ public Source newSource(int index) throws IOException { synchronized (DiskLruCache.this) { @@ -855,11 +844,9 @@ public final class DiskLruCache implements Closeable { } /** - * Returns a new unbuffered output stream to write the value at - * {@code index}. If the underlying output stream encounters errors - * when writing to the filesystem, this edit will be aborted when - * {@link #commit} is called. The returned output stream does not throw - * IOExceptions. + * Returns a new unbuffered output stream to write the value at {@code index}. If the underlying + * output stream encounters errors when writing to the filesystem, this edit will be aborted + * when {@link #commit} is called. The returned output stream does not throw IOExceptions. */ public Sink newSink(int index) throws IOException { synchronized (DiskLruCache.this) { @@ -887,8 +874,8 @@ public final class DiskLruCache implements Closeable { } /** - * Commits this edit so it is visible to readers. This releases the - * edit lock so another edit may be started on the same key. + * Commits this edit so it is visible to readers. This releases the edit lock so another edit + * may be started on the same key. */ public void commit() throws IOException { synchronized (DiskLruCache.this) { @@ -903,8 +890,8 @@ public final class DiskLruCache implements Closeable { } /** - * Aborts this edit. This releases the edit lock so another edit may be - * started on the same key. + * Aborts this edit. This releases the edit lock so another edit may be started on the same + * key. */ public void abort() throws IOException { synchronized (DiskLruCache.this) { diff --git a/okhttp/src/main/java/okhttp3/internal/Internal.java b/okhttp/src/main/java/okhttp3/internal/Internal.java index 320143e5c..e473ba69d 100644 --- a/okhttp/src/main/java/okhttp3/internal/Internal.java +++ b/okhttp/src/main/java/okhttp3/internal/Internal.java @@ -15,6 +15,10 @@ */ package okhttp3.internal; +import java.net.MalformedURLException; +import java.net.UnknownHostException; +import java.util.logging.Logger; +import javax.net.ssl.SSLSocket; import okhttp3.Address; import okhttp3.Call; import okhttp3.Callback; @@ -25,10 +29,6 @@ import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.internal.http.StreamAllocation; import okhttp3.internal.io.RealConnection; -import java.net.MalformedURLException; -import java.net.UnknownHostException; -import java.util.logging.Logger; -import javax.net.ssl.SSLSocket; /** * Escalate internal APIs in {@code okhttp3} so they can be used from OkHttp's implementation @@ -69,5 +69,6 @@ public abstract class Internal { // TODO delete the following when web sockets move into the main package. public abstract void callEnqueue(Call call, Callback responseCallback, boolean forWebSocket); + public abstract StreamAllocation callEngineGetStreamAllocation(Call call); } diff --git a/okhttp/src/main/java/okhttp3/internal/InternalCache.java b/okhttp/src/main/java/okhttp3/internal/InternalCache.java index d21096d45..9752002bc 100644 --- a/okhttp/src/main/java/okhttp3/internal/InternalCache.java +++ b/okhttp/src/main/java/okhttp3/internal/InternalCache.java @@ -15,16 +15,15 @@ */ package okhttp3.internal; +import java.io.IOException; import okhttp3.Request; import okhttp3.Response; import okhttp3.internal.http.CacheRequest; import okhttp3.internal.http.CacheStrategy; -import java.io.IOException; -import okhttp3.Cache; /** - * OkHttp's internal cache interface. Applications shouldn't implement this: - * instead use {@link Cache}. + * OkHttp's internal cache interface. Applications shouldn't implement this: instead use {@link + * okhttp3.Cache}. */ public interface InternalCache { Response get(Request request) throws IOException; @@ -32,16 +31,15 @@ public interface InternalCache { CacheRequest put(Response response) throws IOException; /** - * Remove any cache entries for the supplied {@code request}. This is invoked - * when the client invalidates the cache, such as when making POST requests. + * Remove any cache entries for the supplied {@code request}. This is invoked when the client + * invalidates the cache, such as when making POST requests. */ void remove(Request request) throws IOException; /** - * Handles a conditional request hit by updating the stored cache response - * with the headers from {@code network}. The cached response body is not - * updated. If the stored response has changed since {@code cached} was - * returned, this does nothing. + * Handles a conditional request hit by updating the stored cache response with the headers from + * {@code network}. The cached response body is not updated. If the stored response has changed + * since {@code cached} was returned, this does nothing. */ void update(Response cached, Response network) throws IOException; diff --git a/okhttp/src/main/java/okhttp3/internal/OptionalMethod.java b/okhttp/src/main/java/okhttp3/internal/OptionalMethod.java index 7605556b5..108ec292d 100644 --- a/okhttp/src/main/java/okhttp3/internal/OptionalMethod.java +++ b/okhttp/src/main/java/okhttp3/internal/OptionalMethod.java @@ -57,8 +57,7 @@ class OptionalMethod { /** * Invokes the method on {@code target} with {@code args}. If the method does not exist or is not - * public then {@code null} is returned. See also - * {@link #invokeOptionalWithoutCheckedException(Object, Object...)}. + * public then {@code null} is returned. See also {@link #invokeOptionalWithoutCheckedException}. * * @throws IllegalArgumentException if the arguments are invalid * @throws InvocationTargetException if the invocation throws an exception @@ -76,9 +75,9 @@ class OptionalMethod { } /** - * Invokes the method on {@code target}. If the method does not exist or is not - * public then {@code null} is returned. Any RuntimeException thrown by the method is thrown, - * checked exceptions are wrapped in an {@link AssertionError}. + * Invokes the method on {@code target}. If the method does not exist or is not public then + * {@code null} is returned. Any RuntimeException thrown by the method is thrown, checked + * exceptions are wrapped in an {@link AssertionError}. * * @throws IllegalArgumentException if the arguments are invalid */ @@ -120,8 +119,8 @@ class OptionalMethod { /** * Invokes the method on {@code target}. Throws an error if the method is not supported. Any - * RuntimeException thrown by the method is thrown, checked exceptions are wrapped in - * an {@link AssertionError}. + * RuntimeException thrown by the method is thrown, checked exceptions are wrapped in an {@link + * AssertionError}. * * @throws IllegalArgumentException if the arguments are invalid */ @@ -140,10 +139,9 @@ class OptionalMethod { } /** - * Perform a lookup for the method. No caching. - * In order to return a method the method name and arguments must match those specified when - * the {@link OptionalMethod} was created. If the return type is specified (i.e. non-null) it - * must also be compatible. The method must also be public. + * Perform a lookup for the method. No caching. In order to return a method the method name and + * arguments must match those specified when the {@link OptionalMethod} was created. If the return + * type is specified (i.e. non-null) it must also be compatible. The method must also be public. */ private Method getMethod(Class clazz) { Method method = null; diff --git a/okhttp/src/main/java/okhttp3/internal/Platform.java b/okhttp/src/main/java/okhttp3/internal/Platform.java index d410a60ea..9e5e5545d 100644 --- a/okhttp/src/main/java/okhttp3/internal/Platform.java +++ b/okhttp/src/main/java/okhttp3/internal/Platform.java @@ -17,7 +17,6 @@ package okhttp3.internal; import android.util.Log; -import okhttp3.Protocol; import java.io.IOException; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; @@ -30,6 +29,7 @@ import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import javax.net.ssl.SSLSocket; +import okhttp3.Protocol; import okio.Buffer; import static okhttp3.internal.Internal.logger; @@ -38,16 +38,20 @@ import static okhttp3.internal.Internal.logger; * Access to platform-specific features. * *

      Server name indication (SNI)

      - * Supported on Android 2.3+. + * + *

      Supported on Android 2.3+. * *

      Session Tickets

      - * Supported on Android 2.3+. + * + *

      Supported on Android 2.3+. * *

      Android Traffic Stats (Socket Tagging)

      - * Supported on Android 4.0+. + * + *

      Supported on Android 4.0+. * *

      ALPN (Application Layer Protocol Negotiation)

      - * Supported on Android 5.0+. The APIs were present in Android 4.4, but that implementation was + * + *

      Supported on Android 5.0+. The APIs were present in Android 4.4, but that implementation was * unstable. * * Supported on OpenJDK 7 and 8 (via the JettyALPN-boot library). @@ -77,8 +81,7 @@ public class Platform { /** * Configure TLS extensions on {@code sslSocket} for {@code route}. * - * @param hostname non-null for client-side handshakes; null for - * server-side handshakes. + * @param hostname non-null for client-side handshakes; null for server-side handshakes. */ public void configureTlsExtensions(SSLSocket sslSocket, String hostname, List protocols) { @@ -217,7 +220,7 @@ public class Platform { // Enable ALPN. if (setAlpnProtocols != null && setAlpnProtocols.isSupported(sslSocket)) { - Object[] parameters = { concatLengthPrefixed(protocols) }; + Object[] parameters = {concatLengthPrefixed(protocols)}; setAlpnProtocols.invokeWithoutCheckedException(sslSocket, parameters); } } @@ -297,7 +300,7 @@ public class Platform { } try { Object provider = Proxy.newProxyInstance(Platform.class.getClassLoader(), - new Class[] { clientProviderClass, serverProviderClass }, new JettyNegoProvider(names)); + new Class[] {clientProviderClass, serverProviderClass}, new JettyNegoProvider(names)); putMethod.invoke(null, sslSocket, provider); } catch (InvocationTargetException | IllegalAccessException e) { throw new AssertionError(e); @@ -329,8 +332,8 @@ public class Platform { } /** - * Handle the methods of ALPN's ClientProvider and ServerProvider - * without a compile-time dependency on those interfaces. + * Handle the methods of ALPN's ClientProvider and ServerProvider without a compile-time + * dependency on those interfaces. */ private static class JettyNegoProvider implements InvocationHandler { /** This peer's supported protocols. */ diff --git a/okhttp/src/main/java/okhttp3/internal/RouteDatabase.java b/okhttp/src/main/java/okhttp3/internal/RouteDatabase.java index d2c2a5ea6..613e0bf21 100644 --- a/okhttp/src/main/java/okhttp3/internal/RouteDatabase.java +++ b/okhttp/src/main/java/okhttp3/internal/RouteDatabase.java @@ -15,15 +15,15 @@ */ package okhttp3.internal; -import okhttp3.Route; import java.util.LinkedHashSet; import java.util.Set; +import okhttp3.Route; /** - * A blacklist of failed routes to avoid when creating a new connection to a - * target address. This is used so that OkHttp can learn from its mistakes: if - * there was a failure attempting to connect to a specific IP address or proxy - * server, that failure is remembered and alternate routes are preferred. + * A blacklist of failed routes to avoid when creating a new connection to a target address. This is + * used so that OkHttp can learn from its mistakes: if there was a failure attempting to connect to + * a specific IP address or proxy server, that failure is remembered and alternate routes are + * preferred. */ public final class RouteDatabase { private final Set failedRoutes = new LinkedHashSet<>(); diff --git a/okhttp/src/main/java/okhttp3/internal/Util.java b/okhttp/src/main/java/okhttp3/internal/Util.java index 338fe7174..e4001be3f 100644 --- a/okhttp/src/main/java/okhttp3/internal/Util.java +++ b/okhttp/src/main/java/okhttp3/internal/Util.java @@ -16,7 +16,6 @@ package okhttp3.internal; -import okhttp3.HttpUrl; import java.io.Closeable; import java.io.IOException; import java.io.InterruptedIOException; @@ -35,6 +34,7 @@ import java.util.List; import java.util.Map; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; +import okhttp3.HttpUrl; import okio.Buffer; import okio.ByteString; import okio.Source; @@ -62,8 +62,8 @@ public final class Util { } /** - * Closes {@code closeable}, ignoring any checked exceptions. Does nothing - * if {@code closeable} is null. + * Closes {@code closeable}, ignoring any checked exceptions. Does nothing if {@code closeable} is + * null. */ public static void closeQuietly(Closeable closeable) { if (closeable != null) { @@ -77,8 +77,8 @@ public final class Util { } /** - * Closes {@code socket}, ignoring any checked exceptions. Does nothing if - * {@code socket} is null. + * Closes {@code socket}, ignoring any checked exceptions. Does nothing if {@code socket} is + * null. */ public static void closeQuietly(Socket socket) { if (socket != null) { @@ -94,8 +94,8 @@ public final class Util { } /** - * Closes {@code serverSocket}, ignoring any checked exceptions. Does nothing if - * {@code serverSocket} is null. + * Closes {@code serverSocket}, ignoring any checked exceptions. Does nothing if {@code + * serverSocket} is null. */ public static void closeQuietly(ServerSocket serverSocket) { if (serverSocket != null) { @@ -109,8 +109,8 @@ public final class Util { } /** - * Closes {@code a} and {@code b}. If either close fails, this completes - * the other close and rethrows the first encountered exception. + * Closes {@code a} and {@code b}. If either close fails, this completes the other close and + * rethrows the first encountered exception. */ public static void closeAll(Closeable a, Closeable b) throws IOException { Throwable thrown = null; @@ -132,8 +132,8 @@ public final class Util { } /** - * Attempts to exhaust {@code source}, returning true if successful. This is useful when reading - * a complete source is helpful, such as when doing so completes a cache body or frees a socket + * Attempts to exhaust {@code source}, returning true if successful. This is useful when reading a + * complete source is helpful, such as when doing so completes a cache body or frees a socket * connection for reuse. */ public static boolean discard(Source source, int timeout, TimeUnit timeUnit) { @@ -230,8 +230,8 @@ public final class Util { } /** - * Returns an array containing containing only elements found in {@code first} and also in - * {@code second}. The returned elements are in the same order as in {@code first}. + * Returns an array containing containing only elements found in {@code first} and also in {@code + * second}. The returned elements are in the same order as in {@code first}. */ @SuppressWarnings("unchecked") public static T[] intersect(Class arrayType, T[] first, T[] second) { @@ -240,8 +240,8 @@ public final class Util { } /** - * Returns a list containing containing only elements found in {@code first} and also in - * {@code second}. The returned elements are in the same order as in {@code first}. + * Returns a list containing containing only elements found in {@code first} and also in {@code + * second}. The returned elements are in the same order as in {@code first}. */ private static List intersect(T[] first, T[] second) { List result = new ArrayList<>(); diff --git a/okhttp/src/main/java/okhttp3/internal/framed/FrameReader.java b/okhttp/src/main/java/okhttp3/internal/framed/FrameReader.java index 68a23337c..cfcfac0be 100644 --- a/okhttp/src/main/java/okhttp3/internal/framed/FrameReader.java +++ b/okhttp/src/main/java/okhttp3/internal/framed/FrameReader.java @@ -25,6 +25,7 @@ import okio.ByteString; /** Reads transport frames for SPDY/3 or HTTP/2. */ public interface FrameReader extends Closeable { void readConnectionPreface() throws IOException; + boolean nextFrame(Handler handler) throws IOException; interface Handler { @@ -32,100 +33,92 @@ public interface FrameReader extends Closeable { throws IOException; /** - * Create or update incoming headers, creating the corresponding streams - * if necessary. Frames that trigger this are SPDY SYN_STREAM, HEADERS, and - * SYN_REPLY, and HTTP/2 HEADERS and PUSH_PROMISE. + * Create or update incoming headers, creating the corresponding streams if necessary. Frames + * that trigger this are SPDY SYN_STREAM, HEADERS, and SYN_REPLY, and HTTP/2 HEADERS and + * PUSH_PROMISE. * * @param outFinished true if the receiver should not send further frames. * @param inFinished true if the sender will not send further frames. * @param streamId the stream owning these headers. - * @param associatedStreamId the stream that triggered the sender to create - * this stream. + * @param associatedStreamId the stream that triggered the sender to create this stream. */ void headers(boolean outFinished, boolean inFinished, int streamId, int associatedStreamId, List

      headerBlock, HeadersMode headersMode); + void rstStream(int streamId, ErrorCode errorCode); + void settings(boolean clearPrevious, Settings settings); /** HTTP/2 only. */ void ackSettings(); /** - * Read a connection-level ping from the peer. {@code ack} indicates this - * is a reply. Payload parameters are different between SPDY/3 and HTTP/2. - *

      - * In SPDY/3, only the first {@code payload1} parameter is set. If the - * reader is a client, it is an unsigned even number. Likewise, a server - * will receive an odd number. - *

      - * In HTTP/2, both {@code payload1} and {@code payload2} parameters are - * set. The data is opaque binary, and there are no rules on the content. + * Read a connection-level ping from the peer. {@code ack} indicates this is a reply. Payload + * parameters are different between SPDY/3 and HTTP/2. + * + *

      In SPDY/3, only the first {@code payload1} parameter is set. If the reader is a client, + * it is an unsigned even number. Likewise, a server will receive an odd number. + * + *

      In HTTP/2, both {@code payload1} and {@code payload2} parameters are set. The data is + * opaque binary, and there are no rules on the content. */ void ping(boolean ack, int payload1, int payload2); /** - * The peer tells us to stop creating streams. It is safe to replay - * streams with {@code ID > lastGoodStreamId} on a new connection. In- - * flight streams with {@code ID <= lastGoodStreamId} can only be replayed - * on a new connection if they are idempotent. + * The peer tells us to stop creating streams. It is safe to replay streams with {@code ID > + * lastGoodStreamId} on a new connection. In- flight streams with {@code ID <= + * lastGoodStreamId} can only be replayed on a new connection if they are idempotent. * - * @param lastGoodStreamId the last stream ID the peer processed before - * sending this message. If {@code lastGoodStreamId} is zero, the peer - * processed no frames. + * @param lastGoodStreamId the last stream ID the peer processed before sending this message. If + * {@code lastGoodStreamId} is zero, the peer processed no frames. * @param errorCode reason for closing the connection. * @param debugData only valid for HTTP/2; opaque debug data to send. */ void goAway(int lastGoodStreamId, ErrorCode errorCode, ByteString debugData); /** - * Notifies that an additional {@code windowSizeIncrement} bytes can be - * sent on {@code streamId}, or the connection if {@code streamId} is zero. + * Notifies that an additional {@code windowSizeIncrement} bytes can be sent on {@code + * streamId}, or the connection if {@code streamId} is zero. */ void windowUpdate(int streamId, long windowSizeIncrement); /** - * Called when reading a headers or priority frame. This may be used to - * change the stream's weight from the default (16) to a new value. + * Called when reading a headers or priority frame. This may be used to change the stream's + * weight from the default (16) to a new value. * * @param streamId stream which has a priority change. * @param streamDependency the stream ID this stream is dependent on. * @param weight relative proportion of priority in [1..256]. - * @param exclusive inserts this stream ID as the sole child of - * {@code streamDependency}. + * @param exclusive inserts this stream ID as the sole child of {@code streamDependency}. */ void priority(int streamId, int streamDependency, int weight, boolean exclusive); /** - * HTTP/2 only. Receive a push promise header block. - *

      - * A push promise contains all the headers that pertain to a server-initiated - * request, and a {@code promisedStreamId} to which response frames will be - * delivered. Push promise frames are sent as a part of the response to - * {@code streamId}. + * HTTP/2 only. Receive a push promise header block.

      A push promise contains all the headers + * that pertain to a server-initiated request, and a {@code promisedStreamId} to which response + * frames will be delivered. Push promise frames are sent as a part of the response to {@code + * streamId}. * * @param streamId client-initiated stream ID. Must be an odd number. - * @param promisedStreamId server-initiated stream ID. Must be an even - * number. - * @param requestHeaders minimally includes {@code :method}, {@code :scheme}, - * {@code :authority}, and (@code :path}. + * @param promisedStreamId server-initiated stream ID. Must be an even number. + * @param requestHeaders minimally includes {@code :method}, {@code :scheme}, {@code + * :authority}, and (@code :path}. */ void pushPromise(int streamId, int promisedStreamId, List

      requestHeaders) throws IOException; /** - * HTTP/2 only. Expresses that resources for the connection or a client- - * initiated stream are available from a different network location or - * protocol configuration. + * HTTP/2 only. Expresses that resources for the connection or a client- initiated stream are + * available from a different network location or protocol configuration. * *

      See alt-svc * - * @param streamId when a client-initiated stream ID (odd number), the - * origin of this alternate service is the origin of the stream. When - * zero, the origin is specified in the {@code origin} parameter. - * @param origin when present, the - * origin is typically - * represented as a combination of scheme, host and port. When empty, - * the origin is that of the {@code streamId}. + * @param streamId when a client-initiated stream ID (odd number), the origin of this alternate + * service is the origin of the stream. When zero, the origin is specified in the {@code origin} + * parameter. + * @param origin when present, the origin is + * typically represented as a combination of scheme, host and port. When empty, the origin is + * that of the {@code streamId}. * @param protocol an ALPN protocol, such as {@code h2}. * @param host an IP address or hostname. * @param port the IP port associated with the service. diff --git a/okhttp/src/main/java/okhttp3/internal/framed/FrameWriter.java b/okhttp/src/main/java/okhttp3/internal/framed/FrameWriter.java index d22c12a28..ca1a7e4b8 100644 --- a/okhttp/src/main/java/okhttp3/internal/framed/FrameWriter.java +++ b/okhttp/src/main/java/okhttp3/internal/framed/FrameWriter.java @@ -25,34 +25,37 @@ import okio.Buffer; public interface FrameWriter extends Closeable { /** HTTP/2 only. */ void connectionPreface() throws IOException; + /** Informs the peer that we've applied its latest settings. */ void ackSettings(Settings peerSettings) throws IOException; /** * HTTP/2 only. Send a push promise header block. - *

      - * A push promise contains all the headers that pertain to a server-initiated - * request, and a {@code promisedStreamId} to which response frames will be - * delivered. Push promise frames are sent as a part of the response to - * {@code streamId}. The {@code promisedStreamId} has a priority of one - * greater than {@code streamId}. + * + *

      A push promise contains all the headers that pertain to a server-initiated request, and a + * {@code promisedStreamId} to which response frames will be delivered. Push promise frames are + * sent as a part of the response to {@code streamId}. The {@code promisedStreamId} has a priority + * of one greater than {@code streamId}. * * @param streamId client-initiated stream ID. Must be an odd number. - * @param promisedStreamId server-initiated stream ID. Must be an even - * number. - * @param requestHeaders minimally includes {@code :method}, {@code :scheme}, - * {@code :authority}, and (@code :path}. + * @param promisedStreamId server-initiated stream ID. Must be an even number. + * @param requestHeaders minimally includes {@code :method}, {@code :scheme}, {@code :authority}, + * and (@code :path}. */ void pushPromise(int streamId, int promisedStreamId, List

      requestHeaders) throws IOException; /** SPDY/3 only. */ void flush() throws IOException; + void synStream(boolean outFinished, boolean inFinished, int streamId, int associatedStreamId, List
      headerBlock) throws IOException; + void synReply(boolean outFinished, int streamId, List
      headerBlock) throws IOException; + void headers(int streamId, List
      headerBlock) throws IOException; + void rstStream(int streamId, ErrorCode errorCode) throws IOException; /** The maximum size of bytes that may be sent in a single call to {@link #data}. */ @@ -63,8 +66,8 @@ public interface FrameWriter extends Closeable { * Implementations must send multiple frames as necessary. * * @param source the buffer to draw bytes from. May be null if byteCount is 0. - * @param byteCount must be between 0 and the minimum of {code source.length} - * and {@link #maxDataLength}. + * @param byteCount must be between 0 and the minimum of {code source.length} and {@link + * #maxDataLength}. */ void data(boolean outFinished, int streamId, Buffer source, int byteCount) throws IOException; @@ -72,32 +75,30 @@ public interface FrameWriter extends Closeable { void settings(Settings okHttpSettings) throws IOException; /** - * Send a connection-level ping to the peer. {@code ack} indicates this is - * a reply. Payload parameters are different between SPDY/3 and HTTP/2. - *

      - * In SPDY/3, only the first {@code payload1} parameter is sent. If the - * sender is a client, it is an unsigned odd number. Likewise, a server - * will send an even number. - *

      - * In HTTP/2, both {@code payload1} and {@code payload2} parameters are - * sent. The data is opaque binary, and there are no rules on the content. + * Send a connection-level ping to the peer. {@code ack} indicates this is a reply. Payload + * parameters are different between SPDY/3 and HTTP/2. + * + *

      In SPDY/3, only the first {@code payload1} parameter is sent. If the sender is a client, it + * is an unsigned odd number. Likewise, a server will send an even number. + * + *

      In HTTP/2, both {@code payload1} and {@code payload2} parameters are sent. The data is + * opaque binary, and there are no rules on the content. */ void ping(boolean ack, int payload1, int payload2) throws IOException; /** - * Tell the peer to stop creating streams and that we last processed - * {@code lastGoodStreamId}, or zero if no streams were processed. + * Tell the peer to stop creating streams and that we last processed {@code lastGoodStreamId}, or + * zero if no streams were processed. * - * @param lastGoodStreamId the last stream ID processed, or zero if no - * streams were processed. + * @param lastGoodStreamId the last stream ID processed, or zero if no streams were processed. * @param errorCode reason for closing the connection. * @param debugData only valid for HTTP/2; opaque debug data to send. */ void goAway(int lastGoodStreamId, ErrorCode errorCode, byte[] debugData) throws IOException; /** - * Inform peer that an additional {@code windowSizeIncrement} bytes can be - * sent on {@code streamId}, or the connection if {@code streamId} is zero. + * Inform peer that an additional {@code windowSizeIncrement} bytes can be sent on {@code + * streamId}, or the connection if {@code streamId} is zero. */ void windowUpdate(int streamId, long windowSizeIncrement) throws IOException; } diff --git a/okhttp/src/main/java/okhttp3/internal/framed/FramedConnection.java b/okhttp/src/main/java/okhttp3/internal/framed/FramedConnection.java index 7ad9a4084..26d511f91 100644 --- a/okhttp/src/main/java/okhttp3/internal/framed/FramedConnection.java +++ b/okhttp/src/main/java/okhttp3/internal/framed/FramedConnection.java @@ -15,9 +15,6 @@ */ package okhttp3.internal.framed; -import okhttp3.Protocol; -import okhttp3.internal.NamedRunnable; -import okhttp3.internal.Util; import java.io.Closeable; import java.io.IOException; import java.io.InterruptedIOException; @@ -34,6 +31,9 @@ import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.logging.Level; +import okhttp3.Protocol; +import okhttp3.internal.NamedRunnable; +import okhttp3.internal.Util; import okio.Buffer; import okio.BufferedSink; import okio.BufferedSource; @@ -44,13 +44,13 @@ import static okhttp3.internal.Internal.logger; import static okhttp3.internal.framed.Settings.DEFAULT_INITIAL_WINDOW_SIZE; /** - * A socket connection to a remote peer. A connection hosts streams which can - * send and receive data. + * A socket connection to a remote peer. A connection hosts streams which can send and receive + * data. * - *

      Many methods in this API are synchronous: the call is - * completed before the method returns. This is typical for Java but atypical - * for SPDY. This is motivated by exception transparency: an IOException that - * was triggered by a certain caller can be caught and handled by that caller. + *

      Many methods in this API are synchronous: the call is completed before the + * method returns. This is typical for Java but atypical for SPDY. This is motivated by exception + * transparency: an IOException that was triggered by a certain caller can be caught and handled by + * that caller. */ public final class FramedConnection implements Closeable { @@ -98,15 +98,14 @@ public final class FramedConnection implements Closeable { private int nextPingId; /** - * The total number of bytes consumed by the application, but not yet - * acknowledged by sending a {@code WINDOW_UPDATE} frame on this connection. + * The total number of bytes consumed by the application, but not yet acknowledged by sending a + * {@code WINDOW_UPDATE} frame on this connection. */ // Visible for testing long unacknowledgedBytesRead = 0; /** - * Count of bytes that can be written on the connection before receiving a - * window update. + * Count of bytes that can be written on the connection before receiving a window update. */ // Visible for testing long bytesLeftInWriteWindow; @@ -180,8 +179,7 @@ public final class FramedConnection implements Closeable { } /** - * Returns the number of {@link FramedStream#isOpen() open streams} on this - * connection. + * Returns the number of {@link FramedStream#isOpen() open streams} on this connection. */ public synchronized int openStreamCount() { return streams.size(); @@ -214,8 +212,8 @@ public final class FramedConnection implements Closeable { } /** - * Returns the time in ns when this connection became idle or Long.MAX_VALUE - * if connection is not idle. + * Returns the time in ns when this connection became idle or Long.MAX_VALUE if connection is not + * idle. */ public synchronized long getIdleStartTimeNs() { return idleStartTimeNs; @@ -224,10 +222,9 @@ public final class FramedConnection implements Closeable { /** * Returns a new server-initiated stream. * - * @param associatedStreamId the stream that triggered the sender to create - * this stream. - * @param out true to create an output stream that we can use to send data - * to the remote peer. Corresponds to {@code FLAG_FIN}. + * @param associatedStreamId the stream that triggered the sender to create this stream. + * @param out true to create an output stream that we can use to send data to the remote peer. + * Corresponds to {@code FLAG_FIN}. */ public FramedStream pushStream(int associatedStreamId, List

      requestHeaders, boolean out) throws IOException { @@ -240,9 +237,9 @@ public final class FramedConnection implements Closeable { * Returns a new locally-initiated stream. * * @param out true to create an output stream that we can use to send data to the remote peer. - * Corresponds to {@code FLAG_FIN}. + * Corresponds to {@code FLAG_FIN}. * @param in true to create an input stream that the remote peer can use to send data to us. - * Corresponds to {@code FLAG_UNIDIRECTIONAL}. + * Corresponds to {@code FLAG_UNIDIRECTIONAL}. */ public FramedStream newStream(List
      requestHeaders, boolean out, boolean in) throws IOException { @@ -337,8 +334,7 @@ public final class FramedConnection implements Closeable { } /** - * {@code delta} will be negative if a settings frame initial window is - * smaller than the last. + * {@code delta} will be negative if a settings frame initial window is smaller than the last. */ void addBytesToWriteWindow(long delta) { bytesLeftInWriteWindow += delta; @@ -372,8 +368,8 @@ public final class FramedConnection implements Closeable { } /** - * Sends a ping frame to the peer. Use the returned object to await the - * ping's response and observe its round trip time. + * Sends a ping frame to the peer. Use the returned object to await the ping's response and + * observe its round trip time. */ public Ping ping() throws IOException { Ping ping = new Ping(); @@ -421,10 +417,9 @@ public final class FramedConnection implements Closeable { } /** - * Degrades this connection such that new streams can neither be created - * locally, nor accepted from the remote peer. Existing streams are not - * impacted. This is intended to permit an endpoint to gracefully stop - * accepting new requests without harming previously established streams. + * Degrades this connection such that new streams can neither be created locally, nor accepted + * from the remote peer. Existing streams are not impacted. This is intended to permit an endpoint + * to gracefully stop accepting new requests without harming previously established streams. */ public void shutdown(ErrorCode statusCode) throws IOException { synchronized (frameWriter) { @@ -442,9 +437,8 @@ public final class FramedConnection implements Closeable { } /** - * Closes this connection. This cancels all open streams and unanswered - * pings. It closes the underlying input and output streams and shuts down - * internal executor services. + * Closes this connection. This cancels all open streams and unanswered pings. It closes the + * underlying input and output streams and shuts down internal executor services. */ @Override public void close() throws IOException { close(ErrorCode.NO_ERROR, ErrorCode.CANCEL); @@ -507,8 +501,8 @@ public final class FramedConnection implements Closeable { } /** - * Sends a connection header if the current variant requires it. This should - * be called after {@link Builder#build} for all new connections. + * Sends a connection header if the current variant requires it. This should be called after + * {@link Builder#build} for all new connections. */ public void sendConnectionPreface() throws IOException { frameWriter.connectionPreface(); @@ -543,8 +537,8 @@ public final class FramedConnection implements Closeable { private boolean client; /** - * @param client true if this peer initiated the connection; false if this - * peer accepted the connection. + * @param client true if this peer initiated the connection; false if this peer accepted the + * connection. */ public Builder(boolean client) throws IOException { this.client = client; @@ -585,8 +579,8 @@ public final class FramedConnection implements Closeable { } /** - * Methods in this class must not lock FrameWriter. If a method needs to - * write a frame, create an async task to do so. + * Methods in this class must not lock FrameWriter. If a method needs to write a frame, create an + * async task to do so. */ class Reader extends NamedRunnable implements FrameReader.Handler { final FrameReader frameReader; @@ -920,22 +914,19 @@ public final class FramedConnection implements Closeable { }; /** - * Handle a new stream from this connection's peer. Implementations should - * respond by either {@linkplain FramedStream#reply replying to the stream} - * or {@linkplain FramedStream#close closing it}. This response does not - * need to be synchronous. + * Handle a new stream from this connection's peer. Implementations should respond by either + * {@linkplain FramedStream#reply replying to the stream} or {@linkplain FramedStream#close + * closing it}. This response does not need to be synchronous. */ public abstract void onStream(FramedStream stream) throws IOException; /** - * Notification that the connection's peer's settings may have changed. - * Implementations should take appropriate action to handle the updated - * settings. + * Notification that the connection's peer's settings may have changed. Implementations should + * take appropriate action to handle the updated settings. * - *

      It is the implementation's responsibility to handle concurrent calls - * to this method. A remote peer that sends multiple settings frames will - * trigger multiple calls to this method, and those calls are not - * necessarily serialized. + *

      It is the implementation's responsibility to handle concurrent calls to this method. A + * remote peer that sends multiple settings frames will trigger multiple calls to this method, + * and those calls are not necessarily serialized. */ public void onSettings(FramedConnection connection) { } diff --git a/okhttp/src/main/java/okhttp3/internal/framed/FramedStream.java b/okhttp/src/main/java/okhttp3/internal/framed/FramedStream.java index 2532ee7eb..857a99c3c 100644 --- a/okhttp/src/main/java/okhttp3/internal/framed/FramedStream.java +++ b/okhttp/src/main/java/okhttp3/internal/framed/FramedStream.java @@ -37,17 +37,16 @@ public final class FramedStream { // blocking operations are performed while the lock is held. /** - * The total number of bytes consumed by the application (with {@link - * FramedDataSource#read}), but not yet acknowledged by sending a {@code - * WINDOW_UPDATE} frame on this stream. + * The total number of bytes consumed by the application (with {@link FramedDataSource#read}), but + * not yet acknowledged by sending a {@code WINDOW_UPDATE} frame on this stream. */ // Visible for testing long unacknowledgedBytesRead = 0; /** - * Count of bytes that can be written on the stream before receiving a - * window update. Even if this is positive, writes will block until there - * available bytes in {@code connection.bytesLeftInWriteWindow}. + * Count of bytes that can be written on the stream before receiving a window update. Even if this + * is positive, writes will block until there available bytes in {@code + * connection.bytesLeftInWriteWindow}. */ // guarded by this long bytesLeftInWriteWindow; @@ -67,9 +66,9 @@ public final class FramedStream { private final StreamTimeout writeTimeout = new StreamTimeout(); /** - * The reason why this stream was abnormally closed. If there are multiple - * reasons to abnormally close this stream (such as both peers closing it - * near-simultaneously) then this is the first reason known to this peer. + * The reason why this stream was abnormally closed. If there are multiple reasons to abnormally + * close this stream (such as both peers closing it near-simultaneously) then this is the first + * reason known to this peer. */ private ErrorCode errorCode = null; @@ -95,13 +94,14 @@ public final class FramedStream { /** * Returns true if this stream is open. A stream is open until either: + * *

        - *
      • A {@code SYN_RESET} frame abnormally terminates the stream. - *
      • Both input and output streams have transmitted all data and - * headers. + *
      • A {@code SYN_RESET} frame abnormally terminates the stream. + *
      • Both input and output streams have transmitted all data and headers. *
      - * Note that the input stream may continue to yield data even after a stream - * reports itself as not open. This is because input data is buffered. + * + *

      Note that the input stream may continue to yield data even after a stream reports itself as + * not open. This is because input data is buffered. */ public synchronized boolean isOpen() { if (errorCode != null) { @@ -130,8 +130,8 @@ public final class FramedStream { } /** - * Returns the stream's response headers, blocking if necessary if they - * have not been received yet. + * Returns the stream's response headers, blocking if necessary if they have not been received + * yet. */ public synchronized List

      getResponseHeaders() throws IOException { readTimeout.enter(); @@ -147,8 +147,8 @@ public final class FramedStream { } /** - * Returns the reason why this stream was closed, or null if it closed - * normally or has not yet been closed. + * Returns the reason why this stream was closed, or null if it closed normally or has not yet + * been closed. */ public synchronized ErrorCode getErrorCode() { return errorCode; @@ -157,8 +157,8 @@ public final class FramedStream { /** * Sends a reply to an incoming stream. * - * @param out true to create an output stream that we can use to send data - * to the remote peer. Corresponds to {@code FLAG_FIN}. + * @param out true to create an output stream that we can use to send data to the remote peer. + * Corresponds to {@code FLAG_FIN}. */ public void reply(List
      responseHeaders, boolean out) throws IOException { assert (!Thread.holdsLock(FramedStream.this)); @@ -199,8 +199,8 @@ public final class FramedStream { /** * Returns a sink that can be used to write data to the peer. * - * @throws IllegalStateException if this stream was initiated by the peer - * and a {@link #reply} has not yet been sent. + * @throws IllegalStateException if this stream was initiated by the peer and a {@link #reply} has + * not yet been sent. */ public Sink getSink() { synchronized (this) { @@ -212,8 +212,8 @@ public final class FramedStream { } /** - * Abnormally terminate this stream. This blocks until the {@code RST_STREAM} - * frame has been transmitted. + * Abnormally terminate this stream. This blocks until the {@code RST_STREAM} frame has been + * transmitted. */ public void close(ErrorCode rstStatusCode) throws IOException { if (!closeInternal(rstStatusCode)) { @@ -223,8 +223,8 @@ public final class FramedStream { } /** - * Abnormally terminate this stream. This enqueues a {@code RST_STREAM} - * frame and returns immediately. + * Abnormally terminate this stream. This enqueues a {@code RST_STREAM} frame and returns + * immediately. */ public void closeLater(ErrorCode errorCode) { if (!closeInternal(errorCode)) { @@ -307,9 +307,9 @@ public final class FramedStream { } /** - * A source that reads the incoming data frames of a stream. Although this - * class uses synchronization to safely receive incoming data frames, it is - * not intended for use by multiple readers. + * A source that reads the incoming data frames of a stream. Although this class uses + * synchronization to safely receive incoming data frames, it is not intended for use by multiple + * readers. */ private final class FramedDataSource implements Source { /** Buffer to receive data from the network into. Only accessed by the reader thread. */ @@ -325,8 +325,8 @@ public final class FramedStream { private boolean closed; /** - * True if either side has cleanly shut down this stream. We will - * receive no more bytes beyond those already in the buffer. + * True if either side has cleanly shut down this stream. We will receive no more bytes beyond + * those already in the buffer. */ private boolean finished; @@ -464,23 +464,21 @@ public final class FramedStream { } /** - * A sink that writes outgoing data frames of a stream. This class is not - * thread safe. + * A sink that writes outgoing data frames of a stream. This class is not thread safe. */ final class FramedDataSink implements Sink { private static final long EMIT_BUFFER_SIZE = 16384; /** - * Buffer of outgoing data. This batches writes of small writes into this sink as larges - * frames written to the outgoing connection. Batching saves the (small) framing overhead. + * Buffer of outgoing data. This batches writes of small writes into this sink as larges frames + * written to the outgoing connection. Batching saves the (small) framing overhead. */ private final Buffer sendBuffer = new Buffer(); private boolean closed; /** - * True if either side has cleanly shut down this stream. We shall send - * no more bytes. + * True if either side has cleanly shut down this stream. We shall send no more bytes. */ private boolean finished; @@ -561,8 +559,7 @@ public final class FramedStream { } /** - * {@code delta} will be negative if a settings frame initial window is - * smaller than the last. + * {@code delta} will be negative if a settings frame initial window is smaller than the last. */ void addBytesToWriteWindow(long delta) { bytesLeftInWriteWindow += delta; @@ -580,8 +577,8 @@ public final class FramedStream { } /** - * Like {@link #wait}, but throws an {@code InterruptedIOException} when - * interrupted instead of the more awkward {@link InterruptedException}. + * Like {@link #wait}, but throws an {@code InterruptedIOException} when interrupted instead of + * the more awkward {@link InterruptedException}. */ private void waitForIo() throws InterruptedIOException { try { @@ -592,9 +589,8 @@ public final class FramedStream { } /** - * The Okio timeout watchdog will call {@link #timedOut} if the timeout is - * reached. In that case we close the stream (asynchronously) which will - * notify the waiting thread. + * The Okio timeout watchdog will call {@link #timedOut} if the timeout is reached. In that case + * we close the stream (asynchronously) which will notify the waiting thread. */ class StreamTimeout extends AsyncTimeout { @Override protected void timedOut() { diff --git a/okhttp/src/main/java/okhttp3/internal/framed/HeadersMode.java b/okhttp/src/main/java/okhttp3/internal/framed/HeadersMode.java index 772d58f60..bc851ed78 100644 --- a/okhttp/src/main/java/okhttp3/internal/framed/HeadersMode.java +++ b/okhttp/src/main/java/okhttp3/internal/framed/HeadersMode.java @@ -32,16 +32,14 @@ public enum HeadersMode { } /** - * Returns true if it is an error these headers to be the initial headers of a - * response. + * Returns true if it is an error these headers to be the initial headers of a response. */ public boolean failIfHeadersAbsent() { return this == SPDY_HEADERS; } /** - * Returns true if it is an error these headers to be update existing headers - * of a response. + * Returns true if it is an error these headers to be update existing headers of a response. */ public boolean failIfHeadersPresent() { return this == SPDY_REPLY; diff --git a/okhttp/src/main/java/okhttp3/internal/framed/Hpack.java b/okhttp/src/main/java/okhttp3/internal/framed/Hpack.java index 0eb67743f..2b49784e9 100644 --- a/okhttp/src/main/java/okhttp3/internal/framed/Hpack.java +++ b/okhttp/src/main/java/okhttp3/internal/framed/Hpack.java @@ -33,9 +33,9 @@ import okio.Source; * * http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-12 * - * This implementation uses an array for the dynamic table and a list for - * indexed entries. Dynamic entries are added to the array, starting in the - * last position moving forward. When the array fills, it is doubled. + * This implementation uses an array for the dynamic table and a list for indexed entries. Dynamic + * entries are added to the array, starting in the last position moving forward. When the array + * fills, it is doubled. */ final class Hpack { private static final int PREFIX_4_BITS = 0x0f; @@ -136,11 +136,11 @@ final class Hpack { } /** - * Called by the reader when the peer sent {@link Settings#HEADER_TABLE_SIZE}. - * While this establishes the maximum dynamic table size, the - * {@link #maxDynamicTableByteCount} set during processing may limit the - * table size to a smaller amount. - *

      Evicts entries or clears the table as needed. + * Called by the reader when the peer sent {@link Settings#HEADER_TABLE_SIZE}. While this + * establishes the maximum dynamic table size, the {@link #maxDynamicTableByteCount} set during + * processing may limit the table size to a smaller amount. + * + *

      Evicts entries or clears the table as needed. */ void headerTableSizeSetting(int headerTableSizeSetting) { this.headerTableSizeSetting = headerTableSizeSetting; @@ -185,8 +185,8 @@ final class Hpack { } /** - * Read {@code byteCount} bytes of headers from the source stream. This - * implementation does not propagate the never indexed flag of a header. + * Read {@code byteCount} bytes of headers from the source stream. This implementation does not + * propagate the never indexed flag of a header. */ void readHeaders() throws IOException { while (!source.exhausted()) { @@ -420,8 +420,8 @@ final class Hpack { } /** - * An HTTP/2 response cannot contain uppercase header characters and must - * be treated as malformed. + * An HTTP/2 response cannot contain uppercase header characters and must be treated as + * malformed. */ private static ByteString checkLowercase(ByteString name) throws IOException { for (int i = 0, length = name.size(); i < length; i++) { diff --git a/okhttp/src/main/java/okhttp3/internal/framed/Http2.java b/okhttp/src/main/java/okhttp3/internal/framed/Http2.java index f0d4ce40d..78ca9ce79 100644 --- a/okhttp/src/main/java/okhttp3/internal/framed/Http2.java +++ b/okhttp/src/main/java/okhttp3/internal/framed/Http2.java @@ -15,10 +15,10 @@ */ package okhttp3.internal.framed; -import okhttp3.Protocol; import java.io.IOException; import java.util.List; import java.util.logging.Logger; +import okhttp3.Protocol; import okio.Buffer; import okio.BufferedSink; import okio.BufferedSource; @@ -26,18 +26,17 @@ import okio.ByteString; import okio.Source; import okio.Timeout; -import static okhttp3.internal.framed.Http2.FrameLogger.formatHeader; import static java.lang.String.format; import static java.util.logging.Level.FINE; +import static okhttp3.internal.framed.Http2.FrameLogger.formatHeader; import static okio.ByteString.EMPTY; /** * Read and write HTTP/2 frames. - *

      - * This implementation assumes we do not send an increased - * {@link Settings#getMaxFrameSize frame size setting} to the peer. Hence, we - * expect all frames to have a max length of {@link #INITIAL_MAX_FRAME_SIZE}. - *

      http://tools.ietf.org/html/draft-ietf-httpbis-http2-17 + * + *

      This implementation assumes we do not send an increased {@link Settings#getMaxFrameSize frame + * size setting} to the peer. Hence, we expect all frames to have a max length of {@link + * #INITIAL_MAX_FRAME_SIZE}.

      http://tools.ietf.org/html/draft-ietf-httpbis-http2-17 */ public final class Http2 implements Variant { private static final Logger logger = Logger.getLogger(FrameLogger.class.getName()); @@ -73,8 +72,7 @@ public final class Http2 implements Variant { static final byte FLAG_COMPRESSED = 0x20; // Used for data. /** - * Creates a frame reader with max header table size of 4096 and data frame - * compression disabled. + * Creates a frame reader with max header table size of 4096 and data frame compression disabled. */ @Override public FrameReader newReader(BufferedSource source, boolean client) { return new Reader(source, 4096, client); @@ -505,8 +503,11 @@ public final class Http2 implements Variant { for (int i = 0; i < Settings.COUNT; i++) { if (!settings.isSet(i)) continue; int id = i; - if (id == 4) id = 3; // SETTINGS_MAX_CONCURRENT_STREAMS renumbered. - else if (id == 7) id = 4; // SETTINGS_INITIAL_WINDOW_SIZE renumbered. + if (id == 4) { + id = 3; // SETTINGS_MAX_CONCURRENT_STREAMS renumbered. + } else if (id == 7) { + id = 4; // SETTINGS_INITIAL_WINDOW_SIZE renumbered. + } sink.writeShort(id); sink.writeInt(settings.get(i)); } @@ -585,9 +586,8 @@ public final class Http2 implements Variant { } /** - * Decompression of the header block occurs above the framing layer. This - * class lazily reads continuation frames as they are needed by {@link - * Hpack.Reader#readHeaders()}. + * Decompression of the header block occurs above the framing layer. This class lazily reads + * continuation frames as they are needed by {@link Hpack.Reader#readHeaders()}. */ static final class ContinuationSource implements Source { private final BufferedSource source; @@ -657,8 +657,7 @@ public final class Http2 implements Variant { *

* Where direction is {@code <<} for inbound and {@code >>} for outbound. * - *

For example, the following would indicate a HEAD request sent from - * the client. + *

For example, the following would indicate a HEAD request sent from the client. *

    * {@code
    *   << 0x0000000f    12 HEADERS       END_HEADERS|END_STREAM
@@ -675,8 +674,8 @@ public final class Http2 implements Variant {
     }
 
     /**
-     * Looks up valid string representing flags from the table. Invalid
-     * combinations are represented in binary.
+     * Looks up valid string representing flags from the table. Invalid combinations are represented
+     * in binary.
      */
     // Visible for testing.
     static String formatFlags(byte type, byte flags) {
@@ -716,8 +715,8 @@ public final class Http2 implements Variant {
     };
 
     /**
-     * Lookup table for valid flags for DATA, HEADERS, CONTINUATION. Invalid
-     * combinations are represented in binary.
+     * Lookup table for valid flags for DATA, HEADERS, CONTINUATION. Invalid combinations are
+     * represented in binary.
      */
     private static final String[] FLAGS = new String[0x40]; // Highest bit flag is 0x20.
     private static final String[] BINARY = new String[256];
@@ -734,7 +733,7 @@ public final class Http2 implements Variant {
 
       FLAGS[FLAG_PADDED] = "PADDED";
       for (int prefixFlag : prefixFlags) {
-         FLAGS[prefixFlag | FLAG_PADDED] = FLAGS[prefixFlag] + "|PADDED";
+        FLAGS[prefixFlag | FLAG_PADDED] = FLAGS[prefixFlag] + "|PADDED";
       }
 
       FLAGS[FLAG_END_HEADERS] = "END_HEADERS"; // Same as END_PUSH_PROMISE.
@@ -759,13 +758,13 @@ public final class Http2 implements Variant {
 
   private static int readMedium(BufferedSource source) throws IOException {
     return (source.readByte() & 0xff) << 16
-        |  (source.readByte() & 0xff) <<  8
-        |  (source.readByte() & 0xff);
+        | (source.readByte() & 0xff) << 8
+        | (source.readByte() & 0xff);
   }
 
   private static void writeMedium(BufferedSink sink, int i) throws IOException {
     sink.writeByte((i >>> 16) & 0xff);
-    sink.writeByte((i >>>  8) & 0xff);
-    sink.writeByte(i          & 0xff);
+    sink.writeByte((i >>> 8) & 0xff);
+    sink.writeByte(i & 0xff);
   }
 }
diff --git a/okhttp/src/main/java/okhttp3/internal/framed/Huffman.java b/okhttp/src/main/java/okhttp3/internal/framed/Huffman.java
index 63b6c3945..0c7f3012a 100644
--- a/okhttp/src/main/java/okhttp3/internal/framed/Huffman.java
+++ b/okhttp/src/main/java/okhttp3/internal/framed/Huffman.java
@@ -20,12 +20,13 @@ import java.io.IOException;
 import java.io.OutputStream;
 
 /**
- * This class was originally composed from the following classes in
- * Twitter Hpack.
+ * This class was originally composed from the following classes in Twitter Hpack.
+ *
  * 
    - *
  • {@code com.twitter.hpack.HuffmanEncoder}
  • - *
  • {@code com.twitter.hpack.HuffmanDecoder}
  • - *
  • {@code com.twitter.hpack.HpackUtil}
  • + *
  • {@code com.twitter.hpack.HuffmanEncoder}
  • + *
  • {@code com.twitter.hpack.HuffmanDecoder}
  • + *
  • {@code com.twitter.hpack.HpackUtil}
  • *
*/ class Huffman { diff --git a/okhttp/src/main/java/okhttp3/internal/framed/NameValueBlockReader.java b/okhttp/src/main/java/okhttp3/internal/framed/NameValueBlockReader.java index 8994722cb..75cd9594f 100644 --- a/okhttp/src/main/java/okhttp3/internal/framed/NameValueBlockReader.java +++ b/okhttp/src/main/java/okhttp3/internal/framed/NameValueBlockReader.java @@ -29,18 +29,17 @@ import okio.Okio; import okio.Source; /** - * Reads a SPDY/3 Name/Value header block. This class is made complicated by the - * requirement that we're strict with which bytes we put in the compressed bytes - * buffer. We need to put all compressed bytes into that buffer -- but no other - * bytes. + * Reads a SPDY/3 Name/Value header block. This class is made complicated by the requirement that + * we're strict with which bytes we put in the compressed bytes buffer. We need to put all + * compressed bytes into that buffer -- but no other bytes. */ class NameValueBlockReader { /** This source transforms compressed bytes into uncompressed bytes. */ private final InflaterSource inflaterSource; /** - * How many compressed bytes must be read into inflaterSource before - * {@link #readNameValueBlock} returns. + * How many compressed bytes must be read into inflaterSource before {@link #readNameValueBlock} + * returns. */ private int compressedLimit; diff --git a/okhttp/src/main/java/okhttp3/internal/framed/Ping.java b/okhttp/src/main/java/okhttp3/internal/framed/Ping.java index 31adb1dd8..d3e0b428d 100644 --- a/okhttp/src/main/java/okhttp3/internal/framed/Ping.java +++ b/okhttp/src/main/java/okhttp3/internal/framed/Ping.java @@ -47,9 +47,8 @@ public final class Ping { } /** - * Returns the round trip time for this ping in nanoseconds, waiting for the - * response to arrive if necessary. Returns -1 if the response was - * canceled. + * Returns the round trip time for this ping in nanoseconds, waiting for the response to arrive if + * necessary. Returns -1 if the response was canceled. */ public long roundTripTime() throws InterruptedException { latch.await(); @@ -57,9 +56,8 @@ public final class Ping { } /** - * Returns the round trip time for this ping in nanoseconds, or -1 if the - * response was canceled, or -2 if the timeout elapsed before the round - * trip completed. + * Returns the round trip time for this ping in nanoseconds, or -1 if the response was canceled, + * or -2 if the timeout elapsed before the round trip completed. */ public long roundTripTime(long timeout, TimeUnit unit) throws InterruptedException { if (latch.await(timeout, unit)) { diff --git a/okhttp/src/main/java/okhttp3/internal/framed/PushObserver.java b/okhttp/src/main/java/okhttp3/internal/framed/PushObserver.java index 72d294812..95dd41a5b 100644 --- a/okhttp/src/main/java/okhttp3/internal/framed/PushObserver.java +++ b/okhttp/src/main/java/okhttp3/internal/framed/PushObserver.java @@ -21,37 +21,36 @@ import okhttp3.Protocol; import okio.BufferedSource; /** - * {@link Protocol#HTTP_2 HTTP/2} only. - * Processes server-initiated HTTP requests on the client. Implementations must - * quickly dispatch callbacks to avoid creating a bottleneck. + * {@link Protocol#HTTP_2 HTTP/2} only. Processes server-initiated HTTP requests on the client. + * Implementations must quickly dispatch callbacks to avoid creating a bottleneck. + * + *

While {@link #onReset} may occur at any time, the following callbacks are expected in order, + * correlated by stream ID. * - *

While {@link #onReset} may occur at any time, the following callbacks are - * expected in order, correlated by stream ID. *

    - *
  • {@link #onRequest}
  • - *
  • {@link #onHeaders} (unless canceled)
  • - *
  • {@link #onData} (optional sequence of data frames)
  • + *
  • {@link #onRequest}
  • {@link #onHeaders} (unless canceled) + *
  • {@link #onData} (optional sequence of data frames) *
* - *

As a stream ID is scoped to a single HTTP/2 connection, implementations - * which target multiple connections should expect repetition of stream IDs. + *

As a stream ID is scoped to a single HTTP/2 connection, implementations which target multiple + * connections should expect repetition of stream IDs. * - *

Return true to request cancellation of a pushed stream. Note that this - * does not guarantee future frames won't arrive on the stream ID. + *

Return true to request cancellation of a pushed stream. Note that this does not guarantee + * future frames won't arrive on the stream ID. */ public interface PushObserver { /** * Describes the request that the server intends to push a response for. * * @param streamId server-initiated stream ID: an even number. - * @param requestHeaders minimally includes {@code :method}, {@code :scheme}, - * {@code :authority}, and (@code :path}. + * @param requestHeaders minimally includes {@code :method}, {@code :scheme}, {@code :authority}, + * and (@code :path}. */ boolean onRequest(int streamId, List

requestHeaders); /** - * The response headers corresponding to a pushed request. When {@code last} - * is true, there are no data frames to follow. + * The response headers corresponding to a pushed request. When {@code last} is true, there are + * no data frames to follow. * * @param streamId server-initiated stream ID: an even number. * @param responseHeaders minimally includes {@code :status}. @@ -60,8 +59,8 @@ public interface PushObserver { boolean onHeaders(int streamId, List
responseHeaders, boolean last); /** - * A chunk of response data corresponding to a pushed request. This data - * must either be read or skipped. + * A chunk of response data corresponding to a pushed request. This data must either be read or + * skipped. * * @param streamId server-initiated stream ID: an even number. * @param source location of data corresponding with this stream ID. diff --git a/okhttp/src/main/java/okhttp3/internal/framed/Settings.java b/okhttp/src/main/java/okhttp3/internal/framed/Settings.java index 598b0680b..f4eab0173 100644 --- a/okhttp/src/main/java/okhttp3/internal/framed/Settings.java +++ b/okhttp/src/main/java/okhttp3/internal/framed/Settings.java @@ -23,8 +23,8 @@ import java.util.Arrays; */ public final class Settings { /** - * From the SPDY/3 and HTTP/2 specs, the default initial window size for all - * streams is 64 KiB. (Chrome 25 uses 10 MiB). + * From the SPDY/3 and HTTP/2 specs, the default initial window size for all streams is 64 KiB. + * (Chrome 25 uses 10 MiB). */ static final int DEFAULT_INITIAL_WINDOW_SIZE = 64 * 1024; @@ -212,8 +212,8 @@ public final class Settings { } /** - * Returns true if this user agent should use this setting in future spdy/3 - * connections to the same host. + * Returns true if this user agent should use this setting in future spdy/3 connections to the + * same host. */ boolean persistValue(int id) { int bit = 1 << id; @@ -227,8 +227,8 @@ public final class Settings { } /** - * Writes {@code other} into this. If any setting is populated by this and - * {@code other}, the value and flags from {@code other} will be kept. + * Writes {@code other} into this. If any setting is populated by this and {@code other}, the + * value and flags from {@code other} will be kept. */ void merge(Settings other) { for (int i = 0; i < COUNT; i++) { diff --git a/okhttp/src/main/java/okhttp3/internal/framed/Spdy3.java b/okhttp/src/main/java/okhttp3/internal/framed/Spdy3.java index 11ac226a7..72053e006 100644 --- a/okhttp/src/main/java/okhttp3/internal/framed/Spdy3.java +++ b/okhttp/src/main/java/okhttp3/internal/framed/Spdy3.java @@ -15,13 +15,13 @@ */ package okhttp3.internal.framed; -import okhttp3.Protocol; -import okhttp3.internal.Util; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.ProtocolException; import java.util.List; import java.util.zip.Deflater; +import okhttp3.Protocol; +import okhttp3.internal.Util; import okio.Buffer; import okio.BufferedSink; import okio.BufferedSource; @@ -30,8 +30,7 @@ import okio.DeflaterSink; import okio.Okio; /** - * Read and write spdy/3.1 frames. - * http://www.chromium.org/spdy/spdy-protocol/spdy-protocol-draft3-1 + * Read and write spdy/3.1 frames. http://www.chromium.org/spdy/spdy-protocol/spdy-protocol-draft3-1 */ public final class Spdy3 implements Variant { @@ -55,6 +54,7 @@ public final class Spdy3 implements Variant { static final int VERSION = 3; static final byte[] DICTIONARY; + static { try { DICTIONARY = ("\u0000\u0000\u0000\u0007options\u0000\u0000\u0000\u0004hea" @@ -119,8 +119,8 @@ public final class Spdy3 implements Variant { } /** - * Send the next frame to {@code handler}. Returns true unless there are no - * more frames on the stream. + * Send the next frame to {@code handler}. Returns true unless there are no more frames on the + * stream. */ @Override public boolean nextFrame(Handler handler) throws IOException { int w1; diff --git a/okhttp/src/main/java/okhttp3/internal/http/CacheRequest.java b/okhttp/src/main/java/okhttp3/internal/http/CacheRequest.java index 18a40c19f..12c3134e8 100644 --- a/okhttp/src/main/java/okhttp3/internal/http/CacheRequest.java +++ b/okhttp/src/main/java/okhttp3/internal/http/CacheRequest.java @@ -20,5 +20,6 @@ import okio.Sink; public interface CacheRequest { Sink body() throws IOException; + void abort(); } diff --git a/okhttp/src/main/java/okhttp3/internal/http/CacheStrategy.java b/okhttp/src/main/java/okhttp3/internal/http/CacheStrategy.java index 56fa0fefa..a2f513d1d 100644 --- a/okhttp/src/main/java/okhttp3/internal/http/CacheStrategy.java +++ b/okhttp/src/main/java/okhttp3/internal/http/CacheStrategy.java @@ -1,10 +1,10 @@ package okhttp3.internal.http; +import java.util.Date; import okhttp3.CacheControl; import okhttp3.Headers; import okhttp3.Request; import okhttp3.Response; -import java.util.Date; import static java.net.HttpURLConnection.HTTP_BAD_METHOD; import static java.net.HttpURLConnection.HTTP_GONE; @@ -20,12 +20,12 @@ import static java.net.HttpURLConnection.HTTP_REQ_TOO_LONG; import static java.util.concurrent.TimeUnit.SECONDS; /** - * Given a request and cached response, this figures out whether to use the - * network, the cache, or both. + * Given a request and cached response, this figures out whether to use the network, the cache, or + * both. * - *

Selecting a cache strategy may add conditions to the request (like the - * "If-Modified-Since" header for conditional GETs) or warnings to the cached - * response (if the cached data is potentially stale). + *

Selecting a cache strategy may add conditions to the request (like the "If-Modified-Since" + * header for conditional GETs) or warnings to the cached response (if the cached data is + * potentially stale). */ public final class CacheStrategy { /** The request to send on the network, or null if this call doesn't use the network. */ @@ -39,10 +39,7 @@ public final class CacheStrategy { this.cacheResponse = cacheResponse; } - /** - * Returns true if {@code response} can be stored to later serve another - * request. - */ + /** Returns true if {@code response} can be stored to later serve another request. */ public static boolean isCacheable(Response response, Request request) { // Always go to network for uncacheable response codes (RFC 7231 section 6.1), // This implementation doesn't support caching partial content. @@ -58,8 +55,8 @@ public final class CacheStrategy { case HTTP_REQ_TOO_LONG: case HTTP_NOT_IMPLEMENTED: case StatusLine.HTTP_PERM_REDIRECT: - // These codes can be cached unless headers forbid it. - break; + // These codes can be cached unless headers forbid it. + break; case HTTP_MOVED_TEMP: case StatusLine.HTTP_TEMP_REDIRECT: @@ -97,20 +94,20 @@ public final class CacheStrategy { private String lastModifiedString; /** - * The expiration date of the cached response, if known. If both this field - * and the max age are set, the max age is preferred. + * The expiration date of the cached response, if known. If both this field and the max age are + * set, the max age is preferred. */ private Date expires; /** - * Extension header set by OkHttp specifying the timestamp when the cached - * HTTP request was first initiated. + * Extension header set by OkHttp specifying the timestamp when the cached HTTP request was + * first initiated. */ private long sentRequestMillis; /** - * Extension header set by OkHttp specifying the timestamp when the cached - * HTTP response was first received. + * Extension header set by OkHttp specifying the timestamp when the cached HTTP response was + * first received. */ private long receivedResponseMillis; @@ -152,8 +149,7 @@ public final class CacheStrategy { } /** - * Returns a strategy to satisfy {@code request} using the a cached response - * {@code response}. + * Returns a strategy to satisfy {@code request} using the a cached response {@code response}. */ public CacheStrategy get() { CacheStrategy candidate = getCandidate(); @@ -237,8 +233,8 @@ public final class CacheStrategy { } /** - * Returns the number of milliseconds that the response was fresh for, - * starting from the served date. + * Returns the number of milliseconds that the response was fresh for, starting from the served + * date. */ private long computeFreshnessLifetime() { CacheControl responseCaching = cacheResponse.cacheControl(); @@ -266,8 +262,8 @@ public final class CacheStrategy { } /** - * Returns the current age of the response, in milliseconds. The calculation - * is specified by RFC 2616, 13.2.3 Age Calculations. + * Returns the current age of the response, in milliseconds. The calculation is specified by RFC + * 2616, 13.2.3 Age Calculations. */ private long cacheResponseAge() { long apparentReceivedAge = servedDate != null @@ -282,18 +278,17 @@ public final class CacheStrategy { } /** - * Returns true if computeFreshnessLifetime used a heuristic. If we used a - * heuristic to serve a cached response older than 24 hours, we are required - * to attach a warning. + * Returns true if computeFreshnessLifetime used a heuristic. If we used a heuristic to serve a + * cached response older than 24 hours, we are required to attach a warning. */ private boolean isFreshnessLifetimeHeuristic() { return cacheResponse.cacheControl().maxAgeSeconds() == -1 && expires == null; } /** - * Returns true if the request contains conditions that save the server from - * sending a response that the client has locally. When a request is enqueued - * with its own conditions, the built-in response cache won't be used. + * Returns true if the request contains conditions that save the server from sending a response + * that the client has locally. When a request is enqueued with its own conditions, the built-in + * response cache won't be used. */ private static boolean hasConditions(Request request) { return request.header("If-Modified-Since") != null || request.header("If-None-Match") != null; diff --git a/okhttp/src/main/java/okhttp3/internal/http/HeaderParser.java b/okhttp/src/main/java/okhttp3/internal/http/HeaderParser.java index 085f6f144..6cb323280 100644 --- a/okhttp/src/main/java/okhttp3/internal/http/HeaderParser.java +++ b/okhttp/src/main/java/okhttp3/internal/http/HeaderParser.java @@ -18,9 +18,8 @@ package okhttp3.internal.http; public final class HeaderParser { /** - * Returns the next index in {@code input} at or after {@code pos} that - * contains a character from {@code characters}. Returns the input length if - * none of the requested characters can be found. + * Returns the next index in {@code input} at or after {@code pos} that contains a character from + * {@code characters}. Returns the input length if none of the requested characters can be found. */ public static int skipUntil(String input, int pos, String characters) { for (; pos < input.length(); pos++) { @@ -32,8 +31,8 @@ public final class HeaderParser { } /** - * Returns the next non-whitespace character in {@code input} that is white - * space. Result is undefined if input contains newline characters. + * Returns the next non-whitespace character in {@code input} that is white space. Result is + * undefined if input contains newline characters. */ public static int skipWhitespace(String input, int pos) { for (; pos < input.length(); pos++) { @@ -46,8 +45,8 @@ public final class HeaderParser { } /** - * Returns {@code value} as a positive integer, or 0 if it is negative, or - * {@code defaultValue} if it cannot be parsed. + * Returns {@code value} as a positive integer, or 0 if it is negative, or {@code defaultValue} if + * it cannot be parsed. */ public static int parseSeconds(String value, int defaultValue) { try { diff --git a/okhttp/src/main/java/okhttp3/internal/http/Http1xStream.java b/okhttp/src/main/java/okhttp3/internal/http/Http1xStream.java index f64dec89a..39ff4d478 100644 --- a/okhttp/src/main/java/okhttp3/internal/http/Http1xStream.java +++ b/okhttp/src/main/java/okhttp3/internal/http/Http1xStream.java @@ -40,23 +40,24 @@ import static okhttp3.internal.Util.checkOffsetAndCount; import static okhttp3.internal.http.StatusLine.HTTP_CONTINUE; /** - * A socket connection that can be used to send HTTP/1.1 messages. This class - * strictly enforces the following lifecycle: + * A socket connection that can be used to send HTTP/1.1 messages. This class strictly enforces the + * following lifecycle: + * *

    - *
  1. {@link #writeRequest Send request headers}. - *
  2. Open a sink to write the request body. Either {@link - * #newFixedLengthSink fixed-length} or {@link #newChunkedSink chunked}. - *
  3. Write to and then close that sink. - *
  4. {@link #readResponse Read response headers}. - *
  5. Open a source to read the response body. Either {@link - * #newFixedLengthSource fixed-length}, {@link #newChunkedSource chunked} - * or {@link #newUnknownLengthSource unknown length}. - *
  6. Read from and close that source. + *
  7. {@linkplain #writeRequest Send request headers}. + *
  8. Open a sink to write the request body. Either {@linkplain #newFixedLengthSink + * fixed-length} or {@link #newChunkedSink chunked}. + *
  9. Write to and then close that sink. + *
  10. {@linkplain #readResponse Read response headers}. + *
  11. Open a source to read the response body. Either {@linkplain #newFixedLengthSource + * fixed-length}, {@linkplain #newChunkedSource chunked} or {@linkplain + * #newUnknownLengthSource unknown length}. + *
  12. Read from and close that source. *
- *

Exchanges that do not have a request body may skip creating and closing - * the request body. Exchanges that do not have a response body can call {@link - * #newFixedLengthSource(long) newFixedLengthSource(0)} and may skip reading and - * closing that source. + * + *

Exchanges that do not have a request body may skip creating and closing the request body. + * Exchanges that do not have a response body can call {@link #newFixedLengthSource(long) + * newFixedLengthSource(0)} and may skip reading and closing that source. */ public final class Http1xStream implements HttpStream { private static final int STATE_IDLE = 0; // Idle connections are ready to write request headers. @@ -107,14 +108,12 @@ public final class Http1xStream implements HttpStream { /** * Prepares the HTTP headers and sends them to the server. * - *

For streaming requests with a body, headers must be prepared - * before the output stream has been written to. Otherwise - * the body would need to be buffered! + *

For streaming requests with a body, headers must be prepared before the + * output stream has been written to. Otherwise the body would need to be buffered! * - *

For non-streaming requests with a body, headers must be prepared - * after the output stream has been written to and closed. - * This ensures that the {@code Content-Length} header field receives the - * proper value. + *

For non-streaming requests with a body, headers must be prepared after the + * output stream has been written to and closed. This ensures that the {@code Content-Length} + * header field receives the proper value. */ @Override public void writeRequestHeaders(Request request) throws IOException { httpEngine.writingRequestHeaders(); @@ -165,7 +164,7 @@ public final class Http1xStream implements HttpStream { public void writeRequest(Headers headers, String requestLine) throws IOException { if (state != STATE_IDLE) throw new IllegalStateException("state: " + state); sink.writeUtf8(requestLine).writeUtf8("\r\n"); - for (int i = 0, size = headers.size(); i < size; i ++) { + for (int i = 0, size = headers.size(); i < size; i++) { sink.writeUtf8(headers.name(i)) .writeUtf8(": ") .writeUtf8(headers.value(i)) @@ -304,9 +303,8 @@ public final class Http1xStream implements HttpStream { } /** - * An HTTP body with alternating chunk sizes and chunk bodies. It is the - * caller's responsibility to buffer chunks; typically by using a buffered - * sink with this sink. + * An HTTP body with alternating chunk sizes and chunk bodies. It is the caller's responsibility + * to buffer chunks; typically by using a buffered sink with this sink. */ private final class ChunkedSink implements Sink { private final ForwardingTimeout timeout = new ForwardingTimeout(sink.timeout()); @@ -349,8 +347,8 @@ public final class Http1xStream implements HttpStream { } /** - * Closes the cache entry and makes the socket available for reuse. This - * should be invoked when the end of the body has been reached. + * Closes the cache entry and makes the socket available for reuse. This should be invoked when + * the end of the body has been reached. */ protected final void endOfInput(boolean reuseConnection) throws IOException { if (state == STATE_CLOSED) return; diff --git a/okhttp/src/main/java/okhttp3/internal/http/Http2xStream.java b/okhttp/src/main/java/okhttp3/internal/http/Http2xStream.java index a6c272414..6aaece8e0 100644 --- a/okhttp/src/main/java/okhttp3/internal/http/Http2xStream.java +++ b/okhttp/src/main/java/okhttp3/internal/http/Http2xStream.java @@ -16,6 +16,14 @@ package okhttp3.internal.http; +import java.io.IOException; +import java.net.ProtocolException; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.concurrent.TimeUnit; import okhttp3.Headers; import okhttp3.Protocol; import okhttp3.Request; @@ -26,14 +34,6 @@ import okhttp3.internal.framed.ErrorCode; import okhttp3.internal.framed.FramedConnection; import okhttp3.internal.framed.FramedStream; import okhttp3.internal.framed.Header; -import java.io.IOException; -import java.net.ProtocolException; -import java.util.ArrayList; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Locale; -import java.util.Set; -import java.util.concurrent.TimeUnit; import okio.ByteString; import okio.ForwardingSource; import okio.Okio; @@ -152,9 +152,9 @@ public final class Http2xStream implements HttpStream { } /** - * Returns a list of alternating names and values containing a SPDY request. - * Names are all lowercase. No names are repeated. If any name has multiple - * values, they are concatenated using "\0" as a delimiter. + * Returns a list of alternating names and values containing a SPDY request. Names are all + * lowercase. No names are repeated. If any name has multiple values, they are concatenated using + * "\0" as a delimiter. */ public static List

spdy3HeadersList(Request request) { Headers headers = request.headers(); diff --git a/okhttp/src/main/java/okhttp3/internal/http/HttpDate.java b/okhttp/src/main/java/okhttp3/internal/http/HttpDate.java index 99411fb92..3f8d3149d 100644 --- a/okhttp/src/main/java/okhttp3/internal/http/HttpDate.java +++ b/okhttp/src/main/java/okhttp3/internal/http/HttpDate.java @@ -51,7 +51,7 @@ public final class HttpDate { "EEE, dd MMM yyyy HH:mm:ss zzz", // RFC 822, updated by RFC 1123 with any TZ "EEEE, dd-MMM-yy HH:mm:ss zzz", // RFC 850, obsoleted by RFC 1036 with any TZ. "EEE MMM d HH:mm:ss yyyy", // ANSI C's asctime() format - // Alternative formats. + // Alternative formats. "EEE, dd-MMM-yyyy HH:mm:ss z", "EEE, dd-MMM-yyyy HH-mm-ss z", "EEE, dd MMM yy HH:mm:ss z", diff --git a/okhttp/src/main/java/okhttp3/internal/http/HttpEngine.java b/okhttp/src/main/java/okhttp3/internal/http/HttpEngine.java index a53a2bd7b..aa05b767a 100644 --- a/okhttp/src/main/java/okhttp3/internal/http/HttpEngine.java +++ b/okhttp/src/main/java/okhttp3/internal/http/HttpEngine.java @@ -68,22 +68,15 @@ import static okhttp3.internal.http.StatusLine.HTTP_PERM_REDIRECT; import static okhttp3.internal.http.StatusLine.HTTP_TEMP_REDIRECT; /** - * Handles a single HTTP request/response pair. Each HTTP engine follows this - * lifecycle: - *
    - *
  1. It is created. - *
  2. The HTTP request message is sent with sendRequest(). Once the request - * is sent it is an error to modify the request headers. After - * sendRequest() has been called the request body can be written to if - * it exists. - *
  3. The HTTP response message is read with readResponse(). After the - * response has been read the response headers and body can be read. - * All responses have a response body input stream, though in some - * instances this stream is empty. - *
+ * Handles a single HTTP request/response pair. Each HTTP engine follows this lifecycle:
  1. It + * is created.
  2. The HTTP request message is sent with sendRequest(). Once the request is sent it + * is an error to modify the request headers. After sendRequest() has been called the request body + * can be written to if it exists.
  3. The HTTP response message is read with readResponse(). After + * the response has been read the response headers and body can be read. All responses have a + * response body input stream, though in some instances this stream is empty.
* - *

The request and response may be served by the HTTP response cache, by the - * network, or by both in the event of a conditional GET. + *

The request and response may be served by the HTTP response cache, by the network, or by both + * in the event of a conditional GET. */ public final class HttpEngine { /** @@ -96,9 +89,11 @@ public final class HttpEngine { @Override public MediaType contentType() { return null; } + @Override public long contentLength() { return 0; } + @Override public BufferedSource source() { return new Buffer(); } @@ -114,43 +109,40 @@ public final class HttpEngine { long sentRequestMillis = -1; /** - * True if this client added an "Accept-Encoding: gzip" header field and is - * therefore responsible for also decompressing the transfer stream. + * True if this client added an "Accept-Encoding: gzip" header field and is therefore responsible + * for also decompressing the transfer stream. */ private boolean transparentGzip; /** - * True if the request body must be completely buffered before transmission; - * false if it can be streamed. Buffering has two advantages: we don't need - * the content-length in advance and we can retransmit if necessary. The - * upside of streaming is that we can save memory. + * True if the request body must be completely buffered before transmission; false if it can be + * streamed. Buffering has two advantages: we don't need the content-length in advance and we can + * retransmit if necessary. The upside of streaming is that we can save memory. */ public final boolean bufferRequestBody; /** - * The original application-provided request. Never modified by OkHttp. When - * follow-up requests are necessary, they are derived from this request. + * The original application-provided request. Never modified by OkHttp. When follow-up requests + * are necessary, they are derived from this request. */ private final Request userRequest; /** - * The request to send on the network, or null for no network request. This is - * derived from the user request, and customized to support OkHttp features - * like compression and caching. + * The request to send on the network, or null for no network request. This is derived from the + * user request, and customized to support OkHttp features like compression and caching. */ private Request networkRequest; /** - * The cached response, or null if the cache doesn't exist or cannot be used - * for this request. Conditional caching means this may be non-null even when - * the network request is non-null. Never modified by OkHttp. + * The cached response, or null if the cache doesn't exist or cannot be used for this request. + * Conditional caching means this may be non-null even when the network request is non-null. Never + * modified by OkHttp. */ private Response cacheResponse; /** - * The user-visible response. This is derived from either the network - * response, cache response, or both. It is customized to support OkHttp - * features like compression and caching. + * The user-visible response. This is derived from either the network response, cache response, or + * both. It is customized to support OkHttp features like compression and caching. */ private Response userResponse; @@ -165,10 +157,10 @@ public final class HttpEngine { /** * @param request the HTTP request without a body. The body must be written via the engine's - * request body stream. - * @param callerWritesRequestBody true for the {@code HttpURLConnection}-style interaction - * model where control flow is returned to the calling application to write the request body - * before the response body is readable. + * request body stream. + * @param callerWritesRequestBody true for the {@code HttpURLConnection}-style interaction model + * where control flow is returned to the calling application to write the request body before the + * response body is readable. */ public HttpEngine(OkHttpClient client, Request request, boolean bufferRequestBody, boolean callerWritesRequestBody, boolean forWebSocket, StreamAllocation streamAllocation, @@ -186,16 +178,14 @@ public final class HttpEngine { } /** - * Figures out what the response source will be, and opens a socket to that - * source if necessary. Prepares the request headers and gets ready to start - * writing the request body if it exists. + * Figures out what the response source will be, and opens a socket to that source if necessary. + * Prepares the request headers and gets ready to start writing the request body if it exists. * * @throws RequestException if there was a problem with request setup. Unrecoverable. * @throws RouteException if the was a problem during connection via a specific route. Sometimes - * recoverable. See {@link #recover}. + * recoverable. See {@link #recover}. * @throws IOException if there was a problem while making a request. Sometimes recoverable. See - * {@link #recover(IOException)}. - * + * {@link #recover(IOException)}. */ public void sendRequest() throws RequestException, RouteException, IOException { if (cacheStrategy != null) return; // Already sent. @@ -252,7 +242,6 @@ public final class HttpEngine { requestBodyOut = httpStream.createRequestBody(networkRequest, contentLength); } } - } else { streamAllocation.release(); @@ -292,10 +281,9 @@ public final class HttpEngine { : response; } - /** - * Called immediately before the transport transmits HTTP request headers. - * This is used to observe the sent time should the request be cached. + * Called immediately before the transport transmits HTTP request headers. This is used to observe + * the sent time should the request be cached. */ public void writingRequestHeaders() { if (sentRequestMillis != -1) throw new IllegalStateException(); @@ -341,9 +329,9 @@ public final class HttpEngine { } /** - * Report and attempt to recover from a failure to communicate with a server. Returns a new - * HTTP engine that should be used for the retry if {@code e} is recoverable, or null if - * the failure is permanent. Requests with a body can only be recovered if the body is buffered. + * Report and attempt to recover from a failure to communicate with a server. Returns a new HTTP + * engine that should be used for the retry if {@code e} is recoverable, or null if the failure is + * permanent. Requests with a body can only be recovered if the body is buffered. */ public HttpEngine recover(IOException e, Sink requestBodyOut) { if (!streamAllocation.recover(e, requestBodyOut)) { @@ -386,9 +374,8 @@ public final class HttpEngine { } /** - * Configure the socket connection to be either pooled or closed when it is - * either exhausted or closed. If it is unneeded when this is called, it will - * be released immediately. + * Configure the socket connection to be either pooled or closed when it is either exhausted or + * closed. If it is unneeded when this is called, it will be released immediately. */ public void releaseStreamAllocation() throws IOException { streamAllocation.release(); @@ -463,8 +450,7 @@ public final class HttpEngine { } /** - * Returns true if the response must have a (possibly 0-length) body. - * See RFC 2616 section 4.3. + * Returns true if the response must have a (possibly 0-length) body. See RFC 2616 section 4.3. */ public static boolean hasBody(Response response) { // HEAD requests never yield a body regardless of the response headers. @@ -493,8 +479,8 @@ public final class HttpEngine { /** * Populates request with defaults and cookies. * - *

This client doesn't specify a default {@code Accept} header because it - * doesn't know what content types the application is interested in. + *

This client doesn't specify a default {@code Accept} header because it doesn't know what + * content types the application is interested in. */ private Request networkRequest(Request request) throws IOException { Request.Builder result = request.newBuilder(); @@ -533,8 +519,8 @@ public final class HttpEngine { } /** - * Flushes the remaining request header and body, parses the HTTP response - * headers and starts reading the HTTP response body if it exists. + * Flushes the remaining request header and body, parses the HTTP response headers and starts + * reading the HTTP response body if it exists. */ public void readResponse() throws IOException { if (userResponse != null) { @@ -552,10 +538,8 @@ public final class HttpEngine { if (forWebSocket) { httpStream.writeRequestHeaders(networkRequest); networkResponse = readNetworkResponse(); - } else if (!callerWritesRequestBody) { networkResponse = new NetworkInterceptorChain(0, networkRequest).proceed(networkRequest); - } else { // Emit the request body's buffer so that everything is in requestBodyOut. if (bufferedRequestBody != null && bufferedRequestBody.buffer().size() > 0) { @@ -799,8 +783,8 @@ public final class HttpEngine { } /** - * Returns true if {@code cached} should be used; false if {@code network} - * response should be used. + * Returns true if {@code cached} should be used; false if {@code network} response should be + * used. */ private static boolean validate(Response cached, Response network) { if (network.code() == HTTP_NOT_MODIFIED) { @@ -823,8 +807,7 @@ public final class HttpEngine { } /** - * Combines cached headers with a network headers as defined by RFC 2616, - * 13.5.3. + * Combines cached headers with a network headers as defined by RFC 2616, 13.5.3. */ private static Headers combine(Headers cachedHeaders, Headers networkHeaders) throws IOException { Headers.Builder result = new Headers.Builder(); @@ -861,9 +844,9 @@ public final class HttpEngine { } /** - * Figures out the HTTP request to make in response to receiving this engine's - * response. This will either add authentication headers or follow redirects. - * If a follow-up is either unnecessary or not applicable, this returns null. + * Figures out the HTTP request to make in response to receiving this engine's response. This will + * either add authentication headers or follow redirects. If a follow-up is either unnecessary or + * not applicable, this returns null. */ public Request followUpRequest() throws IOException { if (userResponse == null) throw new IllegalStateException(); @@ -891,7 +874,7 @@ public final class HttpEngine { // "If the 307 or 308 status code is received in response to a request other than GET // or HEAD, the user agent MUST NOT automatically redirect the request" if (!method.equals("GET") && !method.equals("HEAD")) { - return null; + return null; } // fall-through case HTTP_MULT_CHOICE: @@ -940,8 +923,8 @@ public final class HttpEngine { } /** - * Returns true if an HTTP request for {@code followUp} can reuse the - * connection used by this engine. + * Returns true if an HTTP request for {@code followUp} can reuse the connection used by this + * engine. */ public boolean sameConnection(HttpUrl followUp) { HttpUrl url = userRequest.url(); diff --git a/okhttp/src/main/java/okhttp3/internal/http/HttpStream.java b/okhttp/src/main/java/okhttp3/internal/http/HttpStream.java index 147197a03..d5fc94c7b 100644 --- a/okhttp/src/main/java/okhttp3/internal/http/HttpStream.java +++ b/okhttp/src/main/java/okhttp3/internal/http/HttpStream.java @@ -16,17 +16,17 @@ package okhttp3.internal.http; +import java.io.IOException; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; -import java.io.IOException; import okio.Sink; public interface HttpStream { /** - * The timeout to use while discarding a stream of input data. Since this is - * used for connection reuse, this timeout should be significantly less than - * the time it takes to establish a new connection. + * The timeout to use while discarding a stream of input data. Since this is used for connection + * reuse, this timeout should be significantly less than the time it takes to establish a new + * connection. */ int DISCARD_STREAM_TIMEOUT_MILLIS = 100; @@ -37,8 +37,7 @@ public interface HttpStream { void writeRequestHeaders(Request request) throws IOException; /** - * Sends the request body returned by {@link #createRequestBody} to the - * remote peer. + * Sends the request body returned by {@link #createRequestBody} to the remote peer. */ void writeRequestBody(RetryableSink requestBody) throws IOException; diff --git a/okhttp/src/main/java/okhttp3/internal/http/OkHeaders.java b/okhttp/src/main/java/okhttp3/internal/http/OkHeaders.java index a8316c0f0..4e924fd6e 100644 --- a/okhttp/src/main/java/okhttp3/internal/http/OkHeaders.java +++ b/okhttp/src/main/java/okhttp3/internal/http/OkHeaders.java @@ -47,8 +47,8 @@ public final class OkHeaders { public static final String RECEIVED_MILLIS = PREFIX + "-Received-Millis"; /** - * Synthetic response header: the selected - * {@link Protocol protocol} ("spdy/3.1", "http/1.1", etc). + * Synthetic response header: the selected {@link Protocol protocol} ("spdy/3.1", "http/1.1", + * etc). */ public static final String SELECTED_PROTOCOL = PREFIX + "-Selected-Protocol"; @@ -82,8 +82,8 @@ public final class OkHeaders { /** * Returns an immutable map containing each field to its list of values. * - * @param valueForNullKey the request line for requests, or the status line - * for responses. If non-null, this value is mapped to the null key. + * @param valueForNullKey the request line for requests, or the status line for responses. If + * non-null, this value is mapped to the null key. */ public static Map> toMultimap(Headers headers, String valueForNullKey) { Map> result = new TreeMap<>(FIELD_NAME_COMPARATOR); @@ -116,8 +116,8 @@ public final class OkHeaders { } /** - * Send all cookies in one big header, as recommended by - * RFC 6265. + * Send all cookies in one big header, as recommended by RFC 6265. */ private static String buildCookieHeader(List cookies) { if (cookies.size() == 1) return cookies.get(0); @@ -130,8 +130,8 @@ public final class OkHeaders { } /** - * Returns true if none of the Vary headers have changed between {@code - * cachedRequest} and {@code newRequest}. + * Returns true if none of the Vary headers have changed between {@code cachedRequest} and {@code + * newRequest}. */ public static boolean varyMatches( Response cachedResponse, Headers cachedRequest, Request newRequest) { @@ -142,16 +142,14 @@ public final class OkHeaders { } /** - * Returns true if a Vary header contains an asterisk. Such responses cannot - * be cached. + * Returns true if a Vary header contains an asterisk. Such responses cannot be cached. */ public static boolean hasVaryAll(Response response) { return hasVaryAll(response.headers()); } /** - * Returns true if a Vary header contains an asterisk. Such responses cannot - * be cached. + * Returns true if a Vary header contains an asterisk. Such responses cannot be cached. */ public static boolean hasVaryAll(Headers responseHeaders) { return varyFields(responseHeaders).contains("*"); @@ -162,8 +160,7 @@ public final class OkHeaders { } /** - * Returns the names of the request headers that need to be checked for - * equality when caching. + * Returns the names of the request headers that need to be checked for equality when caching. */ public static Set varyFields(Headers responseHeaders) { Set result = Collections.emptySet(); @@ -182,8 +179,8 @@ public final class OkHeaders { } /** - * Returns the subset of the headers in {@code response}'s request that - * impact the content of response's body. + * Returns the subset of the headers in {@code response}'s request that impact the content of + * response's body. */ public static Headers varyHeaders(Response response) { // Use the request headers sent over the network, since that's what the @@ -195,8 +192,8 @@ public final class OkHeaders { } /** - * Returns the subset of the headers in {@code requestHeaders} that - * impact the content of response's body. + * Returns the subset of the headers in {@code requestHeaders} that impact the content of + * response's body. */ public static Headers varyHeaders(Headers requestHeaders, Headers responseHeaders) { Set varyFields = varyFields(responseHeaders); @@ -213,8 +210,8 @@ public final class OkHeaders { } /** - * Returns true if {@code fieldName} is an end-to-end HTTP header, as - * defined by RFC 2616, 13.5.1. + * Returns true if {@code fieldName} is an end-to-end HTTP header, as defined by RFC 2616, + * 13.5.1. */ static boolean isEndToEnd(String fieldName) { return !"Connection".equalsIgnoreCase(fieldName) @@ -228,8 +225,7 @@ public final class OkHeaders { } /** - * Parse RFC 2617 challenges. This API is only interested in the scheme - * name and realm. + * Parse RFC 2617 challenges. This API is only interested in the scheme name and realm. */ public static List parseChallenges(Headers responseHeaders, String challengeHeader) { // auth-scheme = token diff --git a/okhttp/src/main/java/okhttp3/internal/http/RequestLine.java b/okhttp/src/main/java/okhttp3/internal/http/RequestLine.java index 756524a59..ff2bc5598 100644 --- a/okhttp/src/main/java/okhttp3/internal/http/RequestLine.java +++ b/okhttp/src/main/java/okhttp3/internal/http/RequestLine.java @@ -1,18 +1,18 @@ package okhttp3.internal.http; -import okhttp3.HttpUrl; -import okhttp3.Request; import java.net.HttpURLConnection; import java.net.Proxy; +import okhttp3.HttpUrl; +import okhttp3.Request; public final class RequestLine { private RequestLine() { } /** - * Returns the request status line, like "GET / HTTP/1.1". This is exposed - * to the application by {@link HttpURLConnection#getHeaderFields}, so it - * needs to be set even if the transport is SPDY. + * Returns the request status line, like "GET / HTTP/1.1". This is exposed to the application by + * {@link HttpURLConnection#getHeaderFields}, so it needs to be set even if the transport is + * SPDY. */ static String get(Request request, Proxy.Type proxyType) { StringBuilder result = new StringBuilder(); @@ -30,17 +30,16 @@ public final class RequestLine { } /** - * Returns true if the request line should contain the full URL with host - * and port (like "GET http://android.com/foo HTTP/1.1") or only the path - * (like "GET /foo HTTP/1.1"). + * Returns true if the request line should contain the full URL with host and port (like "GET + * http://android.com/foo HTTP/1.1") or only the path (like "GET /foo HTTP/1.1"). */ private static boolean includeAuthorityInRequestLine(Request request, Proxy.Type proxyType) { return !request.isHttps() && proxyType == Proxy.Type.HTTP; } /** - * Returns the path to request, like the '/' in 'GET / HTTP/1.1'. Never empty, - * even if the request URL is. Includes the query component if it exists. + * Returns the path to request, like the '/' in 'GET / HTTP/1.1'. Never empty, even if the request + * URL is. Includes the query component if it exists. */ public static String requestPath(HttpUrl url) { String path = url.encodedPath(); diff --git a/okhttp/src/main/java/okhttp3/internal/http/RetryableSink.java b/okhttp/src/main/java/okhttp3/internal/http/RetryableSink.java index 08ef9fc27..8fb13a8a7 100644 --- a/okhttp/src/main/java/okhttp3/internal/http/RetryableSink.java +++ b/okhttp/src/main/java/okhttp3/internal/http/RetryableSink.java @@ -25,9 +25,8 @@ import okio.Timeout; import static okhttp3.internal.Util.checkOffsetAndCount; /** - * An HTTP request body that's completely buffered in memory. This allows - * the post body to be transparently re-sent if the HTTP request must be - * sent multiple times. + * An HTTP request body that's completely buffered in memory. This allows the post body to be + * transparently re-sent if the HTTP request must be sent multiple times. */ public final class RetryableSink implements Sink { private boolean closed; diff --git a/okhttp/src/main/java/okhttp3/internal/http/RouteException.java b/okhttp/src/main/java/okhttp3/internal/http/RouteException.java index a6aeeeedd..030b346a5 100644 --- a/okhttp/src/main/java/okhttp3/internal/http/RouteException.java +++ b/okhttp/src/main/java/okhttp3/internal/http/RouteException.java @@ -25,6 +25,7 @@ import java.lang.reflect.Method; */ public final class RouteException extends Exception { private static final Method addSuppressedExceptionMethod; + static { Method m; try { @@ -34,6 +35,7 @@ public final class RouteException extends Exception { } addSuppressedExceptionMethod = m; } + private IOException lastException; public RouteException(IOException cause) { diff --git a/okhttp/src/main/java/okhttp3/internal/http/RouteSelector.java b/okhttp/src/main/java/okhttp3/internal/http/RouteSelector.java index f6f06caa0..3b5725cbe 100644 --- a/okhttp/src/main/java/okhttp3/internal/http/RouteSelector.java +++ b/okhttp/src/main/java/okhttp3/internal/http/RouteSelector.java @@ -15,10 +15,6 @@ */ package okhttp3.internal.http; -import okhttp3.Address; -import okhttp3.HttpUrl; -import okhttp3.Route; -import okhttp3.internal.RouteDatabase; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -29,11 +25,14 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; +import okhttp3.Address; +import okhttp3.HttpUrl; +import okhttp3.Route; +import okhttp3.internal.RouteDatabase; /** - * Selects routes to connect to an origin server. Each connection requires a - * choice of proxy server, IP address, and TLS mode. Connections may also be - * recycled. + * Selects routes to connect to an origin server. Each connection requires a choice of proxy server, + * IP address, and TLS mode. Connections may also be recycled. */ public final class RouteSelector { private final Address address; @@ -62,8 +61,7 @@ public final class RouteSelector { } /** - * Returns true if there's another route to attempt. Every address has at - * least one route. + * Returns true if there's another route to attempt. Every address has at least one route. */ public boolean hasNext() { return hasNextInetSocketAddress() @@ -95,8 +93,8 @@ public final class RouteSelector { } /** - * Clients should invoke this method when they encounter a connectivity - * failure on a connection returned by this route selector. + * Clients should invoke this method when they encounter a connectivity failure on a connection + * returned by this route selector. */ public void connectFailed(Route failedRoute, IOException failure) { if (failedRoute.proxy().type() != Proxy.Type.DIRECT && address.proxySelector() != null) { diff --git a/okhttp/src/main/java/okhttp3/internal/http/StatusLine.java b/okhttp/src/main/java/okhttp3/internal/http/StatusLine.java index de27241a9..ccc642b4b 100644 --- a/okhttp/src/main/java/okhttp3/internal/http/StatusLine.java +++ b/okhttp/src/main/java/okhttp3/internal/http/StatusLine.java @@ -1,9 +1,9 @@ package okhttp3.internal.http; -import okhttp3.Protocol; -import okhttp3.Response; import java.io.IOException; import java.net.ProtocolException; +import okhttp3.Protocol; +import okhttp3.Response; /** An HTTP response status line like "HTTP/1.1 200 OK". */ public final class StatusLine { diff --git a/okhttp/src/main/java/okhttp3/internal/http/StreamAllocation.java b/okhttp/src/main/java/okhttp3/internal/http/StreamAllocation.java index 6f3146f42..0b0469f64 100644 --- a/okhttp/src/main/java/okhttp3/internal/http/StreamAllocation.java +++ b/okhttp/src/main/java/okhttp3/internal/http/StreamAllocation.java @@ -39,38 +39,38 @@ import static java.util.concurrent.TimeUnit.MILLISECONDS; * This class coordinates the relationship between three entities: * *

    - *
  • Connections: physical socket connections to remote servers. These are - * potentially slow to establish so it is necessary to be able to cancel a connection - * currently being connected. - *
  • Streams: logical HTTP request/response pairs that are layered on - * connections. Each connection has its own allocation limit, which defines how many - * concurrent streams that connection can carry. HTTP/1.x connections can carry 1 stream - * at a time, SPDY and HTTP/2 typically carry multiple. - *
  • Calls: a logical sequence of streams, typically an initial request and - * its follow up requests. We prefer to keep all streams of a single call on the same - * connection for better behavior and locality. + *
  • Connections: physical socket connections to remote servers. These are + * potentially slow to establish so it is necessary to be able to cancel a connection + * currently being connected. + *
  • Streams: logical HTTP request/response pairs that are layered on + * connections. Each connection has its own allocation limit, which defines how many + * concurrent streams that connection can carry. HTTP/1.x connections can carry 1 stream + * at a time, SPDY and HTTP/2 typically carry multiple. + *
  • Calls: a logical sequence of streams, typically an initial request and + * its follow up requests. We prefer to keep all streams of a single call on the same + * connection for better behavior and locality. *
* - *

Instances of this class act on behalf of the call, using one or more streams over one or - * more connections. This class has APIs to release each of the above resources: + *

Instances of this class act on behalf of the call, using one or more streams over one or more + * connections. This class has APIs to release each of the above resources: * *

    - *
  • {@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 - * inconsistent. - *
  • {@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 {@link - * #streamFinished streamFinished()} before creating a subsequent stream with {@link - * #newStream newStream()}. - *
  • {@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 - * call is complete but its response body has yet to be fully consumed. + *
  • {@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 + * inconsistent. + *
  • {@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 + * {@link #streamFinished streamFinished()} before creating a subsequent stream with {@link + * #newStream newStream()}. + *
  • {@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 + * call is complete but its response body has yet to be fully consumed. *
* - *

This class supports {@linkplain #cancel asynchronous canceling}. This is intended to have - * the smallest blast radius possible. If an HTTP/2 stream is active, canceling will cancel that - * stream but not the other streams sharing its connection. But if the TLS handshake is still in - * progress then canceling may break the entire connection. + *

This class supports {@linkplain #cancel asynchronous canceling}. This is intended to have the + * smallest blast radius possible. If an HTTP/2 stream is active, canceling will cancel that stream + * but not the other streams sharing its connection. But if the TLS handshake is still in progress + * then canceling may break the entire connection. */ public final class StreamAllocation { public final Address address; diff --git a/okhttp/src/main/java/okhttp3/internal/io/FileSystem.java b/okhttp/src/main/java/okhttp3/internal/io/FileSystem.java index f4f120572..6a786954b 100644 --- a/okhttp/src/main/java/okhttp3/internal/io/FileSystem.java +++ b/okhttp/src/main/java/okhttp3/internal/io/FileSystem.java @@ -28,9 +28,9 @@ import okio.Source; * implementations may be used to inject faults (for testing) or to transform stored data (to add * encryption, for example). * - *

All operations on a file system are racy. For example, guarding a call to {@link #source} - * with {@link #exists} does not guarantee that {@link FileNotFoundException} will not be thrown. - * The file may be moved between the two calls! + *

All operations on a file system are racy. For example, guarding a call to {@link #source} with + * {@link #exists} does not guarantee that {@link FileNotFoundException} will not be thrown. The + * file may be moved between the two calls! * *

This interface is less ambitious than {@link java.nio.file.FileSystem} introduced in Java 7. * It lacks important features like file watching, metadata, permissions, and disk space diff --git a/okhttp/src/main/java/okhttp3/internal/io/RealConnection.java b/okhttp/src/main/java/okhttp3/internal/io/RealConnection.java index c6d7ecc54..3077a7717 100644 --- a/okhttp/src/main/java/okhttp3/internal/io/RealConnection.java +++ b/okhttp/src/main/java/okhttp3/internal/io/RealConnection.java @@ -227,9 +227,8 @@ public final class RealConnection implements Connection { } /** - * To make an HTTPS connection over an HTTP proxy, send an unencrypted - * CONNECT request to create the proxy connection. This may need to be - * retried if the proxy requires authorization. + * To make an HTTPS connection over an HTTP proxy, send an unencrypted CONNECT request to create + * the proxy connection. This may need to be retried if the proxy requires authorization. */ private void createTunnel(int readTimeout, int writeTimeout) throws IOException { // Make an SSL Tunnel on the first message pair of each SSL + proxy connection. @@ -277,11 +276,10 @@ public final class RealConnection implements Connection { } /** - * Returns a request that creates a TLS tunnel via an HTTP proxy, or null if - * no tunnel is necessary. Everything in the tunnel request is sent - * unencrypted to the proxy server, so tunnels include only the minimum set of - * headers. This avoids sending potentially sensitive data like HTTP cookies - * to the proxy unencrypted. + * Returns a request that creates a TLS tunnel via an HTTP proxy, or null if no tunnel is + * necessary. Everything in the tunnel request is sent unencrypted to the proxy server, so tunnels + * include only the minimum set of headers. This avoids sending potentially sensitive data like + * HTTP cookies to the proxy unencrypted. */ private Request createTunnelRequest() throws IOException { return new Request.Builder() @@ -354,8 +352,8 @@ public final class RealConnection implements Connection { } /** - * Returns true if this is a SPDY connection. Such connections can be used - * in multiple HTTP requests simultaneously. + * Returns true if this is a SPDY connection. Such connections can be used in multiple HTTP + * requests simultaneously. */ public boolean isMultiplexed() { return framedConnection != null; diff --git a/okhttp/src/main/java/okhttp3/internal/tls/DistinguishedNameParser.java b/okhttp/src/main/java/okhttp3/internal/tls/DistinguishedNameParser.java index 7a6814b18..ceecd9c31 100644 --- a/okhttp/src/main/java/okhttp3/internal/tls/DistinguishedNameParser.java +++ b/okhttp/src/main/java/okhttp3/internal/tls/DistinguishedNameParser.java @@ -20,8 +20,8 @@ package okhttp3.internal.tls; import javax.security.auth.x500.X500Principal; /** - * A distinguished name (DN) parser. This parser only supports extracting a - * string value from a DN. It doesn't support values in the hex-string style. + * A distinguished name (DN) parser. This parser only supports extracting a string value from a DN. + * It doesn't support values in the hex-string style. */ final class DistinguishedNameParser { private final String dn; @@ -341,8 +341,8 @@ final class DistinguishedNameParser { } /** - * Parses the DN and returns the most significant attribute value - * for an attribute type, or null if none found. + * Parses the DN and returns the most significant attribute value for an attribute type, or null + * if none found. * * @param attributeType attribute type to look for (e.g. "ca") */ diff --git a/okhttp/src/main/java/okhttp3/internal/tls/OkHostnameVerifier.java b/okhttp/src/main/java/okhttp3/internal/tls/OkHostnameVerifier.java index aee522b05..524623ba3 100644 --- a/okhttp/src/main/java/okhttp3/internal/tls/OkHostnameVerifier.java +++ b/okhttp/src/main/java/okhttp3/internal/tls/OkHostnameVerifier.java @@ -32,21 +32,19 @@ import javax.net.ssl.SSLSession; import javax.security.auth.x500.X500Principal; /** - * A HostnameVerifier consistent with RFC 2818. + * A HostnameVerifier consistent with RFC 2818. */ public final class OkHostnameVerifier implements HostnameVerifier { public static final OkHostnameVerifier INSTANCE = new OkHostnameVerifier(); /** - * Quick and dirty pattern to differentiate IP addresses from hostnames. This - * is an approximation of Android's private InetAddress#isNumeric API. + * Quick and dirty pattern to differentiate IP addresses from hostnames. This is an approximation + * of Android's private InetAddress#isNumeric API. * - *

This matches IPv6 addresses as a hex string containing at least one - * colon, and possibly including dots after the first colon. It matches IPv4 - * addresses as strings containing only decimal digits and dots. This pattern - * matches strings like "a:.23" and "54" that are neither IP addresses nor - * hostnames; they will be verified as IP addresses (which is a more strict + *

This matches IPv6 addresses as a hex string containing at least one colon, and possibly + * including dots after the first colon. It matches IPv4 addresses as strings containing only + * decimal digits and dots. This pattern matches strings like "a:.23" and "54" that are neither IP + * addresses nor hostnames; they will be verified as IP addresses (which is a more strict * verification). */ private static final Pattern VERIFY_AS_IP_ADDRESS = Pattern.compile( @@ -159,8 +157,8 @@ public final class OkHostnameVerifier implements HostnameVerifier { * Returns {@code true} iff {@code hostName} matches the domain name {@code pattern}. * * @param hostName lower-case host name. - * @param pattern domain name pattern from certificate. May be a wildcard pattern such as - * {@code *.android.com}. + * @param pattern domain name pattern from certificate. May be a wildcard pattern such as {@code + * *.android.com}. */ private boolean verifyHostName(String hostName, String pattern) { // Basic sanity checks diff --git a/pom.xml b/pom.xml index c58d828c3..6da4ada93 100644 --- a/pom.xml +++ b/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 @@ -237,7 +239,9 @@ 1.7 - ${settings.localRepository}/org/mortbay/jetty/alpn/alpn-boot/${alpn.jdk7.version}/alpn-boot-${alpn.jdk7.version}.jar + + ${settings.localRepository}/org/mortbay/jetty/alpn/alpn-boot/${alpn.jdk7.version}/alpn-boot-${alpn.jdk7.version}.jar + @@ -266,7 +270,9 @@ 1.8 - ${settings.localRepository}/org/mortbay/jetty/alpn/alpn-boot/${alpn.jdk8.version}/alpn-boot-${alpn.jdk8.version}.jar + + ${settings.localRepository}/org/mortbay/jetty/alpn/alpn-boot/${alpn.jdk8.version}/alpn-boot-${alpn.jdk8.version}.jar +