You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cordova.apache.org by ia...@apache.org on 2013/04/29 15:39:54 UTC
[5/7] android commit: [CB-2431] Switch to OkHttp for FileTransfer
connections
[CB-2431] Switch to OkHttp for FileTransfer connections
Project: http://git-wip-us.apache.org/repos/asf/cordova-android/repo
Commit: http://git-wip-us.apache.org/repos/asf/cordova-android/commit/553a25ce
Tree: http://git-wip-us.apache.org/repos/asf/cordova-android/tree/553a25ce
Diff: http://git-wip-us.apache.org/repos/asf/cordova-android/diff/553a25ce
Branch: refs/heads/master
Commit: 553a25cea7363028c81d6a87491b582a8bb8e888
Parents: 5398227
Author: Ian Clelland <ic...@chromium.org>
Authored: Tue Mar 26 15:14:00 2013 -0400
Committer: Ian Clelland <ic...@chromium.org>
Committed: Mon Apr 29 09:31:23 2013 -0400
----------------------------------------------------------------------
framework/src/com/squareup/okhttp/Address.java | 111 ++
framework/src/com/squareup/okhttp/Connection.java | 321 ++++++
.../src/com/squareup/okhttp/ConnectionPool.java | 257 +++++
.../src/com/squareup/okhttp/OkHttpClient.java | 198 ++++
.../src/com/squareup/okhttp/OkResponseCache.java | 38 +
.../src/com/squareup/okhttp/ResponseSource.java | 37 +
.../src/com/squareup/okhttp/TunnelRequest.java | 75 ++
.../src/com/squareup/okhttp/internal/Base64.java | 164 +++
.../com/squareup/okhttp/internal/DiskLruCache.java | 826 +++++++++++++++
.../src/com/squareup/okhttp/internal/Dns.java | 33 +
.../squareup/okhttp/internal/NamedRunnable.java | 40 +
.../src/com/squareup/okhttp/internal/Platform.java | 343 ++++++
.../squareup/okhttp/internal/StrictLineReader.java | 231 ++++
.../src/com/squareup/okhttp/internal/Util.java | 325 ++++++
.../internal/http/AbstractHttpInputStream.java | 107 ++
.../internal/http/AbstractHttpOutputStream.java | 40 +
.../okhttp/internal/http/HeaderParser.java | 112 ++
.../okhttp/internal/http/HttpAuthenticator.java | 175 +++
.../squareup/okhttp/internal/http/HttpDate.java | 82 ++
.../squareup/okhttp/internal/http/HttpEngine.java | 666 ++++++++++++
.../okhttp/internal/http/HttpResponseCache.java | 608 +++++++++++
.../okhttp/internal/http/HttpTransport.java | 499 +++++++++
.../internal/http/HttpURLConnectionImpl.java | 502 +++++++++
.../internal/http/HttpsURLConnectionImpl.java | 458 ++++++++
.../squareup/okhttp/internal/http/RawHeaders.java | 429 ++++++++
.../okhttp/internal/http/RequestHeaders.java | 290 +++++
.../okhttp/internal/http/ResponseHeaders.java | 496 +++++++++
.../internal/http/RetryableOutputStream.java | 74 ++
.../okhttp/internal/http/RouteSelector.java | 236 ++++
.../okhttp/internal/http/SpdyTransport.java | 96 ++
.../squareup/okhttp/internal/http/Transport.java | 64 ++
.../http/UnknownLengthHttpInputStream.java | 63 ++
.../internal/spdy/IncomingStreamHandler.java | 36 +
.../com/squareup/okhttp/internal/spdy/Ping.java | 71 ++
.../squareup/okhttp/internal/spdy/Settings.java | 174 +++
.../okhttp/internal/spdy/SpdyConnection.java | 579 ++++++++++
.../squareup/okhttp/internal/spdy/SpdyReader.java | 318 ++++++
.../squareup/okhttp/internal/spdy/SpdyStream.java | 733 +++++++++++++
.../squareup/okhttp/internal/spdy/SpdyWriter.java | 176 +++
framework/src/org/apache/cordova/FileTransfer.java | 17 +-
40 files changed, 10094 insertions(+), 6 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/553a25ce/framework/src/com/squareup/okhttp/Address.java
----------------------------------------------------------------------
diff --git a/framework/src/com/squareup/okhttp/Address.java b/framework/src/com/squareup/okhttp/Address.java
new file mode 100644
index 0000000..cd41ac9
--- /dev/null
+++ b/framework/src/com/squareup/okhttp/Address.java
@@ -0,0 +1,111 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp;
+
+import java.net.Proxy;
+import java.net.UnknownHostException;
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.SSLSocketFactory;
+
+import static com.squareup.okhttp.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
+ * {@link 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 and hostname verifier.
+ *
+ * <p>HTTP requests that share the same {@code Address} may also share the same
+ * {@link Connection}.
+ */
+public final class Address {
+ final Proxy proxy;
+ final String uriHost;
+ final int uriPort;
+ final SSLSocketFactory sslSocketFactory;
+ final HostnameVerifier hostnameVerifier;
+
+ public Address(String uriHost, int uriPort, SSLSocketFactory sslSocketFactory,
+ HostnameVerifier hostnameVerifier, Proxy proxy) throws UnknownHostException {
+ if (uriHost == null) throw new NullPointerException("uriHost == null");
+ if (uriPort <= 0) throw new IllegalArgumentException("uriPort <= 0: " + uriPort);
+ this.proxy = proxy;
+ this.uriHost = uriHost;
+ this.uriPort = uriPort;
+ this.sslSocketFactory = sslSocketFactory;
+ this.hostnameVerifier = hostnameVerifier;
+ }
+
+ /** Returns the hostname of the origin server. */
+ public String getUriHost() {
+ return uriHost;
+ }
+
+ /**
+ * Returns the port of the origin server; typically 80 or 443. Unlike
+ * may {@code getPort()} accessors, this method never returns -1.
+ */
+ public int getUriPort() {
+ return uriPort;
+ }
+
+ /**
+ * Returns the SSL socket factory, or null if this is not an HTTPS
+ * address.
+ */
+ public SSLSocketFactory getSslSocketFactory() {
+ return sslSocketFactory;
+ }
+
+ /**
+ * Returns the hostname verifier, or null if this is not an HTTPS
+ * address.
+ */
+ public HostnameVerifier getHostnameVerifier() {
+ return hostnameVerifier;
+ }
+
+ /**
+ * Returns this address's explicitly-specified HTTP proxy, or null to
+ * delegate to the HTTP client's proxy selector.
+ */
+ public Proxy getProxy() {
+ return proxy;
+ }
+
+ @Override public boolean equals(Object other) {
+ if (other instanceof Address) {
+ Address that = (Address) other;
+ return equal(this.proxy, that.proxy)
+ && this.uriHost.equals(that.uriHost)
+ && this.uriPort == that.uriPort
+ && equal(this.sslSocketFactory, that.sslSocketFactory)
+ && equal(this.hostnameVerifier, that.hostnameVerifier);
+ }
+ return false;
+ }
+
+ @Override public int hashCode() {
+ int result = 17;
+ result = 31 * result + uriHost.hashCode();
+ result = 31 * result + uriPort;
+ result = 31 * result + (sslSocketFactory != null ? sslSocketFactory.hashCode() : 0);
+ result = 31 * result + (hostnameVerifier != null ? hostnameVerifier.hashCode() : 0);
+ result = 31 * result + (proxy != null ? proxy.hashCode() : 0);
+ return result;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/553a25ce/framework/src/com/squareup/okhttp/Connection.java
----------------------------------------------------------------------
diff --git a/framework/src/com/squareup/okhttp/Connection.java b/framework/src/com/squareup/okhttp/Connection.java
new file mode 100644
index 0000000..90424ff
--- /dev/null
+++ b/framework/src/com/squareup/okhttp/Connection.java
@@ -0,0 +1,321 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp;
+
+import com.squareup.okhttp.internal.Platform;
+import com.squareup.okhttp.internal.http.HttpAuthenticator;
+import com.squareup.okhttp.internal.http.HttpEngine;
+import com.squareup.okhttp.internal.http.HttpTransport;
+import com.squareup.okhttp.internal.http.RawHeaders;
+import com.squareup.okhttp.internal.http.SpdyTransport;
+import com.squareup.okhttp.internal.spdy.SpdyConnection;
+import java.io.BufferedInputStream;
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.net.Proxy;
+import java.net.Socket;
+import java.net.URL;
+import java.util.Arrays;
+import javax.net.ssl.SSLSocket;
+
+import static java.net.HttpURLConnection.HTTP_OK;
+import static java.net.HttpURLConnection.HTTP_PROXY_AUTH;
+
+/**
+ * Holds the sockets and streams of an HTTP, HTTPS, or HTTPS+SPDY connection,
+ * which may be used for multiple HTTP request/response exchanges. Connections
+ * may be direct to the origin server or via a proxy.
+ *
+ * <p>Typically instances of this class are created, connected and exercised
+ * automatically by the HTTP client. Applications may use this class to monitor
+ * HTTP connections as members of a {@link ConnectionPool connection pool}.
+ *
+ * <p>Do not confuse this class with the misnamed {@code HttpURLConnection},
+ * which isn't so much a connection as a single request/response exchange.
+ *
+ * <h3>Modern TLS</h3>
+ * There are tradeoffs when selecting which options to include when negotiating
+ * a secure connection to a remote host. Newer TLS options are quite useful:
+ * <ul>
+ * <li>Server Name Indication (SNI) enables one IP address to negotiate secure
+ * connections for multiple domain names.
+ * <li>Next Protocol Negotiation (NPN) enables the HTTPS port (443) to be used
+ * for both HTTP and SPDY transports.
+ * </ul>
+ * 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.
+ */
+public final class Connection implements Closeable {
+ private static final byte[] NPN_PROTOCOLS = new byte[] {
+ 6, 's', 'p', 'd', 'y', '/', '3',
+ 8, 'h', 't', 't', 'p', '/', '1', '.', '1'
+ };
+ private static final byte[] SPDY3 = new byte[] {
+ 's', 'p', 'd', 'y', '/', '3'
+ };
+ private static final byte[] HTTP_11 = new byte[] {
+ 'h', 't', 't', 'p', '/', '1', '.', '1'
+ };
+
+ private final Address address;
+ private final Proxy proxy;
+ private final InetSocketAddress inetSocketAddress;
+ private final boolean modernTls;
+
+ private Socket socket;
+ private InputStream in;
+ private OutputStream out;
+ private boolean connected = false;
+ private SpdyConnection spdyConnection;
+ private int httpMinorVersion = 1; // Assume HTTP/1.1
+ private long idleStartTimeNs;
+
+ public Connection(Address address, Proxy proxy, InetSocketAddress inetSocketAddress,
+ boolean modernTls) {
+ if (address == null) throw new NullPointerException("address == null");
+ if (proxy == null) throw new NullPointerException("proxy == null");
+ if (inetSocketAddress == null) throw new NullPointerException("inetSocketAddress == null");
+ this.address = address;
+ this.proxy = proxy;
+ this.inetSocketAddress = inetSocketAddress;
+ this.modernTls = modernTls;
+ }
+
+ public void connect(int connectTimeout, int readTimeout, TunnelRequest tunnelRequest)
+ throws IOException {
+ if (connected) {
+ throw new IllegalStateException("already connected");
+ }
+ connected = true;
+ socket = (proxy.type() != Proxy.Type.HTTP) ? new Socket(proxy) : new Socket();
+ socket.connect(inetSocketAddress, connectTimeout);
+ socket.setSoTimeout(readTimeout);
+ in = socket.getInputStream();
+ out = socket.getOutputStream();
+
+ if (address.sslSocketFactory != null) {
+ upgradeToTls(tunnelRequest);
+ }
+
+ // Buffer the socket stream to permit efficient parsing of HTTP headers and chunk sizes.
+ if (!isSpdy()) {
+ int bufferSize = 128;
+ in = new BufferedInputStream(in, bufferSize);
+ }
+ }
+
+ /**
+ * Create an {@code SSLSocket} and perform the TLS handshake and certificate
+ * validation.
+ */
+ private void upgradeToTls(TunnelRequest tunnelRequest) throws IOException {
+ Platform platform = Platform.get();
+
+ // Make an SSL Tunnel on the first message pair of each SSL + proxy connection.
+ if (requiresTunnel()) {
+ makeTunnel(tunnelRequest);
+ }
+
+ // Create the wrapper over connected socket.
+ socket = address.sslSocketFactory
+ .createSocket(socket, address.uriHost, address.uriPort, true /* autoClose */);
+ SSLSocket sslSocket = (SSLSocket) socket;
+ if (modernTls) {
+ platform.enableTlsExtensions(sslSocket, address.uriHost);
+ } else {
+ platform.supportTlsIntolerantServer(sslSocket);
+ }
+
+ if (modernTls) {
+ platform.setNpnProtocols(sslSocket, NPN_PROTOCOLS);
+ }
+
+ // Force handshake. This can throw!
+ sslSocket.startHandshake();
+
+ // Verify that the socket's certificates are acceptable for the target host.
+ if (!address.hostnameVerifier.verify(address.uriHost, sslSocket.getSession())) {
+ throw new IOException("Hostname '" + address.uriHost + "' was not verified");
+ }
+
+ out = sslSocket.getOutputStream();
+ in = sslSocket.getInputStream();
+
+ byte[] selectedProtocol;
+ if (modernTls && (selectedProtocol = platform.getNpnSelectedProtocol(sslSocket)) != null) {
+ if (Arrays.equals(selectedProtocol, SPDY3)) {
+ sslSocket.setSoTimeout(0); // SPDY timeouts are set per-stream.
+ spdyConnection = new SpdyConnection.Builder(address.getUriHost(), true, in, out).build();
+ } else if (!Arrays.equals(selectedProtocol, HTTP_11)) {
+ throw new IOException(
+ "Unexpected NPN transport " + new String(selectedProtocol, "ISO-8859-1"));
+ }
+ }
+ }
+
+ /** Returns true if {@link #connect} has been attempted on this connection. */
+ public boolean isConnected() {
+ return connected;
+ }
+
+ @Override public void close() throws IOException {
+ socket.close();
+ }
+
+ /**
+ * Returns the proxy that this connection is using.
+ *
+ * <strong>Warning:</strong> This may be different than the proxy returned
+ * by {@link #getAddress}! That is the proxy that the user asked to be
+ * connected to; this returns the proxy that they were actually connected
+ * to. The two may disagree when a proxy selector selects a different proxy
+ * for a connection.
+ */
+ public Proxy getProxy() {
+ return proxy;
+ }
+
+ public Address getAddress() {
+ return address;
+ }
+
+ public InetSocketAddress getSocketAddress() {
+ return inetSocketAddress;
+ }
+
+ public boolean isModernTls() {
+ return modernTls;
+ }
+
+ /**
+ * Returns the socket that this connection uses, or null if the connection
+ * is not currently connected.
+ */
+ public Socket getSocket() {
+ return socket;
+ }
+
+ /** Returns true if this connection is alive. */
+ public boolean isAlive() {
+ return !socket.isClosed() && !socket.isInputShutdown() && !socket.isOutputShutdown();
+ }
+
+ public void resetIdleStartTime() {
+ if (spdyConnection != null) {
+ throw new IllegalStateException("spdyConnection != null");
+ }
+ this.idleStartTimeNs = System.nanoTime();
+ }
+
+ /** Returns true if this connection is idle. */
+ public boolean isIdle() {
+ return spdyConnection == null || spdyConnection.isIdle();
+ }
+
+ /**
+ * Returns true if this connection has been idle for longer than
+ * {@code keepAliveDurationNs}.
+ */
+ public boolean isExpired(long keepAliveDurationNs) {
+ return isIdle() && System.nanoTime() - getIdleStartTimeNs() > keepAliveDurationNs;
+ }
+
+ /**
+ * Returns the time in ns when this connection became idle. Undefined if
+ * this connection is not idle.
+ */
+ public long getIdleStartTimeNs() {
+ return spdyConnection == null ? idleStartTimeNs : spdyConnection.getIdleStartTimeNs();
+ }
+
+ /** Returns the transport appropriate for this connection. */
+ public Object newTransport(HttpEngine httpEngine) throws IOException {
+ return (spdyConnection != null) ? new SpdyTransport(httpEngine, spdyConnection)
+ : new HttpTransport(httpEngine, out, in);
+ }
+
+ /**
+ * Returns true if this is a SPDY connection. Such connections can be used
+ * in multiple HTTP requests simultaneously.
+ */
+ public boolean isSpdy() {
+ return spdyConnection != null;
+ }
+
+ public SpdyConnection getSpdyConnection() {
+ return spdyConnection;
+ }
+
+ /**
+ * Returns the minor HTTP version that should be used for future requests on
+ * this connection. Either 0 for HTTP/1.0, or 1 for HTTP/1.1. The default
+ * value is 1 for new connections.
+ */
+ public int getHttpMinorVersion() {
+ return httpMinorVersion;
+ }
+
+ public void setHttpMinorVersion(int httpMinorVersion) {
+ this.httpMinorVersion = httpMinorVersion;
+ }
+
+ /**
+ * Returns true if the HTTP connection needs to tunnel one protocol over
+ * another, such as when using HTTPS through an HTTP proxy. When doing so,
+ * we must avoid buffering bytes intended for the higher-level protocol.
+ */
+ public boolean requiresTunnel() {
+ return address.sslSocketFactory != null && proxy != null && proxy.type() == Proxy.Type.HTTP;
+ }
+
+ /**
+ * 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 makeTunnel(TunnelRequest tunnelRequest) throws IOException {
+ RawHeaders requestHeaders = tunnelRequest.getRequestHeaders();
+ while (true) {
+ out.write(requestHeaders.toBytes());
+ RawHeaders responseHeaders = RawHeaders.fromBytes(in);
+
+ switch (responseHeaders.getResponseCode()) {
+ case HTTP_OK:
+ return;
+ case HTTP_PROXY_AUTH:
+ requestHeaders = new RawHeaders(requestHeaders);
+ URL url = new URL("https", tunnelRequest.host, tunnelRequest.port, "/");
+ boolean credentialsFound =
+ HttpAuthenticator.processAuthHeader(HTTP_PROXY_AUTH, responseHeaders, requestHeaders,
+ proxy, url);
+ if (credentialsFound) {
+ continue;
+ } else {
+ throw new IOException("Failed to authenticate with proxy");
+ }
+ default:
+ throw new IOException(
+ "Unexpected response code for CONNECT: " + responseHeaders.getResponseCode());
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/553a25ce/framework/src/com/squareup/okhttp/ConnectionPool.java
----------------------------------------------------------------------
diff --git a/framework/src/com/squareup/okhttp/ConnectionPool.java b/framework/src/com/squareup/okhttp/ConnectionPool.java
new file mode 100644
index 0000000..4eff4ec
--- /dev/null
+++ b/framework/src/com/squareup/okhttp/ConnectionPool.java
@@ -0,0 +1,257 @@
+package com.squareup.okhttp;
+
+import com.squareup.okhttp.internal.Platform;
+import com.squareup.okhttp.internal.Util;
+import java.net.SocketException;
+import java.util.ArrayList;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Manages reuse of HTTP and SPDY connections for reduced network latency. HTTP
+ * requests that share the same {@link com.squareup.okhttp.Address} may share a
+ * {@link com.squareup.okhttp.Connection}. This class implements the policy of
+ * which connections to keep open for future use.
+ *
+ * <p>The {@link #getDefault() system-wide default} uses system properties for
+ * tuning parameters:
+ * <ul>
+ * <li>{@code http.keepAlive} true if HTTP and SPDY connections should be
+ * pooled at all. Default is true.
+ * <li>{@code http.maxConnections} maximum number of idle connections to
+ * each to keep in the pool. Default is 5.
+ * <li>{@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}.
+ * </ul>
+ *
+ * <p>The default instance <i>doesn't</i> 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 class ConnectionPool {
+ private static final int MAX_CONNECTIONS_TO_CLEANUP = 2;
+ private static final long DEFAULT_KEEP_ALIVE_DURATION_MS = 5 * 60 * 1000; // 5 min
+
+ private static final ConnectionPool systemDefault;
+
+ static {
+ String keepAlive = System.getProperty("http.keepAlive");
+ String keepAliveDuration = System.getProperty("http.keepAliveDuration");
+ String maxIdleConnections = System.getProperty("http.maxConnections");
+ long keepAliveDurationMs = keepAliveDuration != null ? Long.parseLong(keepAliveDuration)
+ : DEFAULT_KEEP_ALIVE_DURATION_MS;
+ if (keepAlive != null && !Boolean.parseBoolean(keepAlive)) {
+ systemDefault = new ConnectionPool(0, keepAliveDurationMs);
+ } else if (maxIdleConnections != null) {
+ systemDefault = new ConnectionPool(Integer.parseInt(maxIdleConnections), keepAliveDurationMs);
+ } else {
+ systemDefault = new ConnectionPool(5, keepAliveDurationMs);
+ }
+ }
+
+ /** The maximum number of idle connections for each address. */
+ private final int maxIdleConnections;
+ private final long keepAliveDurationNs;
+
+ private final LinkedList<Connection> connections = new LinkedList<Connection>();
+
+ /** We use a single background thread to cleanup expired connections. */
+ private final ExecutorService executorService =
+ new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
+ private final Callable<Void> connectionsCleanupCallable = new Callable<Void>() {
+ @Override public Void call() throws Exception {
+ List<Connection> expiredConnections = new ArrayList<Connection>(MAX_CONNECTIONS_TO_CLEANUP);
+ int idleConnectionCount = 0;
+ synchronized (ConnectionPool.this) {
+ for (ListIterator<Connection> i = connections.listIterator(connections.size());
+ i.hasPrevious(); ) {
+ Connection connection = i.previous();
+ if (!connection.isAlive() || connection.isExpired(keepAliveDurationNs)) {
+ i.remove();
+ expiredConnections.add(connection);
+ if (expiredConnections.size() == MAX_CONNECTIONS_TO_CLEANUP) break;
+ } else if (connection.isIdle()) {
+ idleConnectionCount++;
+ }
+ }
+
+ for (ListIterator<Connection> i = connections.listIterator(connections.size());
+ i.hasPrevious() && idleConnectionCount > maxIdleConnections; ) {
+ Connection connection = i.previous();
+ if (connection.isIdle()) {
+ expiredConnections.add(connection);
+ i.remove();
+ --idleConnectionCount;
+ }
+ }
+ }
+ for (Connection expiredConnection : expiredConnections) {
+ Util.closeQuietly(expiredConnection);
+ }
+ return null;
+ }
+ };
+
+ public ConnectionPool(int maxIdleConnections, long keepAliveDurationMs) {
+ this.maxIdleConnections = maxIdleConnections;
+ this.keepAliveDurationNs = keepAliveDurationMs * 1000 * 1000;
+ }
+
+ /**
+ * Returns a snapshot of the connections in this pool, ordered from newest to
+ * oldest. Waits for the cleanup callable to run if it is currently scheduled.
+ */
+ List<Connection> getConnections() {
+ waitForCleanupCallableToRun();
+ synchronized (this) {
+ return new ArrayList<Connection>(connections);
+ }
+ }
+
+ /**
+ * Blocks until the executor service has processed all currently enqueued
+ * jobs.
+ */
+ private void waitForCleanupCallableToRun() {
+ try {
+ executorService.submit(new Runnable() {
+ @Override public void run() {
+ }
+ }).get();
+ } catch (Exception e) {
+ throw new AssertionError();
+ }
+ }
+
+ public static ConnectionPool getDefault() {
+ return systemDefault;
+ }
+
+ /** Returns total number of connections in the pool. */
+ public synchronized int getConnectionCount() {
+ return connections.size();
+ }
+
+ /** Returns total number of spdy connections in the pool. */
+ public synchronized int getSpdyConnectionCount() {
+ int total = 0;
+ for (Connection connection : connections) {
+ if (connection.isSpdy()) total++;
+ }
+ return total;
+ }
+
+ /** Returns total number of http connections in the pool. */
+ public synchronized int getHttpConnectionCount() {
+ int total = 0;
+ for (Connection connection : connections) {
+ if (!connection.isSpdy()) total++;
+ }
+ return total;
+ }
+
+ /** Returns a recycled connection to {@code address}, or null if no such connection exists. */
+ public synchronized Connection get(Address address) {
+ Connection foundConnection = null;
+ for (ListIterator<Connection> i = connections.listIterator(connections.size());
+ i.hasPrevious(); ) {
+ Connection connection = i.previous();
+ if (!connection.getAddress().equals(address)
+ || !connection.isAlive()
+ || System.nanoTime() - connection.getIdleStartTimeNs() >= keepAliveDurationNs) {
+ continue;
+ }
+ i.remove();
+ if (!connection.isSpdy()) {
+ try {
+ Platform.get().tagSocket(connection.getSocket());
+ } catch (SocketException e) {
+ Util.closeQuietly(connection);
+ // When unable to tag, skip recycling and close
+ Platform.get().logW("Unable to tagSocket(): " + e);
+ continue;
+ }
+ }
+ foundConnection = connection;
+ break;
+ }
+
+ if (foundConnection != null && foundConnection.isSpdy()) {
+ connections.addFirst(foundConnection); // Add it back after iteration.
+ }
+
+ executorService.submit(connectionsCleanupCallable);
+ return foundConnection;
+ }
+
+ /**
+ * Gives {@code connection} to the pool. The pool may store the connection,
+ * or close it, as its policy describes.
+ *
+ * <p>It is an error to use {@code connection} after calling this method.
+ */
+ public void recycle(Connection connection) {
+ executorService.submit(connectionsCleanupCallable);
+
+ if (connection.isSpdy()) {
+ return;
+ }
+
+ if (!connection.isAlive()) {
+ Util.closeQuietly(connection);
+ return;
+ }
+
+ try {
+ Platform.get().untagSocket(connection.getSocket());
+ } catch (SocketException e) {
+ // When unable to remove tagging, skip recycling and close.
+ Platform.get().logW("Unable to untagSocket(): " + e);
+ Util.closeQuietly(connection);
+ return;
+ }
+
+ synchronized (this) {
+ connections.addFirst(connection);
+ connection.resetIdleStartTime();
+ }
+ }
+
+ /**
+ * Shares the SPDY connection with the pool. Callers to this method may
+ * continue to use {@code connection}.
+ */
+ public void maybeShare(Connection connection) {
+ executorService.submit(connectionsCleanupCallable);
+ if (!connection.isSpdy()) {
+ // Only SPDY connections are sharable.
+ return;
+ }
+ if (connection.isAlive()) {
+ synchronized (this) {
+ connections.addFirst(connection);
+ }
+ }
+ }
+
+ /** Close and remove all connections in the pool. */
+ public void evictAll() {
+ List<Connection> connections;
+ synchronized (this) {
+ connections = new ArrayList<Connection>(this.connections);
+ this.connections.clear();
+ }
+
+ for (Connection connection : connections) {
+ Util.closeQuietly(connection);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/553a25ce/framework/src/com/squareup/okhttp/OkHttpClient.java
----------------------------------------------------------------------
diff --git a/framework/src/com/squareup/okhttp/OkHttpClient.java b/framework/src/com/squareup/okhttp/OkHttpClient.java
new file mode 100644
index 0000000..d21cdb7
--- /dev/null
+++ b/framework/src/com/squareup/okhttp/OkHttpClient.java
@@ -0,0 +1,198 @@
+/*
+ * Copyright (C) 2012 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp;
+
+import com.squareup.okhttp.internal.http.HttpURLConnectionImpl;
+import com.squareup.okhttp.internal.http.HttpsURLConnectionImpl;
+import java.net.CookieHandler;
+import java.net.HttpURLConnection;
+import java.net.Proxy;
+import java.net.ProxySelector;
+import java.net.ResponseCache;
+import java.net.URL;
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLSocketFactory;
+
+/** Configures and creates HTTP connections. */
+public final class OkHttpClient {
+ private Proxy proxy;
+ private ProxySelector proxySelector;
+ private CookieHandler cookieHandler;
+ private ResponseCache responseCache;
+ private SSLSocketFactory sslSocketFactory;
+ private HostnameVerifier hostnameVerifier;
+ private ConnectionPool connectionPool;
+ private boolean followProtocolRedirects = true;
+
+ /**
+ * 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;
+ return this;
+ }
+
+ public Proxy getProxy() {
+ return proxy;
+ }
+
+ /**
+ * 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.
+ *
+ * <p>If unset, the {@link ProxySelector#getDefault() system-wide default}
+ * proxy selector will be used.
+ */
+ public OkHttpClient setProxySelector(ProxySelector proxySelector) {
+ this.proxySelector = proxySelector;
+ return this;
+ }
+
+ public ProxySelector getProxySelector() {
+ return proxySelector;
+ }
+
+ /**
+ * Sets the cookie handler to be used to read outgoing cookies and write
+ * incoming cookies.
+ *
+ * <p>If unset, the {@link CookieHandler#getDefault() system-wide default}
+ * cookie handler will be used.
+ */
+ public OkHttpClient setCookieHandler(CookieHandler cookieHandler) {
+ this.cookieHandler = cookieHandler;
+ return this;
+ }
+
+ public CookieHandler getCookieHandler() {
+ return cookieHandler;
+ }
+
+ /**
+ * Sets the response cache to be used to read and write cached responses.
+ *
+ * <p>If unset, the {@link ResponseCache#getDefault() system-wide default}
+ * response cache will be used.
+ */
+ public OkHttpClient setResponseCache(ResponseCache responseCache) {
+ this.responseCache = responseCache;
+ return this;
+ }
+
+ public ResponseCache getResponseCache() {
+ return responseCache;
+ }
+
+ /**
+ * Sets the socket factory used to secure HTTPS connections.
+ *
+ * <p>If unset, the {@link HttpsURLConnection#getDefaultSSLSocketFactory()
+ * system-wide default} SSL socket factory will be used.
+ */
+ public OkHttpClient setSSLSocketFactory(SSLSocketFactory sslSocketFactory) {
+ this.sslSocketFactory = sslSocketFactory;
+ return this;
+ }
+
+ public SSLSocketFactory getSslSocketFactory() {
+ return sslSocketFactory;
+ }
+
+ /**
+ * Sets the verifier used to confirm that response certificates apply to
+ * requested hostnames for HTTPS connections.
+ *
+ * <p>If unset, the {@link HttpsURLConnection#getDefaultHostnameVerifier()
+ * system-wide default} hostname verifier will be used.
+ */
+ public OkHttpClient setHostnameVerifier(HostnameVerifier hostnameVerifier) {
+ this.hostnameVerifier = hostnameVerifier;
+ return this;
+ }
+
+ public HostnameVerifier getHostnameVerifier() {
+ return hostnameVerifier;
+ }
+
+ /**
+ * Sets the connection pool used to recycle HTTP and HTTPS connections.
+ *
+ * <p>If unset, the {@link ConnectionPool#getDefault() system-wide
+ * default} connection pool will be used.
+ */
+ public OkHttpClient setConnectionPool(ConnectionPool connectionPool) {
+ this.connectionPool = connectionPool;
+ return this;
+ }
+
+ public ConnectionPool getConnectionPool() {
+ return connectionPool;
+ }
+
+ /**
+ * Configure this client to follow redirects from HTTPS to HTTP and from HTTP
+ * to HTTPS.
+ *
+ * <p>If unset, protocol redirects will be followed. This is different than
+ * the built-in {@code HttpURLConnection}'s default.
+ */
+ public OkHttpClient setFollowProtocolRedirects(boolean followProtocolRedirects) {
+ this.followProtocolRedirects = followProtocolRedirects;
+ return this;
+ }
+
+ public boolean getFollowProtocolRedirects() {
+ return followProtocolRedirects;
+ }
+
+ public HttpURLConnection open(URL url) {
+ String protocol = url.getProtocol();
+ if (protocol.equals("http")) {
+ return new HttpURLConnectionImpl(url, copyWithDefaults());
+ } else if (protocol.equals("https")) {
+ return new HttpsURLConnectionImpl(url, copyWithDefaults());
+ } else {
+ throw new IllegalArgumentException("Unexpected protocol: " + protocol);
+ }
+ }
+
+ /**
+ * Returns a copy of this OkHttpClient that uses the system-wide default for
+ * each field that hasn't been explicitly configured.
+ */
+ private OkHttpClient copyWithDefaults() {
+ OkHttpClient result = new OkHttpClient();
+ result.proxy = proxy;
+ result.proxySelector = proxySelector != null ? proxySelector : ProxySelector.getDefault();
+ result.cookieHandler = cookieHandler != null ? cookieHandler : CookieHandler.getDefault();
+ result.responseCache = responseCache != null ? responseCache : ResponseCache.getDefault();
+ result.sslSocketFactory = sslSocketFactory != null
+ ? sslSocketFactory
+ : HttpsURLConnection.getDefaultSSLSocketFactory();
+ result.hostnameVerifier = hostnameVerifier != null
+ ? hostnameVerifier
+ : HttpsURLConnection.getDefaultHostnameVerifier();
+ result.connectionPool = connectionPool != null ? connectionPool : ConnectionPool.getDefault();
+ result.followProtocolRedirects = followProtocolRedirects;
+ return result;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/553a25ce/framework/src/com/squareup/okhttp/OkResponseCache.java
----------------------------------------------------------------------
diff --git a/framework/src/com/squareup/okhttp/OkResponseCache.java b/framework/src/com/squareup/okhttp/OkResponseCache.java
new file mode 100644
index 0000000..b7e3801
--- /dev/null
+++ b/framework/src/com/squareup/okhttp/OkResponseCache.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp;
+
+import java.io.IOException;
+import java.net.CacheResponse;
+import java.net.HttpURLConnection;
+
+/**
+ * A response cache that supports statistics tracking and updating stored
+ * responses. Implementations of {@link java.net.ResponseCache} should implement
+ * this interface to receive additional support from the HTTP engine.
+ */
+public interface OkResponseCache {
+
+ /** Track an HTTP response being satisfied by {@code source}. */
+ void trackResponse(ResponseSource source);
+
+ /** Track an conditional GET that was satisfied by this cache. */
+ void trackConditionalCacheHit();
+
+ /** Updates stored HTTP headers using a hit on a conditional GET. */
+ void update(CacheResponse conditionalCacheHit, HttpURLConnection httpConnection)
+ throws IOException;
+}
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/553a25ce/framework/src/com/squareup/okhttp/ResponseSource.java
----------------------------------------------------------------------
diff --git a/framework/src/com/squareup/okhttp/ResponseSource.java b/framework/src/com/squareup/okhttp/ResponseSource.java
new file mode 100644
index 0000000..4eca172
--- /dev/null
+++ b/framework/src/com/squareup/okhttp/ResponseSource.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp;
+
+/** The source of an HTTP response. */
+public enum ResponseSource {
+
+ /** The response was returned from the local cache. */
+ CACHE,
+
+ /**
+ * The response is available in the cache but must be validated with the
+ * network. The cache result will be used if it is still valid; otherwise
+ * the network's response will be used.
+ */
+ CONDITIONAL_CACHE,
+
+ /** The response was returned from the network. */
+ NETWORK;
+
+ public boolean requiresConnection() {
+ return this == CONDITIONAL_CACHE || this == NETWORK;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/553a25ce/framework/src/com/squareup/okhttp/TunnelRequest.java
----------------------------------------------------------------------
diff --git a/framework/src/com/squareup/okhttp/TunnelRequest.java b/framework/src/com/squareup/okhttp/TunnelRequest.java
new file mode 100644
index 0000000..5260b87
--- /dev/null
+++ b/framework/src/com/squareup/okhttp/TunnelRequest.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp;
+
+import com.squareup.okhttp.internal.http.RawHeaders;
+
+import static com.squareup.okhttp.internal.Util.getDefaultPort;
+
+/**
+ * Routing and authentication information sent to an HTTP proxy to create a
+ * HTTPS to an origin server. Everything in the tunnel request is sent
+ * unencrypted to the proxy server.
+ *
+ * <p>See <a href="http://www.ietf.org/rfc/rfc2817.txt">RFC 2817, Section
+ * 5.2</a>.
+ */
+public final class TunnelRequest {
+ final String host;
+ final int port;
+ final String userAgent;
+ final String proxyAuthorization;
+
+ /**
+ * @param host the origin server's hostname. Not null.
+ * @param port the origin server's port, like 80 or 443.
+ * @param userAgent the client's user-agent. Not null.
+ * @param proxyAuthorization proxy authorization, or null if the proxy is
+ * used without an authorization header.
+ */
+ public TunnelRequest(String host, int port, String userAgent, String proxyAuthorization) {
+ if (host == null) throw new NullPointerException("host == null");
+ if (userAgent == null) throw new NullPointerException("userAgent == null");
+ this.host = host;
+ this.port = port;
+ this.userAgent = userAgent;
+ this.proxyAuthorization = proxyAuthorization;
+ }
+
+ /**
+ * If we're creating a TLS tunnel, send only the minimum set of headers.
+ * This avoids sending potentially sensitive data like HTTP cookies to
+ * the proxy unencrypted.
+ */
+ RawHeaders getRequestHeaders() {
+ RawHeaders result = new RawHeaders();
+ result.setRequestLine("CONNECT " + host + ":" + port + " HTTP/1.1");
+
+ // Always set Host and User-Agent.
+ result.set("Host", port == getDefaultPort("https") ? host : (host + ":" + port));
+ result.set("User-Agent", userAgent);
+
+ // Copy over the Proxy-Authorization header if it exists.
+ if (proxyAuthorization != null) {
+ result.set("Proxy-Authorization", proxyAuthorization);
+ }
+
+ // Always set the Proxy-Connection to Keep-Alive for the benefit of
+ // HTTP/1.0 proxies like Squid.
+ result.set("Proxy-Connection", "Keep-Alive");
+ return result;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/553a25ce/framework/src/com/squareup/okhttp/internal/Base64.java
----------------------------------------------------------------------
diff --git a/framework/src/com/squareup/okhttp/internal/Base64.java b/framework/src/com/squareup/okhttp/internal/Base64.java
new file mode 100644
index 0000000..79cd020
--- /dev/null
+++ b/framework/src/com/squareup/okhttp/internal/Base64.java
@@ -0,0 +1,164 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @author Alexander Y. Kleymenov
+ */
+
+package com.squareup.okhttp.internal;
+
+import java.io.UnsupportedEncodingException;
+
+import static com.squareup.okhttp.internal.Util.EMPTY_BYTE_ARRAY;
+
+/**
+ * <a href="http://www.ietf.org/rfc/rfc2045.txt">Base64</a> encoder/decoder.
+ * In violation of the RFC, this encoder doesn't wrap lines at 76 columns.
+ */
+public final class Base64 {
+ private Base64() {
+ }
+
+ public static byte[] decode(byte[] in) {
+ return decode(in, in.length);
+ }
+
+ public static byte[] decode(byte[] in, int len) {
+ // approximate output length
+ int length = len / 4 * 3;
+ // return an empty array on empty or short input without padding
+ if (length == 0) {
+ return EMPTY_BYTE_ARRAY;
+ }
+ // temporary array
+ byte[] out = new byte[length];
+ // number of padding characters ('=')
+ int pad = 0;
+ byte chr;
+ // compute the number of the padding characters
+ // and adjust the length of the input
+ for (; ; len--) {
+ chr = in[len - 1];
+ // skip the neutral characters
+ if ((chr == '\n') || (chr == '\r') || (chr == ' ') || (chr == '\t')) {
+ continue;
+ }
+ if (chr == '=') {
+ pad++;
+ } else {
+ break;
+ }
+ }
+ // index in the output array
+ int outIndex = 0;
+ // index in the input array
+ int inIndex = 0;
+ // holds the value of the input character
+ int bits = 0;
+ // holds the value of the input quantum
+ int quantum = 0;
+ for (int i = 0; i < len; i++) {
+ chr = in[i];
+ // skip the neutral characters
+ if ((chr == '\n') || (chr == '\r') || (chr == ' ') || (chr == '\t')) {
+ continue;
+ }
+ if ((chr >= 'A') && (chr <= 'Z')) {
+ // char ASCII value
+ // A 65 0
+ // Z 90 25 (ASCII - 65)
+ bits = chr - 65;
+ } else if ((chr >= 'a') && (chr <= 'z')) {
+ // char ASCII value
+ // a 97 26
+ // z 122 51 (ASCII - 71)
+ bits = chr - 71;
+ } else if ((chr >= '0') && (chr <= '9')) {
+ // char ASCII value
+ // 0 48 52
+ // 9 57 61 (ASCII + 4)
+ bits = chr + 4;
+ } else if (chr == '+') {
+ bits = 62;
+ } else if (chr == '/') {
+ bits = 63;
+ } else {
+ return null;
+ }
+ // append the value to the quantum
+ quantum = (quantum << 6) | (byte) bits;
+ if (inIndex % 4 == 3) {
+ // 4 characters were read, so make the output:
+ out[outIndex++] = (byte) (quantum >> 16);
+ out[outIndex++] = (byte) (quantum >> 8);
+ out[outIndex++] = (byte) quantum;
+ }
+ inIndex++;
+ }
+ if (pad > 0) {
+ // adjust the quantum value according to the padding
+ quantum = quantum << (6 * pad);
+ // make output
+ out[outIndex++] = (byte) (quantum >> 16);
+ if (pad == 1) {
+ out[outIndex++] = (byte) (quantum >> 8);
+ }
+ }
+ // create the resulting array
+ byte[] result = new byte[outIndex];
+ System.arraycopy(out, 0, result, 0, outIndex);
+ return result;
+ }
+
+ private static final byte[] MAP = new byte[] {
+ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
+ 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
+ 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4',
+ '5', '6', '7', '8', '9', '+', '/'
+ };
+
+ public static String encode(byte[] in) {
+ int length = (in.length + 2) * 4 / 3;
+ byte[] out = new byte[length];
+ int index = 0, end = in.length - in.length % 3;
+ for (int i = 0; i < end; i += 3) {
+ out[index++] = MAP[(in[i] & 0xff) >> 2];
+ out[index++] = MAP[((in[i] & 0x03) << 4) | ((in[i + 1] & 0xff) >> 4)];
+ out[index++] = MAP[((in[i + 1] & 0x0f) << 2) | ((in[i + 2] & 0xff) >> 6)];
+ out[index++] = MAP[(in[i + 2] & 0x3f)];
+ }
+ switch (in.length % 3) {
+ case 1:
+ out[index++] = MAP[(in[end] & 0xff) >> 2];
+ out[index++] = MAP[(in[end] & 0x03) << 4];
+ out[index++] = '=';
+ out[index++] = '=';
+ break;
+ case 2:
+ out[index++] = MAP[(in[end] & 0xff) >> 2];
+ out[index++] = MAP[((in[end] & 0x03) << 4) | ((in[end + 1] & 0xff) >> 4)];
+ out[index++] = MAP[((in[end + 1] & 0x0f) << 2)];
+ out[index++] = '=';
+ break;
+ }
+ try {
+ return new String(out, 0, index, "US-ASCII");
+ } catch (UnsupportedEncodingException e) {
+ throw new AssertionError(e);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/553a25ce/framework/src/com/squareup/okhttp/internal/DiskLruCache.java
----------------------------------------------------------------------
diff --git a/framework/src/com/squareup/okhttp/internal/DiskLruCache.java b/framework/src/com/squareup/okhttp/internal/DiskLruCache.java
new file mode 100644
index 0000000..00fe2f1
--- /dev/null
+++ b/framework/src/com/squareup/okhttp/internal/DiskLruCache.java
@@ -0,0 +1,826 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp.internal;
+
+import java.io.BufferedWriter;
+import java.io.Closeable;
+import java.io.EOFException;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.FileWriter;
+import java.io.FilterOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+import static com.squareup.okhttp.internal.Util.UTF_8;
+
+/**
+ * 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. Values are byte
+ * sequences, accessible as streams or files. Each value must be between {@code
+ * 0} and {@code Integer.MAX_VALUE} bytes in length.
+ *
+ * <p>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.
+ *
+ * <p>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.
+ *
+ * <p>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.
+ * <ul>
+ * <li>When an entry is being <strong>created</strong> it is necessary to
+ * supply a full set of values; the empty value should be used as a
+ * placeholder if necessary.
+ * <li>When an entry is being <strong>edited</strong>, it is not necessary
+ * to supply data for every value; values default to their previous
+ * value.
+ * </ul>
+ * 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.
+ *
+ * <p>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.
+ *
+ * <p>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";
+ static final String JOURNAL_FILE_TMP = "journal.tmp";
+ static final String MAGIC = "libcore.io.DiskLruCache";
+ static final String VERSION_1 = "1";
+ static final long ANY_SEQUENCE_NUMBER = -1;
+ private static final String CLEAN = "CLEAN";
+ private static final String DIRTY = "DIRTY";
+ private static final String REMOVE = "REMOVE";
+ private static final String READ = "READ";
+
+ // This cache uses a journal file named "journal". A typical journal file
+ // looks like this:
+ // libcore.io.DiskLruCache
+ // 1
+ // 100
+ // 2
+ //
+ // CLEAN 3400330d1dfc7f3f7f4b8d4d803dfcf6 832 21054
+ // DIRTY 335c4c6028171cfddfbaae1a9c313c52
+ // CLEAN 335c4c6028171cfddfbaae1a9c313c52 3934 2342
+ // REMOVE 335c4c6028171cfddfbaae1a9c313c52
+ // DIRTY 1ab96a171faeeee38496d8b330771a7a
+ // CLEAN 1ab96a171faeeee38496d8b330771a7a 1600 234
+ // READ 335c4c6028171cfddfbaae1a9c313c52
+ // READ 3400330d1dfc7f3f7f4b8d4d803dfcf6
+ //
+ // The first five lines of the journal form its header. They are the
+ // constant string "libcore.io.DiskLruCache", the disk cache's version,
+ // the application's version, the value count, and a blank line.
+ //
+ // Each of the subsequent lines in the file is a record of the state of a
+ // cache entry. Each line contains space-separated values: a state, a key,
+ // and optional state-specific values.
+ // o DIRTY lines track that an entry is actively being created or updated.
+ // Every successful DIRTY action should be followed by a CLEAN or REMOVE
+ // action. DIRTY lines without a matching CLEAN or REMOVE indicate that
+ // temporary files may need to be deleted.
+ // o CLEAN lines track a cache entry that has been successfully published
+ // and may be read. A publish line is followed by the lengths of each of
+ // its values.
+ // o READ lines track accesses for LRU.
+ // o REMOVE lines track entries that have been deleted.
+ //
+ // The journal file is appended to as cache operations occur. The journal may
+ // occasionally be compacted by dropping redundant lines. A temporary file named
+ // "journal.tmp" will be used during compaction; that file should be deleted if
+ // it exists when the cache is opened.
+
+ private final File directory;
+ private final File journalFile;
+ private final File journalFileTmp;
+ private final int appVersion;
+ private final long maxSize;
+ private final int valueCount;
+ private long size = 0;
+ private Writer journalWriter;
+ private final LinkedHashMap<String, Entry> lruEntries =
+ new LinkedHashMap<String, Entry>(0, 0.75f, true);
+ private int redundantOpCount;
+
+ /**
+ * 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;
+
+ /** This cache uses a single background thread to evict entries. */
+ private final ExecutorService executorService =
+ new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
+ private final Callable<Void> cleanupCallable = new Callable<Void>() {
+ @Override public Void call() throws Exception {
+ synchronized (DiskLruCache.this) {
+ if (journalWriter == null) {
+ return null; // closed
+ }
+ trimToSize();
+ if (journalRebuildRequired()) {
+ rebuildJournal();
+ redundantOpCount = 0;
+ }
+ }
+ return null;
+ }
+ };
+
+ private DiskLruCache(File directory, int appVersion, int valueCount, long maxSize) {
+ this.directory = directory;
+ this.appVersion = appVersion;
+ this.journalFile = new File(directory, JOURNAL_FILE);
+ this.journalFileTmp = new File(directory, JOURNAL_FILE_TMP);
+ this.valueCount = valueCount;
+ this.maxSize = maxSize;
+ }
+
+ /**
+ * Opens the cache in {@code directory}, creating a cache if none exists
+ * there.
+ *
+ * @param directory a writable directory
+ * @param valueCount the number of values per cache entry. Must be positive.
+ * @param maxSize the maximum number of bytes this cache should use to store
+ * @throws IOException if reading or writing the cache directory fails
+ */
+ public static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize)
+ throws IOException {
+ if (maxSize <= 0) {
+ throw new IllegalArgumentException("maxSize <= 0");
+ }
+ if (valueCount <= 0) {
+ throw new IllegalArgumentException("valueCount <= 0");
+ }
+
+ // prefer to pick up where we left off
+ DiskLruCache cache = new DiskLruCache(directory, appVersion, valueCount, maxSize);
+ if (cache.journalFile.exists()) {
+ try {
+ cache.readJournal();
+ cache.processJournal();
+ cache.journalWriter = new BufferedWriter(new FileWriter(cache.journalFile, true));
+ return cache;
+ } catch (IOException journalIsCorrupt) {
+ Platform.get()
+ .logW("DiskLruCache "
+ + directory
+ + " is corrupt: "
+ + journalIsCorrupt.getMessage()
+ + ", removing");
+ cache.delete();
+ }
+ }
+
+ // create a new empty cache
+ directory.mkdirs();
+ cache = new DiskLruCache(directory, appVersion, valueCount, maxSize);
+ cache.rebuildJournal();
+ return cache;
+ }
+
+ private void readJournal() throws IOException {
+ StrictLineReader reader = new StrictLineReader(new FileInputStream(journalFile), Util.US_ASCII);
+ try {
+ String magic = reader.readLine();
+ String version = reader.readLine();
+ String appVersionString = reader.readLine();
+ String valueCountString = reader.readLine();
+ String blank = reader.readLine();
+ if (!MAGIC.equals(magic) || !VERSION_1.equals(version) || !Integer.toString(appVersion)
+ .equals(appVersionString) || !Integer.toString(valueCount).equals(valueCountString) || !""
+ .equals(blank)) {
+ throw new IOException("unexpected journal header: ["
+ + magic
+ + ", "
+ + version
+ + ", "
+ + valueCountString
+ + ", "
+ + blank
+ + "]");
+ }
+
+ while (true) {
+ try {
+ readJournalLine(reader.readLine());
+ } catch (EOFException endOfJournal) {
+ break;
+ }
+ }
+ } finally {
+ Util.closeQuietly(reader);
+ }
+ }
+
+ private void readJournalLine(String line) throws IOException {
+ String[] parts = line.split(" ");
+ if (parts.length < 2) {
+ throw new IOException("unexpected journal line: " + line);
+ }
+
+ String key = parts[1];
+ if (parts[0].equals(REMOVE) && parts.length == 2) {
+ lruEntries.remove(key);
+ return;
+ }
+
+ Entry entry = lruEntries.get(key);
+ if (entry == null) {
+ entry = new Entry(key);
+ lruEntries.put(key, entry);
+ }
+
+ if (parts[0].equals(CLEAN) && parts.length == 2 + valueCount) {
+ entry.readable = true;
+ entry.currentEditor = null;
+ entry.setLengths(Arrays.copyOfRange(parts, 2, parts.length));
+ } else if (parts[0].equals(DIRTY) && parts.length == 2) {
+ entry.currentEditor = new Editor(entry);
+ } else if (parts[0].equals(READ) && parts.length == 2) {
+ // this work was already done by calling lruEntries.get()
+ } else {
+ throw new IOException("unexpected journal line: " + line);
+ }
+ }
+
+ /**
+ * 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 {
+ deleteIfExists(journalFileTmp);
+ for (Iterator<Entry> i = lruEntries.values().iterator(); i.hasNext(); ) {
+ Entry entry = i.next();
+ if (entry.currentEditor == null) {
+ for (int t = 0; t < valueCount; t++) {
+ size += entry.lengths[t];
+ }
+ } else {
+ entry.currentEditor = null;
+ for (int t = 0; t < valueCount; t++) {
+ deleteIfExists(entry.getCleanFile(t));
+ deleteIfExists(entry.getDirtyFile(t));
+ }
+ i.remove();
+ }
+ }
+ }
+
+ /**
+ * 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) {
+ journalWriter.close();
+ }
+
+ Writer writer = new BufferedWriter(new FileWriter(journalFileTmp));
+ writer.write(MAGIC);
+ writer.write("\n");
+ writer.write(VERSION_1);
+ writer.write("\n");
+ writer.write(Integer.toString(appVersion));
+ writer.write("\n");
+ writer.write(Integer.toString(valueCount));
+ writer.write("\n");
+ writer.write("\n");
+
+ for (Entry entry : lruEntries.values()) {
+ if (entry.currentEditor != null) {
+ writer.write(DIRTY + ' ' + entry.key + '\n');
+ } else {
+ writer.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n');
+ }
+ }
+
+ writer.close();
+ journalFileTmp.renameTo(journalFile);
+ journalWriter = new BufferedWriter(new FileWriter(journalFile, true));
+ }
+
+ private static void deleteIfExists(File file) throws IOException {
+ file.delete();
+ }
+
+ /**
+ * 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 {
+ checkNotClosed();
+ validateKey(key);
+ Entry entry = lruEntries.get(key);
+ if (entry == null) {
+ return null;
+ }
+
+ if (!entry.readable) {
+ return null;
+ }
+
+ // Open all streams eagerly to guarantee that we see a single published
+ // snapshot. If we opened streams lazily then the streams could come
+ // from different edits.
+ InputStream[] ins = new InputStream[valueCount];
+ try {
+ for (int i = 0; i < valueCount; i++) {
+ ins[i] = new FileInputStream(entry.getCleanFile(i));
+ }
+ } catch (FileNotFoundException e) {
+ // a file must have been deleted manually!
+ return null;
+ }
+
+ redundantOpCount++;
+ journalWriter.append(READ + ' ' + key + '\n');
+ if (journalRebuildRequired()) {
+ executorService.submit(cleanupCallable);
+ }
+
+ return new Snapshot(key, entry.sequenceNumber, ins);
+ }
+
+ /**
+ * 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);
+ }
+
+ private synchronized Editor edit(String key, long expectedSequenceNumber) throws IOException {
+ checkNotClosed();
+ validateKey(key);
+ Entry entry = lruEntries.get(key);
+ if (expectedSequenceNumber != ANY_SEQUENCE_NUMBER && (entry == null
+ || entry.sequenceNumber != expectedSequenceNumber)) {
+ return null; // snapshot is stale
+ }
+ if (entry == null) {
+ entry = new Entry(key);
+ lruEntries.put(key, entry);
+ } else if (entry.currentEditor != null) {
+ return null; // another edit is in progress
+ }
+
+ Editor editor = new Editor(entry);
+ entry.currentEditor = editor;
+
+ // flush the journal before creating files to prevent file leaks
+ journalWriter.write(DIRTY + ' ' + key + '\n');
+ journalWriter.flush();
+ return editor;
+ }
+
+ /** Returns the directory where this cache stores its data. */
+ public File getDirectory() {
+ return directory;
+ }
+
+ /**
+ * Returns the maximum number of bytes that this cache should use to store
+ * its data.
+ */
+ public long maxSize() {
+ return maxSize;
+ }
+
+ /**
+ * 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() {
+ return size;
+ }
+
+ private synchronized void completeEdit(Editor editor, boolean success) throws IOException {
+ Entry entry = editor.entry;
+ if (entry.currentEditor != editor) {
+ throw new IllegalStateException();
+ }
+
+ // if this edit is creating the entry for the first time, every index must have a value
+ if (success && !entry.readable) {
+ for (int i = 0; i < valueCount; i++) {
+ if (!editor.written[i]) {
+ editor.abort();
+ throw new IllegalStateException("Newly created entry didn't create value for index " + i);
+ }
+ if (!entry.getDirtyFile(i).exists()) {
+ editor.abort();
+ Platform.get().logW("DiskLruCache: Newly created entry doesn't have file for index " + i);
+ return;
+ }
+ }
+ }
+
+ for (int i = 0; i < valueCount; i++) {
+ File dirty = entry.getDirtyFile(i);
+ if (success) {
+ if (dirty.exists()) {
+ File clean = entry.getCleanFile(i);
+ dirty.renameTo(clean);
+ long oldLength = entry.lengths[i];
+ long newLength = clean.length();
+ entry.lengths[i] = newLength;
+ size = size - oldLength + newLength;
+ }
+ } else {
+ deleteIfExists(dirty);
+ }
+ }
+
+ redundantOpCount++;
+ entry.currentEditor = null;
+ if (entry.readable | success) {
+ entry.readable = true;
+ journalWriter.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n');
+ if (success) {
+ entry.sequenceNumber = nextSequenceNumber++;
+ }
+ } else {
+ lruEntries.remove(entry.key);
+ journalWriter.write(REMOVE + ' ' + entry.key + '\n');
+ }
+
+ if (size > maxSize || journalRebuildRequired()) {
+ executorService.submit(cleanupCallable);
+ }
+ }
+
+ /**
+ * 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;
+ return redundantOpCount >= redundantOpCompactThreshold && redundantOpCount >= lruEntries.size();
+ }
+
+ /**
+ * Drops the entry for {@code key} if it exists and can be removed. Entries
+ * actively being edited cannot be removed.
+ *
+ * @return true if an entry was removed.
+ */
+ public synchronized boolean remove(String key) throws IOException {
+ checkNotClosed();
+ validateKey(key);
+ Entry entry = lruEntries.get(key);
+ if (entry == null || entry.currentEditor != null) {
+ return false;
+ }
+
+ for (int i = 0; i < valueCount; i++) {
+ File file = entry.getCleanFile(i);
+ if (!file.delete()) {
+ throw new IOException("failed to delete " + file);
+ }
+ size -= entry.lengths[i];
+ entry.lengths[i] = 0;
+ }
+
+ redundantOpCount++;
+ journalWriter.append(REMOVE + ' ' + key + '\n');
+ lruEntries.remove(key);
+
+ if (journalRebuildRequired()) {
+ executorService.submit(cleanupCallable);
+ }
+
+ return true;
+ }
+
+ /** Returns true if this cache has been closed. */
+ public boolean isClosed() {
+ return journalWriter == null;
+ }
+
+ private void checkNotClosed() {
+ if (journalWriter == null) {
+ throw new IllegalStateException("cache is closed");
+ }
+ }
+
+ /** Force buffered operations to the filesystem. */
+ public synchronized void flush() throws IOException {
+ checkNotClosed();
+ trimToSize();
+ journalWriter.flush();
+ }
+
+ /** Closes this cache. Stored values will remain on the filesystem. */
+ public synchronized void close() throws IOException {
+ if (journalWriter == null) {
+ return; // already closed
+ }
+ for (Entry entry : new ArrayList<Entry>(lruEntries.values())) {
+ if (entry.currentEditor != null) {
+ entry.currentEditor.abort();
+ }
+ }
+ trimToSize();
+ journalWriter.close();
+ journalWriter = null;
+ }
+
+ private void trimToSize() throws IOException {
+ while (size > maxSize) {
+ Map.Entry<String, Entry> toEvict = lruEntries.entrySet().iterator().next();
+ remove(toEvict.getKey());
+ }
+ }
+
+ /**
+ * 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();
+ Util.deleteContents(directory);
+ }
+
+ private void validateKey(String key) {
+ if (key.contains(" ") || key.contains("\n") || key.contains("\r")) {
+ throw new IllegalArgumentException(
+ "keys must not contain spaces or newlines: \"" + key + "\"");
+ }
+ }
+
+ private static String inputStreamToString(InputStream in) throws IOException {
+ return Util.readFully(new InputStreamReader(in, UTF_8));
+ }
+
+ /** A snapshot of the values for an entry. */
+ public final class Snapshot implements Closeable {
+ private final String key;
+ private final long sequenceNumber;
+ private final InputStream[] ins;
+
+ private Snapshot(String key, long sequenceNumber, InputStream[] ins) {
+ this.key = key;
+ this.sequenceNumber = sequenceNumber;
+ this.ins = ins;
+ }
+
+ /**
+ * 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);
+ }
+
+ /** Returns the unbuffered stream with the value for {@code index}. */
+ public InputStream getInputStream(int index) {
+ return ins[index];
+ }
+
+ /** Returns the string value for {@code index}. */
+ public String getString(int index) throws IOException {
+ return inputStreamToString(getInputStream(index));
+ }
+
+ @Override public void close() {
+ for (InputStream in : ins) {
+ Util.closeQuietly(in);
+ }
+ }
+ }
+
+ /** Edits the values for an entry. */
+ public final class Editor {
+ private final Entry entry;
+ private final boolean[] written;
+ private boolean hasErrors;
+
+ private Editor(Entry entry) {
+ this.entry = entry;
+ this.written = (entry.readable) ? null : new boolean[valueCount];
+ }
+
+ /**
+ * Returns an unbuffered input stream to read the last committed value,
+ * or null if no value has been committed.
+ */
+ public InputStream newInputStream(int index) throws IOException {
+ synchronized (DiskLruCache.this) {
+ if (entry.currentEditor != this) {
+ throw new IllegalStateException();
+ }
+ if (!entry.readable) {
+ return null;
+ }
+ return new FileInputStream(entry.getCleanFile(index));
+ }
+ }
+
+ /**
+ * Returns the last committed value as a string, or null if no value
+ * has been committed.
+ */
+ public String getString(int index) throws IOException {
+ InputStream in = newInputStream(index);
+ return in != null ? inputStreamToString(in) : null;
+ }
+
+ /**
+ * 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 OutputStream newOutputStream(int index) throws IOException {
+ synchronized (DiskLruCache.this) {
+ if (entry.currentEditor != this) {
+ throw new IllegalStateException();
+ }
+ if (!entry.readable) {
+ written[index] = true;
+ }
+ return new FaultHidingOutputStream(new FileOutputStream(entry.getDirtyFile(index)));
+ }
+ }
+
+ /** Sets the value at {@code index} to {@code value}. */
+ public void set(int index, String value) throws IOException {
+ Writer writer = null;
+ try {
+ writer = new OutputStreamWriter(newOutputStream(index), UTF_8);
+ writer.write(value);
+ } finally {
+ Util.closeQuietly(writer);
+ }
+ }
+
+ /**
+ * 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 {
+ if (hasErrors) {
+ completeEdit(this, false);
+ remove(entry.key); // the previous entry is stale
+ } else {
+ completeEdit(this, true);
+ }
+ }
+
+ /**
+ * Aborts this edit. This releases the edit lock so another edit may be
+ * started on the same key.
+ */
+ public void abort() throws IOException {
+ completeEdit(this, false);
+ }
+
+ private final class FaultHidingOutputStream extends FilterOutputStream {
+ private FaultHidingOutputStream(OutputStream out) {
+ super(out);
+ }
+
+ @Override public void write(int oneByte) {
+ try {
+ out.write(oneByte);
+ } catch (IOException e) {
+ hasErrors = true;
+ }
+ }
+
+ @Override public void write(byte[] buffer, int offset, int length) {
+ try {
+ out.write(buffer, offset, length);
+ } catch (IOException e) {
+ hasErrors = true;
+ }
+ }
+
+ @Override public void close() {
+ try {
+ out.close();
+ } catch (IOException e) {
+ hasErrors = true;
+ }
+ }
+
+ @Override public void flush() {
+ try {
+ out.flush();
+ } catch (IOException e) {
+ hasErrors = true;
+ }
+ }
+ }
+ }
+
+ private final class Entry {
+ private final String key;
+
+ /** Lengths of this entry's files. */
+ private final long[] lengths;
+
+ /** True if this entry has ever been published. */
+ private boolean readable;
+
+ /** The ongoing edit or null if this entry is not being edited. */
+ private Editor currentEditor;
+
+ /** The sequence number of the most recently committed edit to this entry. */
+ private long sequenceNumber;
+
+ private Entry(String key) {
+ this.key = key;
+ this.lengths = new long[valueCount];
+ }
+
+ public String getLengths() throws IOException {
+ StringBuilder result = new StringBuilder();
+ for (long size : lengths) {
+ result.append(' ').append(size);
+ }
+ return result.toString();
+ }
+
+ /** Set lengths using decimal numbers like "10123". */
+ private void setLengths(String[] strings) throws IOException {
+ if (strings.length != valueCount) {
+ throw invalidLengths(strings);
+ }
+
+ try {
+ for (int i = 0; i < strings.length; i++) {
+ lengths[i] = Long.parseLong(strings[i]);
+ }
+ } catch (NumberFormatException e) {
+ throw invalidLengths(strings);
+ }
+ }
+
+ private IOException invalidLengths(String[] strings) throws IOException {
+ throw new IOException("unexpected journal line: " + Arrays.toString(strings));
+ }
+
+ public File getCleanFile(int i) {
+ return new File(directory, key + "." + i);
+ }
+
+ public File getDirtyFile(int i) {
+ return new File(directory, key + "." + i + ".tmp");
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/553a25ce/framework/src/com/squareup/okhttp/internal/Dns.java
----------------------------------------------------------------------
diff --git a/framework/src/com/squareup/okhttp/internal/Dns.java b/framework/src/com/squareup/okhttp/internal/Dns.java
new file mode 100644
index 0000000..69b2d37
--- /dev/null
+++ b/framework/src/com/squareup/okhttp/internal/Dns.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2012 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.squareup.okhttp.internal;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+
+/**
+ * Domain name service. Prefer this over {@link InetAddress#getAllByName} to
+ * make code more testable.
+ */
+public interface Dns {
+ Dns DEFAULT = new Dns() {
+ @Override public InetAddress[] getAllByName(String host) throws UnknownHostException {
+ return InetAddress.getAllByName(host);
+ }
+ };
+
+ InetAddress[] getAllByName(String host) throws UnknownHostException;
+}
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/553a25ce/framework/src/com/squareup/okhttp/internal/NamedRunnable.java
----------------------------------------------------------------------
diff --git a/framework/src/com/squareup/okhttp/internal/NamedRunnable.java b/framework/src/com/squareup/okhttp/internal/NamedRunnable.java
new file mode 100644
index 0000000..ce430b2
--- /dev/null
+++ b/framework/src/com/squareup/okhttp/internal/NamedRunnable.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2013 Square, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.squareup.okhttp.internal;
+
+/**
+ * Runnable implementation which always sets its thread name.
+ */
+public abstract class NamedRunnable implements Runnable {
+ private String name;
+
+ public NamedRunnable(String name) {
+ this.name = name;
+ }
+
+ @Override public final void run() {
+ String oldName = Thread.currentThread().getName();
+ Thread.currentThread().setName(name);
+ try {
+ execute();
+ } finally {
+ Thread.currentThread().setName(oldName);
+ }
+ }
+
+ protected abstract void execute();
+}