You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cordova.apache.org by ag...@apache.org on 2014/12/31 05:01:15 UTC
[12/12] android commit: CB-6630 Delete bundled (and outdated) copy of
OkHttp
CB-6630 Delete bundled (and outdated) copy of OkHttp
Those that want to use OkHttp can use a plugin.
Project: http://git-wip-us.apache.org/repos/asf/cordova-android/repo
Commit: http://git-wip-us.apache.org/repos/asf/cordova-android/commit/c6b171ba
Tree: http://git-wip-us.apache.org/repos/asf/cordova-android/tree/c6b171ba
Diff: http://git-wip-us.apache.org/repos/asf/cordova-android/diff/c6b171ba
Branch: refs/heads/4.0.x
Commit: c6b171ba950f7ffb2a64dc4470a454da9b5c09ec
Parents: 5a17d6c
Author: Andrew Grieve <ag...@chromium.org>
Authored: Tue Dec 30 22:44:47 2014 -0500
Committer: Andrew Grieve <ag...@chromium.org>
Committed: Tue Dec 30 23:00:18 2014 -0500
----------------------------------------------------------------------
NOTICE | 2 -
framework/src/com/squareup/okhttp/Address.java | 140 ---
.../src/com/squareup/okhttp/Connection.java | 335 -------
.../src/com/squareup/okhttp/ConnectionPool.java | 274 ------
.../src/com/squareup/okhttp/Dispatcher.java | 86 --
framework/src/com/squareup/okhttp/Failure.java | 59 --
.../com/squareup/okhttp/HttpResponseCache.java | 722 ---------------
framework/src/com/squareup/okhttp/Job.java | 232 -----
.../src/com/squareup/okhttp/MediaType.java | 120 ---
.../com/squareup/okhttp/OkAuthenticator.java | 123 ---
.../src/com/squareup/okhttp/OkHttpClient.java | 408 --------
.../com/squareup/okhttp/OkResponseCache.java | 56 --
framework/src/com/squareup/okhttp/Request.java | 284 ------
framework/src/com/squareup/okhttp/Response.java | 290 ------
.../src/com/squareup/okhttp/ResponseSource.java | 37 -
framework/src/com/squareup/okhttp/Route.java | 91 --
.../src/com/squareup/okhttp/RouteDatabase.java | 57 --
.../src/com/squareup/okhttp/TunnelRequest.java | 75 --
.../okhttp/internal/AbstractOutputStream.java | 45 -
.../com/squareup/okhttp/internal/Base64.java | 164 ----
.../squareup/okhttp/internal/DiskLruCache.java | 926 -------------------
.../src/com/squareup/okhttp/internal/Dns.java | 33 -
.../internal/FaultRecoveringOutputStream.java | 163 ----
.../squareup/okhttp/internal/NamedRunnable.java | 40 -
.../com/squareup/okhttp/internal/Platform.java | 370 --------
.../okhttp/internal/StrictLineReader.java | 207 -----
.../src/com/squareup/okhttp/internal/Util.java | 394 --------
.../internal/http/AbstractHttpInputStream.java | 107 ---
.../okhttp/internal/http/HeaderParser.java | 112 ---
.../okhttp/internal/http/HttpAuthenticator.java | 166 ----
.../squareup/okhttp/internal/http/HttpDate.java | 88 --
.../okhttp/internal/http/HttpEngine.java | 686 --------------
.../okhttp/internal/http/HttpTransport.java | 497 ----------
.../internal/http/HttpURLConnectionImpl.java | 590 ------------
.../okhttp/internal/http/HttpsEngine.java | 72 --
.../internal/http/HttpsURLConnectionImpl.java | 366 --------
.../internal/http/OkResponseCacheAdapter.java | 57 --
.../squareup/okhttp/internal/http/Policy.java | 49 -
.../okhttp/internal/http/RawHeaders.java | 447 ---------
.../okhttp/internal/http/RequestHeaders.java | 317 -------
.../okhttp/internal/http/ResponseHeaders.java | 512 ----------
.../internal/http/RetryableOutputStream.java | 75 --
.../okhttp/internal/http/RouteSelector.java | 269 ------
.../okhttp/internal/http/SpdyTransport.java | 103 ---
.../okhttp/internal/http/Transport.java | 64 --
.../http/UnknownLengthHttpInputStream.java | 63 --
.../okhttp/internal/spdy/ErrorCode.java | 83 --
.../okhttp/internal/spdy/FrameReader.java | 55 --
.../okhttp/internal/spdy/FrameWriter.java | 43 -
.../okhttp/internal/spdy/HeadersMode.java | 49 -
.../squareup/okhttp/internal/spdy/Hpack.java | 387 --------
.../okhttp/internal/spdy/Http20Draft06.java | 385 --------
.../internal/spdy/IncomingStreamHandler.java | 36 -
.../internal/spdy/NameValueBlockReader.java | 139 ---
.../com/squareup/okhttp/internal/spdy/Ping.java | 71 --
.../squareup/okhttp/internal/spdy/Settings.java | 187 ----
.../squareup/okhttp/internal/spdy/Spdy3.java | 463 ----------
.../okhttp/internal/spdy/SpdyConnection.java | 599 ------------
.../okhttp/internal/spdy/SpdyStream.java | 684 --------------
.../squareup/okhttp/internal/spdy/Variant.java | 37 -
.../internal/tls/DistinguishedNameParser.java | 407 --------
.../okhttp/internal/tls/OkHostnameVerifier.java | 194 ----
.../org/apache/cordova/CordovaResourceApi.java | 20 +-
63 files changed, 6 insertions(+), 14206 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/c6b171ba/NOTICE
----------------------------------------------------------------------
diff --git a/NOTICE b/NOTICE
index 40c5e74..24a20f7 100644
--- a/NOTICE
+++ b/NOTICE
@@ -13,5 +13,3 @@ The Apache Software Foundation (http://www.apache.org)
This product includes software developed as part of
The Android Open Source Project (http://source.android.com).
-This software includes software developed at Square, Inc.
-Copyright (C) 2013 Square, Inc.
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/c6b171ba/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
deleted file mode 100755
index b34bd91..0000000
--- a/framework/src/com/squareup/okhttp/Address.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * 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.Util;
-import java.net.Proxy;
-import java.net.UnknownHostException;
-import java.util.List;
-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;
- final OkAuthenticator authenticator;
- final List<String> transports;
-
- public Address(String uriHost, int uriPort, SSLSocketFactory sslSocketFactory,
- HostnameVerifier hostnameVerifier, OkAuthenticator authenticator, Proxy proxy,
- List<String> transports) throws UnknownHostException {
- if (uriHost == null) throw new NullPointerException("uriHost == null");
- if (uriPort <= 0) throw new IllegalArgumentException("uriPort <= 0: " + uriPort);
- if (authenticator == null) throw new IllegalArgumentException("authenticator == null");
- if (transports == null) throw new IllegalArgumentException("transports == null");
- this.proxy = proxy;
- this.uriHost = uriHost;
- this.uriPort = uriPort;
- this.sslSocketFactory = sslSocketFactory;
- this.hostnameVerifier = hostnameVerifier;
- this.authenticator = authenticator;
- this.transports = Util.immutableList(transports);
- }
-
- /** 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 the client's authenticator. This method never returns null.
- */
- public OkAuthenticator getAuthenticator() {
- return authenticator;
- }
-
- /**
- * Returns the client's transports. This method always returns a non-null list
- * that contains "http/1.1", possibly among other transports.
- */
- public List<String> getTransports() {
- return transports;
- }
-
- /**
- * 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)
- && equal(this.authenticator, that.authenticator)
- && equal(this.transports, that.transports);
- }
- 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 + (authenticator != null ? authenticator.hashCode() : 0);
- result = 31 * result + (proxy != null ? proxy.hashCode() : 0);
- result = 31 * result + transports.hashCode();
- return result;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/c6b171ba/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
deleted file mode 100755
index 6bb9cb3..0000000
--- a/framework/src/com/squareup/okhttp/Connection.java
+++ /dev/null
@@ -1,335 +0,0 @@
-/*
- * 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.BufferedOutputStream;
-import java.io.Closeable;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.Proxy;
-import java.net.Socket;
-import java.net.SocketTimeoutException;
-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 Route route;
-
- 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(Route route) {
- this.route = route;
- }
-
- public void connect(int connectTimeout, int readTimeout, TunnelRequest tunnelRequest)
- throws IOException {
- if (connected) throw new IllegalStateException("already connected");
-
- socket = (route.proxy.type() != Proxy.Type.HTTP) ? new Socket(route.proxy) : new Socket();
- Platform.get().connectSocket(socket, route.inetSocketAddress, connectTimeout);
- socket.setSoTimeout(readTimeout);
- in = socket.getInputStream();
- out = socket.getOutputStream();
-
- if (route.address.sslSocketFactory != null) {
- upgradeToTls(tunnelRequest);
- } else {
- streamWrapper();
- }
- connected = true;
- }
-
- /**
- * 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 = route.address.sslSocketFactory
- .createSocket(socket, route.address.uriHost, route.address.uriPort, true /* autoClose */);
- SSLSocket sslSocket = (SSLSocket) socket;
- if (route.modernTls) {
- platform.enableTlsExtensions(sslSocket, route.address.uriHost);
- } else {
- platform.supportTlsIntolerantServer(sslSocket);
- }
-
- boolean useNpn = route.modernTls && route.address.transports.contains("spdy/3");
- if (useNpn) {
- 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 (!route.address.hostnameVerifier.verify(route.address.uriHost, sslSocket.getSession())) {
- throw new IOException("Hostname '" + route.address.uriHost + "' was not verified");
- }
-
- out = sslSocket.getOutputStream();
- in = sslSocket.getInputStream();
- streamWrapper();
-
- byte[] selectedProtocol;
- if (useNpn && (selectedProtocol = platform.getNpnSelectedProtocol(sslSocket)) != null) {
- if (Arrays.equals(selectedProtocol, SPDY3)) {
- sslSocket.setSoTimeout(0); // SPDY timeouts are set per-stream.
- spdyConnection = new SpdyConnection.Builder(route.address.getUriHost(), true, in, out)
- .build();
- spdyConnection.sendConnectionHeader();
- } 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 route used by this connection. */
- public Route getRoute() {
- return route;
- }
-
- /**
- * 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();
- }
-
- /**
- * Returns true if we are confident that we can read data from this
- * connection. This is more expensive and more accurate than {@link
- * #isAlive()}; callers should check {@link #isAlive()} first.
- */
- public boolean isReadable() {
- if (!(in instanceof BufferedInputStream)) {
- return true; // Optimistic.
- }
- if (isSpdy()) {
- return true; // Optimistic. We can't test SPDY because its streams are in use.
- }
- BufferedInputStream bufferedInputStream = (BufferedInputStream) in;
- try {
- int readTimeout = socket.getSoTimeout();
- try {
- socket.setSoTimeout(1);
- bufferedInputStream.mark(1);
- if (bufferedInputStream.read() == -1) {
- return false; // Stream is exhausted; socket is closed.
- }
- bufferedInputStream.reset();
- return true;
- } finally {
- socket.setSoTimeout(readTimeout);
- }
- } catch (SocketTimeoutException ignored) {
- return true; // Read timed out; socket is good.
- } catch (IOException e) {
- return false; // Couldn't read; socket is closed.
- }
- }
-
- 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 getIdleStartTimeNs() < System.nanoTime() - 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 route.address.sslSocketFactory != null && route.proxy.type() == Proxy.Type.HTTP;
- }
-
- public void updateReadTimeout(int newTimeout) throws IOException {
- if (!connected) throw new IllegalStateException("updateReadTimeout - not connected");
- socket.setSoTimeout(newTimeout);
- }
-
- /**
- * 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(
- route.address.authenticator, HTTP_PROXY_AUTH, responseHeaders, requestHeaders,
- route.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());
- }
- }
- }
-
- private void streamWrapper() throws IOException {
- in = new BufferedInputStream(in, 4096);
- out = new BufferedOutputStream(out, 256);
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/c6b171ba/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
deleted file mode 100755
index 42b70b9..0000000
--- a/framework/src/com/squareup/okhttp/ConnectionPool.java
+++ /dev/null
@@ -1,274 +0,0 @@
-/*
- * 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.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>(),
- Util.daemonThreadFactory("OkHttp ConnectionPool"));
- 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.getRoute().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) {
- 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();
- }
-
- executorService.submit(connectionsCleanupCallable);
- }
-
- /**
- * 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/c6b171ba/framework/src/com/squareup/okhttp/Dispatcher.java
----------------------------------------------------------------------
diff --git a/framework/src/com/squareup/okhttp/Dispatcher.java b/framework/src/com/squareup/okhttp/Dispatcher.java
deleted file mode 100755
index 1982a8a..0000000
--- a/framework/src/com/squareup/okhttp/Dispatcher.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * 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;
-
-import com.squareup.okhttp.internal.http.ResponseHeaders;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.ThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-
-final class Dispatcher {
- // TODO: thread pool size should be configurable; possibly configurable per host.
- private final ThreadPoolExecutor executorService = new ThreadPoolExecutor(
- 8, 8, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
- private final Map<Object, List<Job>> enqueuedJobs = new LinkedHashMap<Object, List<Job>>();
-
- public synchronized void enqueue(
- OkHttpClient client, Request request, Response.Receiver responseReceiver) {
- Job job = new Job(this, client, request, responseReceiver);
- List<Job> jobsForTag = enqueuedJobs.get(request.tag());
- if (jobsForTag == null) {
- jobsForTag = new ArrayList<Job>(2);
- enqueuedJobs.put(request.tag(), jobsForTag);
- }
- jobsForTag.add(job);
- executorService.execute(job);
- }
-
- public synchronized void cancel(Object tag) {
- List<Job> jobs = enqueuedJobs.remove(tag);
- if (jobs == null) return;
- for (Job job : jobs) {
- executorService.remove(job);
- }
- }
-
- synchronized void finished(Job job) {
- List<Job> jobs = enqueuedJobs.get(job.tag());
- if (jobs != null) jobs.remove(job);
- }
-
- static class RealResponseBody extends Response.Body {
- private final ResponseHeaders responseHeaders;
- private final InputStream in;
-
- RealResponseBody(ResponseHeaders responseHeaders, InputStream in) {
- this.responseHeaders = responseHeaders;
- this.in = in;
- }
-
- @Override public boolean ready() throws IOException {
- return true;
- }
-
- @Override public MediaType contentType() {
- String contentType = responseHeaders.getContentType();
- return contentType != null ? MediaType.parse(contentType) : null;
- }
-
- @Override public long contentLength() {
- return responseHeaders.getContentLength();
- }
-
- @Override public InputStream byteStream() throws IOException {
- return in;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/c6b171ba/framework/src/com/squareup/okhttp/Failure.java
----------------------------------------------------------------------
diff --git a/framework/src/com/squareup/okhttp/Failure.java b/framework/src/com/squareup/okhttp/Failure.java
deleted file mode 100755
index a354700..0000000
--- a/framework/src/com/squareup/okhttp/Failure.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * 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;
-
-/**
- * A failure attempting to retrieve an HTTP response.
- *
- * <h3>Warning: Experimental OkHttp 2.0 API</h3>
- * This class is in beta. APIs are subject to change!
- */
-/* OkHttp 2.0: public */ class Failure {
- private final Request request;
- private final Throwable exception;
-
- private Failure(Builder builder) {
- this.request = builder.request;
- this.exception = builder.exception;
- }
-
- public Request request() {
- return request;
- }
-
- public Throwable exception() {
- return exception;
- }
-
- public static class Builder {
- private Request request;
- private Throwable exception;
-
- public Builder request(Request request) {
- this.request = request;
- return this;
- }
-
- public Builder exception(Throwable exception) {
- this.exception = exception;
- return this;
- }
-
- public Failure build() {
- return new Failure(this);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/c6b171ba/framework/src/com/squareup/okhttp/HttpResponseCache.java
----------------------------------------------------------------------
diff --git a/framework/src/com/squareup/okhttp/HttpResponseCache.java b/framework/src/com/squareup/okhttp/HttpResponseCache.java
deleted file mode 100755
index 8210318..0000000
--- a/framework/src/com/squareup/okhttp/HttpResponseCache.java
+++ /dev/null
@@ -1,722 +0,0 @@
-/*
- * Copyright (C) 2010 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.Base64;
-import com.squareup.okhttp.internal.DiskLruCache;
-import com.squareup.okhttp.internal.StrictLineReader;
-import com.squareup.okhttp.internal.Util;
-import com.squareup.okhttp.internal.http.HttpEngine;
-import com.squareup.okhttp.internal.http.HttpURLConnectionImpl;
-import com.squareup.okhttp.internal.http.HttpsEngine;
-import com.squareup.okhttp.internal.http.HttpsURLConnectionImpl;
-import com.squareup.okhttp.internal.http.RawHeaders;
-import com.squareup.okhttp.internal.http.ResponseHeaders;
-import java.io.BufferedWriter;
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FilterInputStream;
-import java.io.FilterOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.Writer;
-import java.net.CacheRequest;
-import java.net.CacheResponse;
-import java.net.HttpURLConnection;
-import java.net.ResponseCache;
-import java.net.SecureCacheResponse;
-import java.net.URI;
-import java.net.URLConnection;
-import java.security.Principal;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateEncodingException;
-import java.security.cert.CertificateException;
-import java.security.cert.CertificateFactory;
-import java.security.cert.X509Certificate;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import javax.net.ssl.SSLPeerUnverifiedException;
-import javax.net.ssl.SSLSocket;
-
-import static com.squareup.okhttp.internal.Util.US_ASCII;
-import static com.squareup.okhttp.internal.Util.UTF_8;
-
-/**
- * Caches HTTP and HTTPS responses to the filesystem so they may be reused,
- * saving time and bandwidth.
- *
- * <h3>Cache Optimization</h3>
- * To measure cache effectiveness, this class tracks three statistics:
- * <ul>
- * <li><strong>{@link #getRequestCount() Request Count:}</strong> the number
- * of HTTP requests issued since this cache was created.
- * <li><strong>{@link #getNetworkCount() Network Count:}</strong> the
- * number of those requests that required network use.
- * <li><strong>{@link #getHitCount() Hit Count:}</strong> the number of
- * those requests whose responses were served by the cache.
- * </ul>
- * Sometimes a request will result in a conditional cache hit. If the cache
- * contains a stale copy of the response, the client will issue a conditional
- * {@code GET}. The server will then send either the updated response if it has
- * changed, or a short 'not modified' response if the client's copy is still
- * valid. Such responses increment both the network count and hit count.
- *
- * <p>The best way to improve the cache hit rate is by configuring the web
- * server to return cacheable responses. Although this client honors all <a
- * href="http://www.ietf.org/rfc/rfc2616.txt">HTTP/1.1 (RFC 2068)</a> cache
- * headers, it doesn't cache partial responses.
- *
- * <h3>Force a Network Response</h3>
- * In some situations, such as after a user clicks a 'refresh' button, it may be
- * necessary to skip the cache, and fetch data directly from the server. To force
- * a full refresh, add the {@code no-cache} directive: <pre> {@code
- * connection.addRequestProperty("Cache-Control", "no-cache");
- * }</pre>
- * If it is only necessary to force a cached response to be validated by the
- * server, use the more efficient {@code max-age=0} instead: <pre> {@code
- * connection.addRequestProperty("Cache-Control", "max-age=0");
- * }</pre>
- *
- * <h3>Force a Cache Response</h3>
- * Sometimes you'll want to show resources if they are available immediately,
- * but not otherwise. This can be used so your application can show
- * <i>something</i> while waiting for the latest data to be downloaded. To
- * restrict a request to locally-cached resources, add the {@code
- * only-if-cached} directive: <pre> {@code
- * try {
- * connection.addRequestProperty("Cache-Control", "only-if-cached");
- * InputStream cached = connection.getInputStream();
- * // the resource was cached! show it
- * } catch (FileNotFoundException e) {
- * // the resource was not cached
- * }
- * }</pre>
- * This technique works even better in situations where a stale response is
- * better than no response. To permit stale cached responses, use the {@code
- * max-stale} directive with the maximum staleness in seconds: <pre> {@code
- * int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
- * connection.addRequestProperty("Cache-Control", "max-stale=" + maxStale);
- * }</pre>
- */
-public final class HttpResponseCache extends ResponseCache {
- // TODO: add APIs to iterate the cache?
- private static final int VERSION = 201105;
- private static final int ENTRY_METADATA = 0;
- private static final int ENTRY_BODY = 1;
- private static final int ENTRY_COUNT = 2;
-
- private final DiskLruCache cache;
-
- /* read and write statistics, all guarded by 'this' */
- private int writeSuccessCount;
- private int writeAbortCount;
- private int networkCount;
- private int hitCount;
- private int requestCount;
-
- /**
- * Although this class only exposes the limited ResponseCache API, it
- * implements the full OkResponseCache interface. This field is used as a
- * package private handle to the complete implementation. It delegates to
- * public and private members of this type.
- */
- final OkResponseCache okResponseCache = new OkResponseCache() {
- @Override public CacheResponse get(URI uri, String requestMethod,
- Map<String, List<String>> requestHeaders) throws IOException {
- return HttpResponseCache.this.get(uri, requestMethod, requestHeaders);
- }
-
- @Override public CacheRequest put(URI uri, URLConnection connection) throws IOException {
- return HttpResponseCache.this.put(uri, connection);
- }
-
- @Override public void maybeRemove(String requestMethod, URI uri) throws IOException {
- HttpResponseCache.this.maybeRemove(requestMethod, uri);
- }
-
- @Override public void update(
- CacheResponse conditionalCacheHit, HttpURLConnection connection) throws IOException {
- HttpResponseCache.this.update(conditionalCacheHit, connection);
- }
-
- @Override public void trackConditionalCacheHit() {
- HttpResponseCache.this.trackConditionalCacheHit();
- }
-
- @Override public void trackResponse(ResponseSource source) {
- HttpResponseCache.this.trackResponse(source);
- }
- };
-
- public HttpResponseCache(File directory, long maxSize) throws IOException {
- cache = DiskLruCache.open(directory, VERSION, ENTRY_COUNT, maxSize);
- }
-
- private String uriToKey(URI uri) {
- return Util.hash(uri.toString());
- }
-
- @Override public CacheResponse get(URI uri, String requestMethod,
- Map<String, List<String>> requestHeaders) {
- String key = uriToKey(uri);
- DiskLruCache.Snapshot snapshot;
- Entry entry;
- try {
- snapshot = cache.get(key);
- if (snapshot == null) {
- return null;
- }
- entry = new Entry(snapshot.getInputStream(ENTRY_METADATA));
- } catch (IOException e) {
- // Give up because the cache cannot be read.
- return null;
- }
-
- if (!entry.matches(uri, requestMethod, requestHeaders)) {
- snapshot.close();
- return null;
- }
-
- return entry.isHttps() ? new EntrySecureCacheResponse(entry, snapshot)
- : new EntryCacheResponse(entry, snapshot);
- }
-
- @Override public CacheRequest put(URI uri, URLConnection urlConnection) throws IOException {
- if (!(urlConnection instanceof HttpURLConnection)) {
- return null;
- }
-
- HttpURLConnection httpConnection = (HttpURLConnection) urlConnection;
- String requestMethod = httpConnection.getRequestMethod();
-
- if (maybeRemove(requestMethod, uri)) {
- return null;
- }
- if (!requestMethod.equals("GET")) {
- // Don't cache non-GET responses. We're technically allowed to cache
- // HEAD requests and some POST requests, but the complexity of doing
- // so is high and the benefit is low.
- return null;
- }
-
- HttpEngine httpEngine = getHttpEngine(httpConnection);
- if (httpEngine == null) {
- // Don't cache unless the HTTP implementation is ours.
- return null;
- }
-
- ResponseHeaders response = httpEngine.getResponseHeaders();
- if (response.hasVaryAll()) {
- return null;
- }
-
- RawHeaders varyHeaders =
- httpEngine.getRequestHeaders().getHeaders().getAll(response.getVaryFields());
- Entry entry = new Entry(uri, varyHeaders, httpConnection);
- DiskLruCache.Editor editor = null;
- try {
- editor = cache.edit(uriToKey(uri));
- if (editor == null) {
- return null;
- }
- entry.writeTo(editor);
- return new CacheRequestImpl(editor);
- } catch (IOException e) {
- abortQuietly(editor);
- return null;
- }
- }
-
- /**
- * Returns true if the supplied {@code requestMethod} potentially invalidates an entry in the
- * cache.
- */
- private boolean maybeRemove(String requestMethod, URI uri) {
- if (requestMethod.equals("POST") || requestMethod.equals("PUT") || requestMethod.equals(
- "DELETE")) {
- try {
- cache.remove(uriToKey(uri));
- } catch (IOException ignored) {
- // The cache cannot be written.
- }
- return true;
- }
- return false;
- }
-
- private void update(CacheResponse conditionalCacheHit, HttpURLConnection httpConnection)
- throws IOException {
- HttpEngine httpEngine = getHttpEngine(httpConnection);
- URI uri = httpEngine.getUri();
- ResponseHeaders response = httpEngine.getResponseHeaders();
- RawHeaders varyHeaders =
- httpEngine.getRequestHeaders().getHeaders().getAll(response.getVaryFields());
- Entry entry = new Entry(uri, varyHeaders, httpConnection);
- DiskLruCache.Snapshot snapshot = (conditionalCacheHit instanceof EntryCacheResponse)
- ? ((EntryCacheResponse) conditionalCacheHit).snapshot
- : ((EntrySecureCacheResponse) conditionalCacheHit).snapshot;
- DiskLruCache.Editor editor = null;
- try {
- editor = snapshot.edit(); // returns null if snapshot is not current
- if (editor != null) {
- entry.writeTo(editor);
- editor.commit();
- }
- } catch (IOException e) {
- abortQuietly(editor);
- }
- }
-
- private void abortQuietly(DiskLruCache.Editor editor) {
- // Give up because the cache cannot be written.
- try {
- if (editor != null) {
- editor.abort();
- }
- } catch (IOException ignored) {
- }
- }
-
- private HttpEngine getHttpEngine(URLConnection httpConnection) {
- if (httpConnection instanceof HttpURLConnectionImpl) {
- return ((HttpURLConnectionImpl) httpConnection).getHttpEngine();
- } else if (httpConnection instanceof HttpsURLConnectionImpl) {
- return ((HttpsURLConnectionImpl) httpConnection).getHttpEngine();
- } else {
- return null;
- }
- }
-
- /**
- * Closes the cache and deletes all of its stored values. This will delete
- * all files in the cache directory including files that weren't created by
- * the cache.
- */
- public void delete() throws IOException {
- cache.delete();
- }
-
- public synchronized int getWriteAbortCount() {
- return writeAbortCount;
- }
-
- public synchronized int getWriteSuccessCount() {
- return writeSuccessCount;
- }
-
- public long getSize() {
- return cache.size();
- }
-
- public long getMaxSize() {
- return cache.getMaxSize();
- }
-
- public void flush() throws IOException {
- cache.flush();
- }
-
- public void close() throws IOException {
- cache.close();
- }
-
- public File getDirectory() {
- return cache.getDirectory();
- }
-
- public boolean isClosed() {
- return cache.isClosed();
- }
-
- private synchronized void trackResponse(ResponseSource source) {
- requestCount++;
-
- switch (source) {
- case CACHE:
- hitCount++;
- break;
- case CONDITIONAL_CACHE:
- case NETWORK:
- networkCount++;
- break;
- }
- }
-
- private synchronized void trackConditionalCacheHit() {
- hitCount++;
- }
-
- public synchronized int getNetworkCount() {
- return networkCount;
- }
-
- public synchronized int getHitCount() {
- return hitCount;
- }
-
- public synchronized int getRequestCount() {
- return requestCount;
- }
-
- private final class CacheRequestImpl extends CacheRequest {
- private final DiskLruCache.Editor editor;
- private OutputStream cacheOut;
- private boolean done;
- private OutputStream body;
-
- public CacheRequestImpl(final DiskLruCache.Editor editor) throws IOException {
- this.editor = editor;
- this.cacheOut = editor.newOutputStream(ENTRY_BODY);
- this.body = new FilterOutputStream(cacheOut) {
- @Override public void close() throws IOException {
- synchronized (HttpResponseCache.this) {
- if (done) {
- return;
- }
- done = true;
- writeSuccessCount++;
- }
- super.close();
- editor.commit();
- }
-
- @Override public void write(byte[] buffer, int offset, int length) throws IOException {
- // Since we don't override "write(int oneByte)", we can write directly to "out"
- // and avoid the inefficient implementation from the FilterOutputStream.
- out.write(buffer, offset, length);
- }
- };
- }
-
- @Override public void abort() {
- synchronized (HttpResponseCache.this) {
- if (done) {
- return;
- }
- done = true;
- writeAbortCount++;
- }
- Util.closeQuietly(cacheOut);
- try {
- editor.abort();
- } catch (IOException ignored) {
- }
- }
-
- @Override public OutputStream getBody() throws IOException {
- return body;
- }
- }
-
- private static final class Entry {
- private final String uri;
- private final RawHeaders varyHeaders;
- private final String requestMethod;
- private final RawHeaders responseHeaders;
- private final String cipherSuite;
- private final Certificate[] peerCertificates;
- private final Certificate[] localCertificates;
-
- /**
- * Reads an entry from an input stream. A typical entry looks like this:
- * <pre>{@code
- * http://google.com/foo
- * GET
- * 2
- * Accept-Language: fr-CA
- * Accept-Charset: UTF-8
- * HTTP/1.1 200 OK
- * 3
- * Content-Type: image/png
- * Content-Length: 100
- * Cache-Control: max-age=600
- * }</pre>
- *
- * <p>A typical HTTPS file looks like this:
- * <pre>{@code
- * https://google.com/foo
- * GET
- * 2
- * Accept-Language: fr-CA
- * Accept-Charset: UTF-8
- * HTTP/1.1 200 OK
- * 3
- * Content-Type: image/png
- * Content-Length: 100
- * Cache-Control: max-age=600
- *
- * AES_256_WITH_MD5
- * 2
- * base64-encoded peerCertificate[0]
- * base64-encoded peerCertificate[1]
- * -1
- * }</pre>
- * The file is newline separated. The first two lines are the URL and
- * the request method. Next is the number of HTTP Vary request header
- * lines, followed by those lines.
- *
- * <p>Next is the response status line, followed by the number of HTTP
- * response header lines, followed by those lines.
- *
- * <p>HTTPS responses also contain SSL session information. This begins
- * with a blank line, and then a line containing the cipher suite. Next
- * is the length of the peer certificate chain. These certificates are
- * base64-encoded and appear each on their own line. The next line
- * contains the length of the local certificate chain. These
- * certificates are also base64-encoded and appear each on their own
- * line. A length of -1 is used to encode a null array.
- */
- public Entry(InputStream in) throws IOException {
- try {
- StrictLineReader reader = new StrictLineReader(in, US_ASCII);
- uri = reader.readLine();
- requestMethod = reader.readLine();
- varyHeaders = new RawHeaders();
- int varyRequestHeaderLineCount = reader.readInt();
- for (int i = 0; i < varyRequestHeaderLineCount; i++) {
- varyHeaders.addLine(reader.readLine());
- }
-
- responseHeaders = new RawHeaders();
- responseHeaders.setStatusLine(reader.readLine());
- int responseHeaderLineCount = reader.readInt();
- for (int i = 0; i < responseHeaderLineCount; i++) {
- responseHeaders.addLine(reader.readLine());
- }
-
- if (isHttps()) {
- String blank = reader.readLine();
- if (blank.length() > 0) {
- throw new IOException("expected \"\" but was \"" + blank + "\"");
- }
- cipherSuite = reader.readLine();
- peerCertificates = readCertArray(reader);
- localCertificates = readCertArray(reader);
- } else {
- cipherSuite = null;
- peerCertificates = null;
- localCertificates = null;
- }
- } finally {
- in.close();
- }
- }
-
- public Entry(URI uri, RawHeaders varyHeaders, HttpURLConnection httpConnection)
- throws IOException {
- this.uri = uri.toString();
- this.varyHeaders = varyHeaders;
- this.requestMethod = httpConnection.getRequestMethod();
- this.responseHeaders = RawHeaders.fromMultimap(httpConnection.getHeaderFields(), true);
-
- SSLSocket sslSocket = getSslSocket(httpConnection);
- if (sslSocket != null) {
- cipherSuite = sslSocket.getSession().getCipherSuite();
- Certificate[] peerCertificatesNonFinal = null;
- try {
- peerCertificatesNonFinal = sslSocket.getSession().getPeerCertificates();
- } catch (SSLPeerUnverifiedException ignored) {
- }
- peerCertificates = peerCertificatesNonFinal;
- localCertificates = sslSocket.getSession().getLocalCertificates();
- } else {
- cipherSuite = null;
- peerCertificates = null;
- localCertificates = null;
- }
- }
-
- /**
- * Returns the SSL socket used by {@code httpConnection} for HTTPS, nor null
- * if the connection isn't using HTTPS. Since we permit redirects across
- * protocols (HTTP to HTTPS or vice versa), the implementation type of the
- * connection doesn't necessarily match the implementation type of its HTTP
- * engine.
- */
- private SSLSocket getSslSocket(HttpURLConnection httpConnection) {
- HttpEngine engine = httpConnection instanceof HttpsURLConnectionImpl
- ? ((HttpsURLConnectionImpl) httpConnection).getHttpEngine()
- : ((HttpURLConnectionImpl) httpConnection).getHttpEngine();
- return engine instanceof HttpsEngine
- ? ((HttpsEngine) engine).getSslSocket()
- : null;
- }
-
- public void writeTo(DiskLruCache.Editor editor) throws IOException {
- OutputStream out = editor.newOutputStream(ENTRY_METADATA);
- Writer writer = new BufferedWriter(new OutputStreamWriter(out, UTF_8));
-
- writer.write(uri + '\n');
- writer.write(requestMethod + '\n');
- writer.write(Integer.toString(varyHeaders.length()) + '\n');
- for (int i = 0; i < varyHeaders.length(); i++) {
- writer.write(varyHeaders.getFieldName(i) + ": " + varyHeaders.getValue(i) + '\n');
- }
-
- writer.write(responseHeaders.getStatusLine() + '\n');
- writer.write(Integer.toString(responseHeaders.length()) + '\n');
- for (int i = 0; i < responseHeaders.length(); i++) {
- writer.write(responseHeaders.getFieldName(i) + ": " + responseHeaders.getValue(i) + '\n');
- }
-
- if (isHttps()) {
- writer.write('\n');
- writer.write(cipherSuite + '\n');
- writeCertArray(writer, peerCertificates);
- writeCertArray(writer, localCertificates);
- }
- writer.close();
- }
-
- private boolean isHttps() {
- return uri.startsWith("https://");
- }
-
- private Certificate[] readCertArray(StrictLineReader reader) throws IOException {
- int length = reader.readInt();
- if (length == -1) {
- return null;
- }
- try {
- CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
- Certificate[] result = new Certificate[length];
- for (int i = 0; i < result.length; i++) {
- String line = reader.readLine();
- byte[] bytes = Base64.decode(line.getBytes("US-ASCII"));
- result[i] = certificateFactory.generateCertificate(new ByteArrayInputStream(bytes));
- }
- return result;
- } catch (CertificateException e) {
- throw new IOException(e.getMessage());
- }
- }
-
- private void writeCertArray(Writer writer, Certificate[] certificates) throws IOException {
- if (certificates == null) {
- writer.write("-1\n");
- return;
- }
- try {
- writer.write(Integer.toString(certificates.length) + '\n');
- for (Certificate certificate : certificates) {
- byte[] bytes = certificate.getEncoded();
- String line = Base64.encode(bytes);
- writer.write(line + '\n');
- }
- } catch (CertificateEncodingException e) {
- throw new IOException(e.getMessage());
- }
- }
-
- public boolean matches(URI uri, String requestMethod,
- Map<String, List<String>> requestHeaders) {
- return this.uri.equals(uri.toString())
- && this.requestMethod.equals(requestMethod)
- && new ResponseHeaders(uri, responseHeaders).varyMatches(varyHeaders.toMultimap(false),
- requestHeaders);
- }
- }
-
- /**
- * Returns an input stream that reads the body of a snapshot, closing the
- * snapshot when the stream is closed.
- */
- private static InputStream newBodyInputStream(final DiskLruCache.Snapshot snapshot) {
- return new FilterInputStream(snapshot.getInputStream(ENTRY_BODY)) {
- @Override public void close() throws IOException {
- snapshot.close();
- super.close();
- }
- };
- }
-
- static class EntryCacheResponse extends CacheResponse {
- private final Entry entry;
- private final DiskLruCache.Snapshot snapshot;
- private final InputStream in;
-
- public EntryCacheResponse(Entry entry, DiskLruCache.Snapshot snapshot) {
- this.entry = entry;
- this.snapshot = snapshot;
- this.in = newBodyInputStream(snapshot);
- }
-
- @Override public Map<String, List<String>> getHeaders() {
- return entry.responseHeaders.toMultimap(true);
- }
-
- @Override public InputStream getBody() {
- return in;
- }
- }
-
- static class EntrySecureCacheResponse extends SecureCacheResponse {
- private final Entry entry;
- private final DiskLruCache.Snapshot snapshot;
- private final InputStream in;
-
- public EntrySecureCacheResponse(Entry entry, DiskLruCache.Snapshot snapshot) {
- this.entry = entry;
- this.snapshot = snapshot;
- this.in = newBodyInputStream(snapshot);
- }
-
- @Override public Map<String, List<String>> getHeaders() {
- return entry.responseHeaders.toMultimap(true);
- }
-
- @Override public InputStream getBody() {
- return in;
- }
-
- @Override public String getCipherSuite() {
- return entry.cipherSuite;
- }
-
- @Override public List<Certificate> getServerCertificateChain()
- throws SSLPeerUnverifiedException {
- if (entry.peerCertificates == null || entry.peerCertificates.length == 0) {
- throw new SSLPeerUnverifiedException(null);
- }
- return Arrays.asList(entry.peerCertificates.clone());
- }
-
- @Override public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
- if (entry.peerCertificates == null || entry.peerCertificates.length == 0) {
- throw new SSLPeerUnverifiedException(null);
- }
- return ((X509Certificate) entry.peerCertificates[0]).getSubjectX500Principal();
- }
-
- @Override public List<Certificate> getLocalCertificateChain() {
- if (entry.localCertificates == null || entry.localCertificates.length == 0) {
- return null;
- }
- return Arrays.asList(entry.localCertificates.clone());
- }
-
- @Override public Principal getLocalPrincipal() {
- if (entry.localCertificates == null || entry.localCertificates.length == 0) {
- return null;
- }
- return ((X509Certificate) entry.localCertificates[0]).getSubjectX500Principal();
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/c6b171ba/framework/src/com/squareup/okhttp/Job.java
----------------------------------------------------------------------
diff --git a/framework/src/com/squareup/okhttp/Job.java b/framework/src/com/squareup/okhttp/Job.java
deleted file mode 100755
index 1bfeb1d..0000000
--- a/framework/src/com/squareup/okhttp/Job.java
+++ /dev/null
@@ -1,232 +0,0 @@
-/*
- * 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;
-
-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.HttpsEngine;
-import com.squareup.okhttp.internal.http.Policy;
-import com.squareup.okhttp.internal.http.RawHeaders;
-import java.io.IOException;
-import java.net.HttpURLConnection;
-import java.net.ProtocolException;
-import java.net.Proxy;
-import java.net.URL;
-
-import static com.squareup.okhttp.internal.Util.getEffectivePort;
-import static com.squareup.okhttp.internal.http.HttpURLConnectionImpl.HTTP_MOVED_PERM;
-import static com.squareup.okhttp.internal.http.HttpURLConnectionImpl.HTTP_MOVED_TEMP;
-import static com.squareup.okhttp.internal.http.HttpURLConnectionImpl.HTTP_MULT_CHOICE;
-import static com.squareup.okhttp.internal.http.HttpURLConnectionImpl.HTTP_PROXY_AUTH;
-import static com.squareup.okhttp.internal.http.HttpURLConnectionImpl.HTTP_SEE_OTHER;
-import static com.squareup.okhttp.internal.http.HttpURLConnectionImpl.HTTP_TEMP_REDIRECT;
-import static com.squareup.okhttp.internal.http.HttpURLConnectionImpl.HTTP_UNAUTHORIZED;
-
-final class Job implements Runnable, Policy {
- private final Dispatcher dispatcher;
- private final OkHttpClient client;
- private final Response.Receiver responseReceiver;
-
- /** The request; possibly a consequence of redirects or auth headers. */
- private Request request;
-
- public Job(Dispatcher dispatcher, OkHttpClient client, Request request,
- Response.Receiver responseReceiver) {
- this.dispatcher = dispatcher;
- this.client = client;
- this.request = request;
- this.responseReceiver = responseReceiver;
- }
-
- @Override public int getChunkLength() {
- return request.body().contentLength() == -1 ? HttpTransport.DEFAULT_CHUNK_LENGTH : -1;
- }
-
- @Override public long getFixedContentLength() {
- return request.body().contentLength();
- }
-
- @Override public boolean getUseCaches() {
- return false; // TODO.
- }
-
- @Override public HttpURLConnection getHttpConnectionToCache() {
- return null;
- }
-
- @Override public URL getURL() {
- return request.url();
- }
-
- @Override public long getIfModifiedSince() {
- return 0; // For HttpURLConnection only. We let the cache drive this.
- }
-
- @Override public boolean usingProxy() {
- return false; // We let the connection decide this.
- }
-
- @Override public void setSelectedProxy(Proxy proxy) {
- // Do nothing.
- }
-
- Object tag() {
- return request.tag();
- }
-
- @Override public void run() {
- try {
- Response response = execute();
- responseReceiver.onResponse(response);
- } catch (IOException e) {
- responseReceiver.onFailure(new Failure.Builder()
- .request(request)
- .exception(e)
- .build());
- } finally {
- // TODO: close the response body
- // TODO: release the HTTP engine (potentially multiple!)
- dispatcher.finished(this);
- }
- }
-
- private Response execute() throws IOException {
- Connection connection = null;
- Response redirectedBy = null;
-
- while (true) {
- HttpEngine engine = newEngine(connection);
-
- Request.Body body = request.body();
- if (body != null) {
- MediaType contentType = body.contentType();
- if (contentType == null) throw new IllegalStateException("contentType == null");
- if (engine.getRequestHeaders().getContentType() == null) {
- engine.getRequestHeaders().setContentType(contentType.toString());
- }
- }
-
- engine.sendRequest();
-
- if (body != null) {
- body.writeTo(engine.getRequestBody());
- }
-
- engine.readResponse();
-
- int responseCode = engine.getResponseCode();
- Dispatcher.RealResponseBody responseBody = new Dispatcher.RealResponseBody(
- engine.getResponseHeaders(), engine.getResponseBody());
-
- Response response = new Response.Builder(request, responseCode)
- .rawHeaders(engine.getResponseHeaders().getHeaders())
- .body(responseBody)
- .redirectedBy(redirectedBy)
- .build();
-
- Request redirect = processResponse(engine, response);
-
- if (redirect == null) {
- engine.automaticallyReleaseConnectionToPool();
- return response;
- }
-
- // TODO: fail if too many redirects
- // TODO: fail if not following redirects
- // TODO: release engine
-
- connection = sameConnection(request, redirect) ? engine.getConnection() : null;
- redirectedBy = response;
- request = redirect;
- }
- }
-
- HttpEngine newEngine(Connection connection) throws IOException {
- String protocol = request.url().getProtocol();
- RawHeaders requestHeaders = request.rawHeaders();
- if (protocol.equals("http")) {
- return new HttpEngine(client, this, request.method(), requestHeaders, connection, null);
- } else if (protocol.equals("https")) {
- return new HttpsEngine(client, this, request.method(), requestHeaders, connection, null);
- } else {
- throw new AssertionError();
- }
- }
-
- /**
- * Figures out the HTTP request to make in response to receiving {@code
- * response}. This will either add authentication headers or follow
- * redirects. If a follow-up is either unnecessary or not applicable, this
- * returns null.
- */
- private Request processResponse(HttpEngine engine, Response response) throws IOException {
- Request request = response.request();
- Proxy selectedProxy = engine.getConnection() != null
- ? engine.getConnection().getRoute().getProxy()
- : client.getProxy();
- int responseCode = response.code();
-
- switch (responseCode) {
- case HTTP_PROXY_AUTH:
- if (selectedProxy.type() != Proxy.Type.HTTP) {
- throw new ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy");
- }
- // fall-through
- case HTTP_UNAUTHORIZED:
- RawHeaders successorRequestHeaders = request.rawHeaders();
- boolean credentialsFound = HttpAuthenticator.processAuthHeader(client.getAuthenticator(),
- response.code(), response.rawHeaders(), successorRequestHeaders, selectedProxy,
- this.request.url());
- return credentialsFound
- ? request.newBuilder().rawHeaders(successorRequestHeaders).build()
- : null;
-
- case HTTP_MULT_CHOICE:
- case HTTP_MOVED_PERM:
- case HTTP_MOVED_TEMP:
- case HTTP_SEE_OTHER:
- case HTTP_TEMP_REDIRECT:
- String method = request.method();
- if (responseCode == HTTP_TEMP_REDIRECT && !method.equals("GET") && !method.equals("HEAD")) {
- // "If the 307 status code is received in response to a request other than GET or HEAD,
- // the user agent MUST NOT automatically redirect the request"
- return null;
- }
-
- String location = response.header("Location");
- if (location == null) {
- return null;
- }
-
- URL url = new URL(request.url(), location);
- if (!url.getProtocol().equals("https") && !url.getProtocol().equals("http")) {
- return null; // Don't follow redirects to unsupported protocols.
- }
-
- return this.request.newBuilder().url(url).build();
-
- default:
- return null;
- }
- }
-
- private boolean sameConnection(Request a, Request b) {
- return a.url().getHost().equals(b.url().getHost())
- && getEffectivePort(a.url()) == getEffectivePort(b.url())
- && a.url().getProtocol().equals(b.url().getProtocol());
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/c6b171ba/framework/src/com/squareup/okhttp/MediaType.java
----------------------------------------------------------------------
diff --git a/framework/src/com/squareup/okhttp/MediaType.java b/framework/src/com/squareup/okhttp/MediaType.java
deleted file mode 100755
index 2c09596..0000000
--- a/framework/src/com/squareup/okhttp/MediaType.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * 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;
-
-import java.nio.charset.Charset;
-import java.util.Locale;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * An <a href="http://tools.ietf.org/html/rfc2045">RFC 2045</a> Media Type,
- * appropriate to describe the content type of an HTTP request or response body.
- */
-public final class MediaType {
- private static final String TOKEN = "([a-zA-Z0-9-!#$%&'*+.^_`{|}~]+)";
- private static final String QUOTED = "\"([^\"]*)\"";
- private static final Pattern TYPE_SUBTYPE = Pattern.compile(TOKEN + "/" + TOKEN);
- private static final Pattern PARAMETER = Pattern.compile(
- ";\\s*" + TOKEN + "=(?:" + TOKEN + "|" + QUOTED + ")");
-
- private final String mediaType;
- private final String type;
- private final String subtype;
- private final String charset;
-
- private MediaType(String mediaType, String type, String subtype, String charset) {
- this.mediaType = mediaType;
- this.type = type;
- this.subtype = subtype;
- this.charset = charset;
- }
-
- /**
- * Returns a media type for {@code string}, or null if {@code string} is not a
- * well-formed media type.
- */
- public static MediaType parse(String string) {
- Matcher typeSubtype = TYPE_SUBTYPE.matcher(string);
- if (!typeSubtype.lookingAt()) return null;
- String type = typeSubtype.group(1).toLowerCase(Locale.US);
- String subtype = typeSubtype.group(2).toLowerCase(Locale.US);
-
- String charset = null;
- Matcher parameter = PARAMETER.matcher(string);
- for (int s = typeSubtype.end(); s < string.length(); s = parameter.end()) {
- parameter.region(s, string.length());
- if (!parameter.lookingAt()) return null; // This is not a well-formed media type.
-
- String name = parameter.group(1);
- if (name == null || !name.equalsIgnoreCase("charset")) continue;
- if (charset != null) throw new IllegalArgumentException("Multiple charsets: " + string);
- charset = parameter.group(2) != null
- ? parameter.group(2) // Value is a token.
- : parameter.group(3); // Value is a quoted string.
- }
-
- return new MediaType(string, type, subtype, charset);
- }
-
- /**
- * Returns the high-level media type, such as "text", "image", "audio",
- * "video", or "application".
- */
- public String type() {
- return type;
- }
-
- /**
- * Returns a specific media subtype, such as "plain" or "png", "mpeg",
- * "mp4" or "xml".
- */
- public String subtype() {
- return subtype;
- }
-
- /**
- * Returns the charset of this media type, or null if this media type doesn't
- * specify a charset.
- */
- public Charset charset() {
- return charset != null ? Charset.forName(charset) : null;
- }
-
- /**
- * Returns the charset of this media type, or {@code defaultValue} if this
- * media type doesn't specify a charset.
- */
- public Charset charset(Charset defaultValue) {
- return charset != null ? Charset.forName(charset) : defaultValue;
- }
-
- /**
- * Returns the encoded media type, like "text/plain; charset=utf-8",
- * appropriate for use in a Content-Type header.
- */
- @Override public String toString() {
- return mediaType;
- }
-
- @Override public boolean equals(Object o) {
- return o instanceof MediaType && ((MediaType) o).mediaType.equals(mediaType);
- }
-
- @Override public int hashCode() {
- return mediaType.hashCode();
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/c6b171ba/framework/src/com/squareup/okhttp/OkAuthenticator.java
----------------------------------------------------------------------
diff --git a/framework/src/com/squareup/okhttp/OkAuthenticator.java b/framework/src/com/squareup/okhttp/OkAuthenticator.java
deleted file mode 100755
index a505419..0000000
--- a/framework/src/com/squareup/okhttp/OkAuthenticator.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * 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;
-
-import com.squareup.okhttp.internal.Base64;
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.net.Proxy;
-import java.net.URL;
-import java.util.List;
-
-/**
- * Responds to authentication challenges from the remote web or proxy server by
- * returning credentials.
- */
-public interface OkAuthenticator {
- /**
- * Returns a credential that satisfies the authentication challenge made by
- * {@code url}. Returns null if the challenge cannot be satisfied. This method
- * is called in response to an HTTP 401 unauthorized status code sent by the
- * origin server.
- *
- * @param challenges parsed "WWW-Authenticate" challenge headers from the HTTP
- * response.
- */
- Credential authenticate(Proxy proxy, URL url, List<Challenge> challenges) throws IOException;
-
- /**
- * Returns a credential that satisfies the authentication challenge made by
- * {@code proxy}. Returns null if the challenge cannot be satisfied. This
- * method is called in response to an HTTP 401 unauthorized status code sent
- * by the proxy server.
- *
- * @param challenges parsed "Proxy-Authenticate" challenge headers from the
- * HTTP response.
- */
- Credential authenticateProxy(Proxy proxy, URL url, List<Challenge> challenges) throws IOException;
-
- /** An RFC 2617 challenge. */
- public final class Challenge {
- private final String scheme;
- private final String realm;
-
- public Challenge(String scheme, String realm) {
- this.scheme = scheme;
- this.realm = realm;
- }
-
- /** Returns the authentication scheme, like {@code Basic}. */
- public String getScheme() {
- return scheme;
- }
-
- /** Returns the protection space. */
- public String getRealm() {
- return realm;
- }
-
- @Override public boolean equals(Object o) {
- return o instanceof Challenge
- && ((Challenge) o).scheme.equals(scheme)
- && ((Challenge) o).realm.equals(realm);
- }
-
- @Override public int hashCode() {
- return scheme.hashCode() + 31 * realm.hashCode();
- }
-
- @Override public String toString() {
- return scheme + " realm=\"" + realm + "\"";
- }
- }
-
- /** An RFC 2617 credential. */
- public final class Credential {
- private final String headerValue;
-
- private Credential(String headerValue) {
- this.headerValue = headerValue;
- }
-
- /** Returns an auth credential for the Basic scheme. */
- public static Credential basic(String userName, String password) {
- try {
- String usernameAndPassword = userName + ":" + password;
- byte[] bytes = usernameAndPassword.getBytes("ISO-8859-1");
- String encoded = Base64.encode(bytes);
- return new Credential("Basic " + encoded);
- } catch (UnsupportedEncodingException e) {
- throw new AssertionError();
- }
- }
-
- public String getHeaderValue() {
- return headerValue;
- }
-
- @Override public boolean equals(Object o) {
- return o instanceof Credential && ((Credential) o).headerValue.equals(headerValue);
- }
-
- @Override public int hashCode() {
- return headerValue.hashCode();
- }
-
- @Override public String toString() {
- return headerValue;
- }
- }
-}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cordova.apache.org
For additional commands, e-mail: commits-help@cordova.apache.org