1
0
mirror of https://github.com/square/okhttp.git synced 2026-01-18 20:40:58 +03:00

Merge pull request #788 from square/jwilson_0430_hide_more_apis

Hide more APIs with Internal.access.
This commit is contained in:
Jesse Wilson
2014-04-30 22:00:48 -04:00
12 changed files with 158 additions and 67 deletions

View File

@@ -22,6 +22,7 @@ import com.squareup.okhttp.ConnectionPool;
import com.squareup.okhttp.Credentials;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Protocol;
import com.squareup.okhttp.internal.Internal;
import com.squareup.okhttp.internal.RecordingAuthenticator;
import com.squareup.okhttp.internal.RecordingHostnameVerifier;
import com.squareup.okhttp.internal.RecordingOkAuthenticator;
@@ -2314,7 +2315,7 @@ public final class URLConnectionTest {
/** Don't explode if the cache returns a null body. http://b/3373699 */
@Test public void responseCacheReturnsNullOutputStream() throws Exception {
final AtomicBoolean aborted = new AtomicBoolean();
client.setResponseCache(new AbstractResponseCache() {
Internal.instance.setResponseCache(client, new AbstractResponseCache() {
@Override public CacheRequest put(URI uri, URLConnection connection) throws IOException {
return new CacheRequest() {
@Override public void abort() {

View File

@@ -18,6 +18,7 @@ package com.squareup.okhttp.internal.http;
import com.squareup.okhttp.AbstractResponseCache;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.internal.Internal;
import java.io.IOException;
import java.net.CacheResponse;
import java.net.HttpURLConnection;
@@ -122,7 +123,7 @@ public final class URLEncodingTest {
final AtomicReference<URI> uriReference = new AtomicReference<URI>();
OkHttpClient client = new OkHttpClient();
client.setResponseCache(new AbstractResponseCache() {
Internal.instance.setResponseCache(client, new AbstractResponseCache() {
@Override public CacheResponse get(URI uri, String requestMethod,
Map<String, List<String>> requestHeaders) throws IOException {
uriReference.set(uri);

View File

@@ -17,6 +17,7 @@ package com.squareup.okhttp.internal.huc;
import com.squareup.okhttp.AbstractResponseCache;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.internal.Internal;
import com.squareup.okhttp.internal.SslContextBuilder;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.MockWebServer;
@@ -93,7 +94,7 @@ public class CacheAdapterTest {
return null;
}
};
client.setResponseCache(responseCache);
Internal.instance.setResponseCache(client, responseCache);
connection = client.open(serverUrl);
connection.setRequestProperty("key1", "value1");
@@ -116,7 +117,7 @@ public class CacheAdapterTest {
return null;
}
};
client.setResponseCache(responseCache);
Internal.instance.setResponseCache(client, responseCache);
client.setSslSocketFactory(sslContext.getSocketFactory());
client.setHostnameVerifier(NULL_HOSTNAME_VERIFIER);
@@ -158,7 +159,7 @@ public class CacheAdapterTest {
return null;
}
};
client.setResponseCache(responseCache);
Internal.instance.setResponseCache(client, responseCache);
connection = client.open(serverUrl);
connection.setRequestProperty("key", "value");
@@ -197,7 +198,7 @@ public class CacheAdapterTest {
return null;
}
};
client.setResponseCache(responseCache);
Internal.instance.setResponseCache(client, responseCache);
connection = client.open(serverUrl);
@@ -229,7 +230,7 @@ public class CacheAdapterTest {
return null;
}
};
client.setResponseCache(responseCache);
Internal.instance.setResponseCache(client, responseCache);
client.setSslSocketFactory(sslContext.getSocketFactory());
client.setHostnameVerifier(NULL_HOSTNAME_VERIFIER);

View File

@@ -16,8 +16,10 @@
package com.squareup.okhttp.internal.huc;
import com.squareup.okhttp.AbstractResponseCache;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.ResponseSource;
import com.squareup.okhttp.internal.Internal;
import com.squareup.okhttp.internal.SslContextBuilder;
import com.squareup.okhttp.internal.http.OkHeaders;
import com.squareup.okhttp.mockwebserver.MockResponse;
@@ -77,7 +79,6 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@@ -124,16 +125,15 @@ public final class ResponseCacheTest {
@Test public void responseCacheAccessWithOkHttpMember() throws IOException {
ResponseCache.setDefault(null);
client.setResponseCache(cache);
assertSame(cache, client.getResponseCache());
assertTrue(client.internalCache() instanceof CacheAdapter);
Internal.instance.setResponseCache(client, cache);
assertTrue(Internal.instance.internalCache(client) instanceof CacheAdapter);
}
@Test public void responseCacheAccessWithGlobalDefault() throws IOException {
ResponseCache.setDefault(cache);
client.setResponseCache(null);
assertNull(client.internalCache());
assertNull(client.getResponseCache());
Internal.instance.setResponseCache(client, null);
assertNull(Internal.instance.internalCache(client));
assertNull(client.getCache());
}
@Test public void responseCachingAndInputStreamSkipWithFixedLength() throws IOException {
@@ -215,7 +215,8 @@ public final class ResponseCacheTest {
server.enqueue(new MockResponse().setBody("ABC"));
server.enqueue(new MockResponse().setBody("DEF"));
client.setResponseCache(new InsecureResponseCache(new InMemoryResponseCache()));
Internal.instance.setResponseCache(client,
new InsecureResponseCache(new InMemoryResponseCache()));
HttpsURLConnection connection1 = (HttpsURLConnection) openConnection(server.getUrl("/"));
connection1.setSSLSocketFactory(sslContext.getSocketFactory());
@@ -331,18 +332,12 @@ public final class ResponseCacheTest {
final AtomicReference<Map<String, List<String>>> requestHeadersRef =
new AtomicReference<Map<String, List<String>>>();
client.setResponseCache(new ResponseCache() {
@Override
public CacheResponse get(URI uri, String requestMethod,
Internal.instance.setResponseCache(client, new AbstractResponseCache() {
@Override public CacheResponse get(URI uri, String requestMethod,
Map<String, List<String>> requestHeaders) throws IOException {
requestHeadersRef.set(requestHeaders);
return null;
}
@Override
public CacheRequest put(URI uri, URLConnection conn) throws IOException {
return null;
}
});
URL url = server.getUrl("/");

View File

@@ -85,13 +85,13 @@ public final class Connection implements Closeable {
this.route = route;
}
public Object getOwner() {
Object getOwner() {
synchronized (pool) {
return owner;
}
}
public void setOwner(Object owner) {
void setOwner(Object owner) {
if (isSpdy()) return; // SPDY connections are shared.
synchronized (pool) {
if (this.owner != null) throw new IllegalStateException("Connection already has an owner!");
@@ -105,7 +105,7 @@ public final class Connection implements Closeable {
* false if the connection cannot be pooled or reused, such as if it was
* closed with {@link #closeIfOwnedBy}.
*/
public boolean clearOwner() {
boolean clearOwner() {
synchronized (pool) {
if (owner == null) {
// No owner? Don't reuse this connection.
@@ -121,7 +121,7 @@ public final class Connection implements Closeable {
* Closes this connection if it is currently owned by {@code owner}. This also
* strips the ownership of the connection so it cannot be pooled or reused.
*/
public void closeIfOwnedBy(Object owner) throws IOException {
void closeIfOwnedBy(Object owner) throws IOException {
if (isSpdy()) throw new IllegalStateException();
synchronized (pool) {
if (this.owner != owner) {
@@ -135,7 +135,7 @@ public final class Connection implements Closeable {
socket.close();
}
public void connect(int connectTimeout, int readTimeout, int writeTimeout, Request tunnelRequest)
void connect(int connectTimeout, int readTimeout, int writeTimeout, Request tunnelRequest)
throws IOException {
if (connected) throw new IllegalStateException("already connected");
@@ -207,7 +207,7 @@ public final class Connection implements Closeable {
}
/** Returns true if {@link #connect} has been attempted on this connection. */
public boolean isConnected() {
boolean isConnected() {
return connected;
}
@@ -229,7 +229,7 @@ public final class Connection implements Closeable {
}
/** Returns true if this connection is alive. */
public boolean isAlive() {
boolean isAlive() {
return !socket.isClosed() && !socket.isInputShutdown() && !socket.isOutputShutdown();
}
@@ -238,18 +238,18 @@ public final class Connection implements Closeable {
* connection. This is more expensive and more accurate than {@link
* #isAlive()}; callers should check {@link #isAlive()} first.
*/
public boolean isReadable() {
boolean isReadable() {
if (httpConnection != null) return httpConnection.isReadable();
return true; // SPDY connections, and connections before connect() are both optimistic.
}
public void resetIdleStartTime() {
void resetIdleStartTime() {
if (spdyConnection != null) throw new IllegalStateException("spdyConnection != null");
this.idleStartTimeNs = System.nanoTime();
}
/** Returns true if this connection is idle. */
public boolean isIdle() {
boolean isIdle() {
return spdyConnection == null || spdyConnection.isIdle();
}
@@ -257,7 +257,7 @@ public final class Connection implements Closeable {
* Returns true if this connection has been idle for longer than
* {@code keepAliveDurationNs}.
*/
public boolean isExpired(long keepAliveDurationNs) {
boolean isExpired(long keepAliveDurationNs) {
return getIdleStartTimeNs() < System.nanoTime() - keepAliveDurationNs;
}
@@ -265,7 +265,7 @@ public final class Connection implements Closeable {
* Returns the time in ns when this connection became idle. Undefined if
* this connection is not idle.
*/
public long getIdleStartTimeNs() {
long getIdleStartTimeNs() {
return spdyConnection == null ? idleStartTimeNs : spdyConnection.getIdleStartTimeNs();
}
@@ -284,7 +284,7 @@ public final class Connection implements Closeable {
* Returns true if this is a SPDY connection. Such connections can be used
* in multiple HTTP requests simultaneously.
*/
public boolean isSpdy() {
boolean isSpdy() {
return spdyConnection != null;
}
@@ -300,12 +300,12 @@ public final class Connection implements Closeable {
* Sets the protocol negotiated by this connection. Typically this is used
* when an HTTP/1.1 request is sent and an HTTP/1.0 response is received.
*/
public void setProtocol(Protocol protocol) {
void setProtocol(Protocol protocol) {
if (protocol == null) throw new IllegalArgumentException("protocol == null");
this.protocol = protocol;
}
public void setTimeouts(int readTimeoutMillis, int writeTimeoutMillis) throws IOException {
void setTimeouts(int readTimeoutMillis, int writeTimeoutMillis) throws IOException {
if (!connected) throw new IllegalStateException("setTimeouts - not connected");
// Don't set timeouts on shared SPDY connections.
@@ -315,7 +315,7 @@ public final class Connection implements Closeable {
}
}
public void incrementRecycleCount() {
void incrementRecycleCount() {
recycleCount++;
}
@@ -323,7 +323,7 @@ public final class Connection implements Closeable {
* Returns the number of times this connection has been returned to the
* connection pool.
*/
public int recycleCount() {
int recycleCount() {
return recycleCount;
}

View File

@@ -139,7 +139,7 @@ public final class Headers {
private final List<String> namesAndValues = new ArrayList<String>(20);
/** Add an header line containing a field name, a literal colon, and a value. */
public Builder addLine(String line) {
Builder addLine(String line) {
int index = line.indexOf(":", 1);
if (index != -1) {
return addLenient(line.substring(0, index), line.substring(index + 1));

View File

@@ -61,6 +61,64 @@ public final class OkHttpClient implements URLStreamHandlerFactory, Cloneable {
Connection connection, HttpEngine httpEngine) throws IOException {
return connection.newTransport(httpEngine);
}
@Override public boolean clearOwner(Connection connection) {
return connection.clearOwner();
}
@Override public void closeIfOwnedBy(Connection connection, Object owner) throws IOException {
connection.closeIfOwnedBy(owner);
}
@Override public int recycleCount(Connection connection) {
return connection.recycleCount();
}
@Override public Object getOwner(Connection connection) {
return connection.getOwner();
}
@Override public void setProtocol(Connection connection, Protocol protocol) {
connection.setProtocol(protocol);
}
@Override public void setOwner(Connection connection, HttpEngine httpEngine) {
connection.setOwner(httpEngine);
}
@Override public void connect(Connection connection, int connectTimeout, int readTimeout,
int writeTimeout, Request request) throws IOException {
connection.connect(connectTimeout, readTimeout, writeTimeout, request);
}
@Override public boolean isConnected(Connection connection) {
return connection.isConnected();
}
@Override public boolean isSpdy(Connection connection) {
return connection.isSpdy();
}
@Override public void setTimeouts(Connection connection, int readTimeout, int writeTimeout)
throws IOException {
connection.setTimeouts(readTimeout, writeTimeout);
}
@Override public boolean isReadable(Connection pooled) {
return pooled.isReadable();
}
@Override public void addLine(Headers.Builder builder, String line) {
builder.addLine(line);
}
@Override public void setResponseCache(OkHttpClient client, ResponseCache responseCache) {
client.setResponseCache(responseCache);
}
@Override public InternalCache internalCache(OkHttpClient client) {
return client.internalCache();
}
};
}
@@ -194,18 +252,14 @@ public final class OkHttpClient implements URLStreamHandlerFactory, Cloneable {
return cookieHandler;
}
/**
* Sets the response cache to be used to read and write cached responses.
*/
@Deprecated // internal only.
public OkHttpClient setResponseCache(ResponseCache responseCache) {
/** Sets the response cache to be used to read and write cached responses. */
OkHttpClient setResponseCache(ResponseCache responseCache) {
this.cacheAdapter = responseCache != null ? new CacheAdapter(responseCache) : null;
this.cache = null;
return this;
}
@Deprecated // internal only.
public ResponseCache getResponseCache() {
ResponseCache getResponseCache() {
return cacheAdapter != null ? cacheAdapter.getDelegate() : null;
}
@@ -219,8 +273,7 @@ public final class OkHttpClient implements URLStreamHandlerFactory, Cloneable {
return cache;
}
@Deprecated // internal only.
public InternalCache internalCache() {
InternalCache internalCache() {
return cache != null ? cache.internalCache : cacheAdapter;
}

View File

@@ -16,9 +16,14 @@
package com.squareup.okhttp.internal;
import com.squareup.okhttp.Connection;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Protocol;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.internal.http.HttpEngine;
import com.squareup.okhttp.internal.http.Transport;
import java.io.IOException;
import java.net.ResponseCache;
/**
* Escalate internal APIs in {@code com.squareup.okhttp} so they can be used
@@ -30,4 +35,34 @@ public abstract class Internal {
public abstract Transport newTransport(Connection connection, HttpEngine httpEngine)
throws IOException;
public abstract boolean clearOwner(Connection connection);
public abstract void closeIfOwnedBy(Connection connection, Object owner) throws IOException;
public abstract int recycleCount(Connection connection);
public abstract Object getOwner(Connection connection);
public abstract void setProtocol(Connection connection, Protocol protocol);
public abstract void setOwner(Connection connection, HttpEngine httpEngine);
public abstract void connect(Connection connection,
int connectTimeout, int readTimeout, int writeTimeout, Request request) throws IOException;
public abstract boolean isConnected(Connection connection);
public abstract boolean isSpdy(Connection connection);
public abstract void setTimeouts(Connection connection, int readTimeout, int writeTimeout)
throws IOException;
public abstract boolean isReadable(Connection pooled);
public abstract void addLine(Headers.Builder builder, String line);
public abstract void setResponseCache(OkHttpClient client, ResponseCache responseCache);
public abstract InternalCache internalCache(OkHttpClient client);
}

View File

@@ -20,6 +20,7 @@ import com.squareup.okhttp.Connection;
import com.squareup.okhttp.ConnectionPool;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.internal.Internal;
import com.squareup.okhttp.internal.Util;
import java.io.IOException;
import java.io.OutputStream;
@@ -132,7 +133,7 @@ public final class HttpConnection {
}
public void closeIfOwnedBy(Object owner) throws IOException {
connection.closeIfOwnedBy(owner);
Internal.instance.closeIfOwnedBy(connection, owner);
}
public void flush() throws IOException {
@@ -208,7 +209,7 @@ public final class HttpConnection {
public void readHeaders(Headers.Builder builder) throws IOException {
// parse the result headers until the first blank line
for (String line; (line = source.readUtf8LineStrict()).length() != 0; ) {
builder.addLine(line);
Internal.instance.addLine(builder, line);
}
}

View File

@@ -162,7 +162,7 @@ public final class HttpEngine {
this.requestBodyOut = requestBodyOut;
if (connection != null) {
connection.setOwner(this);
Internal.instance.setOwner(connection, this);
this.route = connection.getRoute();
} else {
this.route = null;
@@ -179,7 +179,7 @@ public final class HttpEngine {
if (transport != null) throw new IllegalStateException();
prepareRawRequestHeaders();
InternalCache responseCache = client.internalCache();
InternalCache responseCache = Internal.instance.internalCache(client);
Response cacheResponse = responseCache != null
? responseCache.get(request)
@@ -208,7 +208,9 @@ public final class HttpEngine {
}
// Blow up if we aren't the current owner of the connection.
if (connection.getOwner() != this && !connection.isSpdy()) throw new AssertionError();
if (Internal.instance.getOwner(connection) != this && !Internal.instance.isSpdy(connection)) {
throw new AssertionError();
}
transport = Internal.instance.newTransport(connection, this);
@@ -262,15 +264,15 @@ public final class HttpEngine {
}
connection = routeSelector.next(request.method());
connection.setOwner(this);
Internal.instance.setOwner(connection, this);
if (!connection.isConnected()) {
connection.connect(client.getConnectTimeout(), client.getReadTimeout(),
if (!Internal.instance.isConnected(connection)) {
Internal.instance.connect(connection, client.getConnectTimeout(), client.getReadTimeout(),
client.getWriteTimeout(), tunnelRequest(connection, request));
if (connection.isSpdy()) client.getConnectionPool().share(connection);
if (Internal.instance.isSpdy(connection)) client.getConnectionPool().share(connection);
client.getRoutesDatabase().connected(connection.getRoute());
}
connection.setTimeouts(client.getReadTimeout(), client.getWriteTimeout());
Internal.instance.setTimeouts(connection, client.getReadTimeout(), client.getWriteTimeout());
route = connection.getRoute();
}
@@ -385,7 +387,7 @@ public final class HttpEngine {
}
private void maybeCache() throws IOException {
InternalCache responseCache = client.internalCache();
InternalCache responseCache = Internal.instance.internalCache(client);
if (responseCache == null) return;
// Should we cache this response for this request?
@@ -464,7 +466,7 @@ public final class HttpEngine {
}
// Prevent this engine from disconnecting a connection it no longer owns.
if (connection != null && !connection.clearOwner()) {
if (connection != null && !Internal.instance.clearOwner(connection)) {
connection = null;
}
@@ -634,7 +636,7 @@ public final class HttpEngine {
.header(OkHeaders.RECEIVED_MILLIS, Long.toString(System.currentTimeMillis()))
.setResponseSource(responseSource)
.build();
connection.setProtocol(response.protocol());
Internal.instance.setProtocol(connection, response.protocol());
receiveHeaders(response.headers());
if (responseSource == ResponseSource.CONDITIONAL_CACHE) {
@@ -645,7 +647,7 @@ public final class HttpEngine {
// Update the cache after combining headers but before stripping the
// Content-Encoding header (as performed by initContentStream()).
InternalCache responseCache = client.internalCache();
InternalCache responseCache = Internal.instance.internalCache(client);
responseCache.trackConditionalCacheHit();
responseCache.update(validatingResponse, cacheableResponse());

View File

@@ -21,6 +21,7 @@ import com.squareup.okhttp.ConnectionPool;
import com.squareup.okhttp.Route;
import com.squareup.okhttp.RouteDatabase;
import com.squareup.okhttp.internal.Dns;
import com.squareup.okhttp.internal.Internal;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
@@ -106,7 +107,7 @@ public final class RouteSelector {
public Connection next(String method) throws IOException {
// Always prefer pooled connections over new connections.
for (Connection pooled; (pooled = pool.get(address)) != null; ) {
if (method.equals("GET") || pooled.isReadable()) return pooled;
if (method.equals("GET") || Internal.instance.isReadable(pooled)) return pooled;
pooled.close();
}
@@ -144,7 +145,7 @@ public final class RouteSelector {
*/
public void connectFailed(Connection connection, IOException failure) {
// If this is a recycled connection, don't count its failure against the route.
if (connection.recycleCount() > 0) return;
if (Internal.instance.recycleCount(connection) > 0) return;
Route failedRoute = connection.getRoute();
if (failedRoute.getProxy().type() != Proxy.Type.DIRECT && proxySelector != null) {

View File

@@ -25,6 +25,7 @@ import com.squareup.okhttp.Protocol;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.Route;
import com.squareup.okhttp.internal.Internal;
import com.squareup.okhttp.internal.Platform;
import com.squareup.okhttp.internal.Util;
import com.squareup.okhttp.internal.http.HttpDate;
@@ -303,7 +304,7 @@ public class HttpURLConnectionImpl extends HttpURLConnection {
// If we're currently not using caches, make sure the engine's client doesn't have one.
OkHttpClient engineClient = client;
if (engineClient.internalCache() != null && !getUseCaches()) {
if (Internal.instance.internalCache(engineClient) != null && !getUseCaches()) {
engineClient = client.clone().setCache(null);
}