You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cordova.apache.org by fi...@apache.org on 2013/06/13 20:22:04 UTC
[41/78] [partial] start of lazy loading: axe all vendored-in libs
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/67fa7ebb/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpURLConnectionImpl.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpURLConnectionImpl.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpURLConnectionImpl.java
deleted file mode 100644
index eabe649..0000000
--- a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpURLConnectionImpl.java
+++ /dev/null
@@ -1,556 +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.internal.http;
-
-import com.squareup.okhttp.Connection;
-import com.squareup.okhttp.ConnectionPool;
-import com.squareup.okhttp.OkHttpClient;
-import com.squareup.okhttp.Route;
-import com.squareup.okhttp.internal.AbstractOutputStream;
-import com.squareup.okhttp.internal.FaultRecoveringOutputStream;
-import com.squareup.okhttp.internal.Util;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.CookieHandler;
-import java.net.HttpRetryException;
-import java.net.HttpURLConnection;
-import java.net.InetSocketAddress;
-import java.net.ProtocolException;
-import java.net.Proxy;
-import java.net.ProxySelector;
-import java.net.SocketPermission;
-import java.net.URL;
-import java.security.Permission;
-import java.security.cert.CertificateException;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.SSLHandshakeException;
-import javax.net.ssl.SSLSocketFactory;
-
-import static com.squareup.okhttp.internal.Util.getEffectivePort;
-
-/**
- * This implementation uses HttpEngine to send requests and receive responses.
- * This class may use multiple HttpEngines to follow redirects, authentication
- * retries, etc. to retrieve the final response body.
- *
- * <h3>What does 'connected' mean?</h3>
- * This class inherits a {@code connected} field from the superclass. That field
- * is <strong>not</strong> used to indicate not whether this URLConnection is
- * currently connected. Instead, it indicates whether a connection has ever been
- * attempted. Once a connection has been attempted, certain properties (request
- * header fields, request method, etc.) are immutable. Test the {@code
- * connection} field on this class for null/non-null to determine of an instance
- * is currently connected to a server.
- */
-public class HttpURLConnectionImpl extends HttpURLConnection {
-
- /** Numeric status code, 307: Temporary Redirect. */
- static final int HTTP_TEMP_REDIRECT = 307;
-
- /**
- * How many redirects should we follow? Chrome follows 21; Firefox, curl,
- * and wget follow 20; Safari follows 16; and HTTP/1.0 recommends 5.
- */
- private static final int MAX_REDIRECTS = 20;
-
- /**
- * The minimum number of request body bytes to transmit before we're willing
- * to let a routine {@link IOException} bubble up to the user. This is used to
- * size a buffer for data that will be replayed upon error.
- */
- private static final int MAX_REPLAY_BUFFER_LENGTH = 8192;
-
- private final boolean followProtocolRedirects;
-
- /** The proxy requested by the client, or null for a proxy to be selected automatically. */
- final Proxy requestedProxy;
-
- final ProxySelector proxySelector;
- final CookieHandler cookieHandler;
- final OkResponseCache responseCache;
- final ConnectionPool connectionPool;
- /* SSL configuration; necessary for HTTP requests that get redirected to HTTPS. */
- SSLSocketFactory sslSocketFactory;
- HostnameVerifier hostnameVerifier;
- final Set<Route> failedRoutes;
-
- private final RawHeaders rawRequestHeaders = new RawHeaders();
-
- private int redirectionCount;
- private FaultRecoveringOutputStream faultRecoveringRequestBody;
-
- protected IOException httpEngineFailure;
- protected HttpEngine httpEngine;
-
- public HttpURLConnectionImpl(URL url, OkHttpClient client, OkResponseCache responseCache,
- Set<Route> failedRoutes) {
- super(url);
- this.followProtocolRedirects = client.getFollowProtocolRedirects();
- this.failedRoutes = failedRoutes;
- this.requestedProxy = client.getProxy();
- this.proxySelector = client.getProxySelector();
- this.cookieHandler = client.getCookieHandler();
- this.connectionPool = client.getConnectionPool();
- this.sslSocketFactory = client.getSslSocketFactory();
- this.hostnameVerifier = client.getHostnameVerifier();
- this.responseCache = responseCache;
- }
-
- Set<Route> getFailedRoutes() {
- return failedRoutes;
- }
-
- @Override public final void connect() throws IOException {
- initHttpEngine();
- boolean success;
- do {
- success = execute(false);
- } while (!success);
- }
-
- @Override public final void disconnect() {
- // Calling disconnect() before a connection exists should have no effect.
- if (httpEngine != null) {
- // We close the response body here instead of in
- // HttpEngine.release because that is called when input
- // has been completely read from the underlying socket.
- // However the response body can be a GZIPInputStream that
- // still has unread data.
- if (httpEngine.hasResponse()) {
- Util.closeQuietly(httpEngine.getResponseBody());
- }
- httpEngine.release(true);
- }
- }
-
- /**
- * Returns an input stream from the server in the case of error such as the
- * requested file (txt, htm, html) is not found on the remote server.
- */
- @Override public final InputStream getErrorStream() {
- try {
- HttpEngine response = getResponse();
- if (response.hasResponseBody() && response.getResponseCode() >= HTTP_BAD_REQUEST) {
- return response.getResponseBody();
- }
- return null;
- } catch (IOException e) {
- return null;
- }
- }
-
- /**
- * Returns the value of the field at {@code position}. Returns null if there
- * are fewer than {@code position} headers.
- */
- @Override public final String getHeaderField(int position) {
- try {
- return getResponse().getResponseHeaders().getHeaders().getValue(position);
- } catch (IOException e) {
- return null;
- }
- }
-
- /**
- * Returns the value of the field corresponding to the {@code fieldName}, or
- * null if there is no such field. If the field has multiple values, the
- * last value is returned.
- */
- @Override public final String getHeaderField(String fieldName) {
- try {
- RawHeaders rawHeaders = getResponse().getResponseHeaders().getHeaders();
- return fieldName == null ? rawHeaders.getStatusLine() : rawHeaders.get(fieldName);
- } catch (IOException e) {
- return null;
- }
- }
-
- @Override public final String getHeaderFieldKey(int position) {
- try {
- return getResponse().getResponseHeaders().getHeaders().getFieldName(position);
- } catch (IOException e) {
- return null;
- }
- }
-
- @Override public final Map<String, List<String>> getHeaderFields() {
- try {
- return getResponse().getResponseHeaders().getHeaders().toMultimap(true);
- } catch (IOException e) {
- return null;
- }
- }
-
- @Override public final Map<String, List<String>> getRequestProperties() {
- if (connected) {
- throw new IllegalStateException(
- "Cannot access request header fields after connection is set");
- }
- return rawRequestHeaders.toMultimap(false);
- }
-
- @Override public final InputStream getInputStream() throws IOException {
- if (!doInput) {
- throw new ProtocolException("This protocol does not support input");
- }
-
- HttpEngine response = getResponse();
-
- // if the requested file does not exist, throw an exception formerly the
- // Error page from the server was returned if the requested file was
- // text/html this has changed to return FileNotFoundException for all
- // file types
- if (getResponseCode() >= HTTP_BAD_REQUEST) {
- throw new FileNotFoundException(url.toString());
- }
-
- InputStream result = response.getResponseBody();
- if (result == null) {
- throw new ProtocolException("No response body exists; responseCode=" + getResponseCode());
- }
- return result;
- }
-
- @Override public final OutputStream getOutputStream() throws IOException {
- connect();
-
- OutputStream out = httpEngine.getRequestBody();
- if (out == null) {
- throw new ProtocolException("method does not support a request body: " + method);
- } else if (httpEngine.hasResponse()) {
- throw new ProtocolException("cannot write request body after response has been read");
- }
-
- if (faultRecoveringRequestBody == null) {
- faultRecoveringRequestBody = new FaultRecoveringOutputStream(MAX_REPLAY_BUFFER_LENGTH, out) {
- @Override protected OutputStream replacementStream(IOException e) throws IOException {
- if (httpEngine.getRequestBody() instanceof AbstractOutputStream
- && ((AbstractOutputStream) httpEngine.getRequestBody()).isClosed()) {
- return null; // Don't recover once the underlying stream has been closed.
- }
- if (handleFailure(e)) {
- return httpEngine.getRequestBody();
- }
- return null; // This is a permanent failure.
- }
- };
- }
-
- return faultRecoveringRequestBody;
- }
-
- @Override public final Permission getPermission() throws IOException {
- String hostName = getURL().getHost();
- int hostPort = Util.getEffectivePort(getURL());
- if (usingProxy()) {
- InetSocketAddress proxyAddress = (InetSocketAddress) requestedProxy.address();
- hostName = proxyAddress.getHostName();
- hostPort = proxyAddress.getPort();
- }
- return new SocketPermission(hostName + ":" + hostPort, "connect, resolve");
- }
-
- @Override public final String getRequestProperty(String field) {
- if (field == null) {
- return null;
- }
- return rawRequestHeaders.get(field);
- }
-
- private void initHttpEngine() throws IOException {
- if (httpEngineFailure != null) {
- throw httpEngineFailure;
- } else if (httpEngine != null) {
- return;
- }
-
- connected = true;
- try {
- if (doOutput) {
- if (method.equals("GET")) {
- // they are requesting a stream to write to. This implies a POST method
- method = "POST";
- } else if (!method.equals("POST") && !method.equals("PUT")) {
- // If the request method is neither POST nor PUT, then you're not writing
- throw new ProtocolException(method + " does not support writing");
- }
- }
- httpEngine = newHttpEngine(method, rawRequestHeaders, null, null);
- } catch (IOException e) {
- httpEngineFailure = e;
- throw e;
- }
- }
-
- protected HttpURLConnection getHttpConnectionToCache() {
- return this;
- }
-
- private HttpEngine newHttpEngine(String method, RawHeaders requestHeaders,
- Connection connection, RetryableOutputStream requestBody) throws IOException {
- if (url.getProtocol().equals("http")) {
- return new HttpEngine(this, method, requestHeaders, connection, requestBody);
- } else if (url.getProtocol().equals("https")) {
- return new HttpsURLConnectionImpl.HttpsEngine(
- this, method, requestHeaders, connection, requestBody);
- } else {
- throw new AssertionError();
- }
- }
-
- /**
- * Aggressively tries to get the final HTTP response, potentially making
- * many HTTP requests in the process in order to cope with redirects and
- * authentication.
- */
- private HttpEngine getResponse() throws IOException {
- initHttpEngine();
-
- if (httpEngine.hasResponse()) {
- return httpEngine;
- }
-
- while (true) {
- if (!execute(true)) {
- continue;
- }
-
- Retry retry = processResponseHeaders();
- if (retry == Retry.NONE) {
- httpEngine.automaticallyReleaseConnectionToPool();
- return httpEngine;
- }
-
- // The first request was insufficient. Prepare for another...
- String retryMethod = method;
- OutputStream requestBody = httpEngine.getRequestBody();
-
- // Although RFC 2616 10.3.2 specifies that a HTTP_MOVED_PERM
- // redirect should keep the same method, Chrome, Firefox and the
- // RI all issue GETs when following any redirect.
- int responseCode = getResponseCode();
- if (responseCode == HTTP_MULT_CHOICE
- || responseCode == HTTP_MOVED_PERM
- || responseCode == HTTP_MOVED_TEMP
- || responseCode == HTTP_SEE_OTHER) {
- retryMethod = "GET";
- requestBody = null;
- }
-
- if (requestBody != null && !(requestBody instanceof RetryableOutputStream)) {
- throw new HttpRetryException("Cannot retry streamed HTTP body",
- httpEngine.getResponseCode());
- }
-
- if (retry == Retry.DIFFERENT_CONNECTION) {
- httpEngine.automaticallyReleaseConnectionToPool();
- }
-
- httpEngine.release(false);
-
- httpEngine = newHttpEngine(retryMethod, rawRequestHeaders, httpEngine.getConnection(),
- (RetryableOutputStream) requestBody);
- }
- }
-
- /**
- * Sends a request and optionally reads a response. Returns true if the
- * request was successfully executed, and false if the request can be
- * retried. Throws an exception if the request failed permanently.
- */
- private boolean execute(boolean readResponse) throws IOException {
- try {
- httpEngine.sendRequest();
- if (readResponse) {
- httpEngine.readResponse();
- }
- return true;
- } catch (IOException e) {
- if (handleFailure(e)) {
- return false;
- } else {
- throw e;
- }
- }
- }
-
- /**
- * Report and attempt to recover from {@code e}. Returns true if the HTTP
- * engine was replaced and the request should be retried. Otherwise the
- * failure is permanent.
- */
- private boolean handleFailure(IOException e) throws IOException {
- RouteSelector routeSelector = httpEngine.routeSelector;
- if (routeSelector != null && httpEngine.connection != null) {
- routeSelector.connectFailed(httpEngine.connection, e);
- }
-
- OutputStream requestBody = httpEngine.getRequestBody();
- boolean canRetryRequestBody = requestBody == null
- || requestBody instanceof RetryableOutputStream
- || (faultRecoveringRequestBody != null && faultRecoveringRequestBody.isRecoverable());
- if (routeSelector == null && httpEngine.connection == null // No connection.
- || routeSelector != null && !routeSelector.hasNext() // No more routes to attempt.
- || !isRecoverable(e)
- || !canRetryRequestBody) {
- httpEngineFailure = e;
- return false;
- }
-
- httpEngine.release(true);
- RetryableOutputStream retryableOutputStream = requestBody instanceof RetryableOutputStream
- ? (RetryableOutputStream) requestBody
- : null;
- httpEngine = newHttpEngine(method, rawRequestHeaders, null, retryableOutputStream);
- httpEngine.routeSelector = routeSelector; // Keep the same routeSelector.
- if (faultRecoveringRequestBody != null && faultRecoveringRequestBody.isRecoverable()) {
- httpEngine.sendRequest();
- faultRecoveringRequestBody.replaceStream(httpEngine.getRequestBody());
- }
- return true;
- }
-
- private boolean isRecoverable(IOException e) {
- // If the problem was a CertificateException from the X509TrustManager,
- // do not retry, we didn't have an abrupt server initiated exception.
- boolean sslFailure =
- e instanceof SSLHandshakeException && e.getCause() instanceof CertificateException;
- boolean protocolFailure = e instanceof ProtocolException;
- return !sslFailure && !protocolFailure;
- }
-
- public HttpEngine getHttpEngine() {
- return httpEngine;
- }
-
- enum Retry {
- NONE,
- SAME_CONNECTION,
- DIFFERENT_CONNECTION
- }
-
- /**
- * Returns the retry action to take for the current response headers. The
- * headers, proxy and target URL or this connection may be adjusted to
- * prepare for a follow up request.
- */
- private Retry processResponseHeaders() throws IOException {
- Proxy selectedProxy = httpEngine.connection != null
- ? httpEngine.connection.getRoute().getProxy()
- : requestedProxy;
- final int responseCode = getResponseCode();
- 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:
- boolean credentialsFound = HttpAuthenticator.processAuthHeader(getResponseCode(),
- httpEngine.getResponseHeaders().getHeaders(), rawRequestHeaders, selectedProxy, url);
- return credentialsFound ? Retry.SAME_CONNECTION : Retry.NONE;
-
- case HTTP_MULT_CHOICE:
- case HTTP_MOVED_PERM:
- case HTTP_MOVED_TEMP:
- case HTTP_SEE_OTHER:
- case HTTP_TEMP_REDIRECT:
- if (!getInstanceFollowRedirects()) {
- return Retry.NONE;
- }
- if (++redirectionCount > MAX_REDIRECTS) {
- throw new ProtocolException("Too many redirects: " + redirectionCount);
- }
- 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 Retry.NONE;
- }
- String location = getHeaderField("Location");
- if (location == null) {
- return Retry.NONE;
- }
- URL previousUrl = url;
- url = new URL(previousUrl, location);
- if (!url.getProtocol().equals("https") && !url.getProtocol().equals("http")) {
- return Retry.NONE; // Don't follow redirects to unsupported protocols.
- }
- boolean sameProtocol = previousUrl.getProtocol().equals(url.getProtocol());
- if (!sameProtocol && !followProtocolRedirects) {
- return Retry.NONE; // This client doesn't follow redirects across protocols.
- }
- boolean sameHost = previousUrl.getHost().equals(url.getHost());
- boolean samePort = getEffectivePort(previousUrl) == getEffectivePort(url);
- if (sameHost && samePort && sameProtocol) {
- return Retry.SAME_CONNECTION;
- } else {
- return Retry.DIFFERENT_CONNECTION;
- }
-
- default:
- return Retry.NONE;
- }
- }
-
- /** @see java.net.HttpURLConnection#setFixedLengthStreamingMode(int) */
- final int getFixedContentLength() {
- return fixedContentLength;
- }
-
- /** @see java.net.HttpURLConnection#setChunkedStreamingMode(int) */
- final int getChunkLength() {
- return chunkLength;
- }
-
- @Override public final boolean usingProxy() {
- return (requestedProxy != null && requestedProxy.type() != Proxy.Type.DIRECT);
- }
-
- @Override public String getResponseMessage() throws IOException {
- return getResponse().getResponseHeaders().getHeaders().getResponseMessage();
- }
-
- @Override public final int getResponseCode() throws IOException {
- return getResponse().getResponseCode();
- }
-
- @Override public final void setRequestProperty(String field, String newValue) {
- if (connected) {
- throw new IllegalStateException("Cannot set request property after connection is made");
- }
- if (field == null) {
- throw new NullPointerException("field == null");
- }
- rawRequestHeaders.set(field, newValue);
- }
-
- @Override public final void addRequestProperty(String field, String value) {
- if (connected) {
- throw new IllegalStateException("Cannot add request property after connection is made");
- }
- if (field == null) {
- throw new NullPointerException("field == null");
- }
- rawRequestHeaders.add(field, value);
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/67fa7ebb/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpsURLConnectionImpl.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpsURLConnectionImpl.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpsURLConnectionImpl.java
deleted file mode 100644
index 235f862..0000000
--- a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/HttpsURLConnectionImpl.java
+++ /dev/null
@@ -1,461 +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.internal.http;
-
-import com.squareup.okhttp.Connection;
-import com.squareup.okhttp.OkHttpClient;
-import com.squareup.okhttp.Route;
-import com.squareup.okhttp.TunnelRequest;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.CacheResponse;
-import java.net.HttpURLConnection;
-import java.net.ProtocolException;
-import java.net.SecureCacheResponse;
-import java.net.URL;
-import java.security.Permission;
-import java.security.Principal;
-import java.security.cert.Certificate;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.HttpsURLConnection;
-import javax.net.ssl.SSLPeerUnverifiedException;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.SSLSocketFactory;
-
-import static com.squareup.okhttp.internal.Util.getEffectivePort;
-
-public final class HttpsURLConnectionImpl extends HttpsURLConnection {
-
- /** HttpUrlConnectionDelegate allows reuse of HttpURLConnectionImpl. */
- private final HttpUrlConnectionDelegate delegate;
-
- public HttpsURLConnectionImpl(URL url, OkHttpClient client, OkResponseCache responseCache,
- Set<Route> failedRoutes) {
- super(url);
- delegate = new HttpUrlConnectionDelegate(url, client, responseCache, failedRoutes);
- }
-
- @Override public String getCipherSuite() {
- SecureCacheResponse cacheResponse = delegate.getSecureCacheResponse();
- if (cacheResponse != null) {
- return cacheResponse.getCipherSuite();
- }
- SSLSocket sslSocket = getSslSocket();
- if (sslSocket != null) {
- return sslSocket.getSession().getCipherSuite();
- }
- return null;
- }
-
- @Override public Certificate[] getLocalCertificates() {
- SecureCacheResponse cacheResponse = delegate.getSecureCacheResponse();
- if (cacheResponse != null) {
- List<Certificate> result = cacheResponse.getLocalCertificateChain();
- return result != null ? result.toArray(new Certificate[result.size()]) : null;
- }
- SSLSocket sslSocket = getSslSocket();
- if (sslSocket != null) {
- return sslSocket.getSession().getLocalCertificates();
- }
- return null;
- }
-
- @Override public Certificate[] getServerCertificates() throws SSLPeerUnverifiedException {
- SecureCacheResponse cacheResponse = delegate.getSecureCacheResponse();
- if (cacheResponse != null) {
- List<Certificate> result = cacheResponse.getServerCertificateChain();
- return result != null ? result.toArray(new Certificate[result.size()]) : null;
- }
- SSLSocket sslSocket = getSslSocket();
- if (sslSocket != null) {
- return sslSocket.getSession().getPeerCertificates();
- }
- return null;
- }
-
- @Override public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
- SecureCacheResponse cacheResponse = delegate.getSecureCacheResponse();
- if (cacheResponse != null) {
- return cacheResponse.getPeerPrincipal();
- }
- SSLSocket sslSocket = getSslSocket();
- if (sslSocket != null) {
- return sslSocket.getSession().getPeerPrincipal();
- }
- return null;
- }
-
- @Override public Principal getLocalPrincipal() {
- SecureCacheResponse cacheResponse = delegate.getSecureCacheResponse();
- if (cacheResponse != null) {
- return cacheResponse.getLocalPrincipal();
- }
- SSLSocket sslSocket = getSslSocket();
- if (sslSocket != null) {
- return sslSocket.getSession().getLocalPrincipal();
- }
- return null;
- }
-
- public HttpEngine getHttpEngine() {
- return delegate.getHttpEngine();
- }
-
- private SSLSocket getSslSocket() {
- if (delegate.httpEngine == null || delegate.httpEngine.sentRequestMillis == -1) {
- throw new IllegalStateException("Connection has not yet been established");
- }
- return delegate.httpEngine instanceof HttpsEngine
- ? ((HttpsEngine) delegate.httpEngine).sslSocket
- : null; // Not HTTPS! Probably an https:// to http:// redirect.
- }
-
- @Override
- public void disconnect() {
- delegate.disconnect();
- }
-
- @Override
- public InputStream getErrorStream() {
- return delegate.getErrorStream();
- }
-
- @Override
- public String getRequestMethod() {
- return delegate.getRequestMethod();
- }
-
- @Override
- public int getResponseCode() throws IOException {
- return delegate.getResponseCode();
- }
-
- @Override
- public String getResponseMessage() throws IOException {
- return delegate.getResponseMessage();
- }
-
- @Override
- public void setRequestMethod(String method) throws ProtocolException {
- delegate.setRequestMethod(method);
- }
-
- @Override
- public boolean usingProxy() {
- return delegate.usingProxy();
- }
-
- @Override
- public boolean getInstanceFollowRedirects() {
- return delegate.getInstanceFollowRedirects();
- }
-
- @Override
- public void setInstanceFollowRedirects(boolean followRedirects) {
- delegate.setInstanceFollowRedirects(followRedirects);
- }
-
- @Override
- public void connect() throws IOException {
- connected = true;
- delegate.connect();
- }
-
- @Override
- public boolean getAllowUserInteraction() {
- return delegate.getAllowUserInteraction();
- }
-
- @Override
- public Object getContent() throws IOException {
- return delegate.getContent();
- }
-
- @SuppressWarnings("unchecked") // Spec does not generify
- @Override
- public Object getContent(Class[] types) throws IOException {
- return delegate.getContent(types);
- }
-
- @Override
- public String getContentEncoding() {
- return delegate.getContentEncoding();
- }
-
- @Override
- public int getContentLength() {
- return delegate.getContentLength();
- }
-
- @Override
- public String getContentType() {
- return delegate.getContentType();
- }
-
- @Override
- public long getDate() {
- return delegate.getDate();
- }
-
- @Override
- public boolean getDefaultUseCaches() {
- return delegate.getDefaultUseCaches();
- }
-
- @Override
- public boolean getDoInput() {
- return delegate.getDoInput();
- }
-
- @Override
- public boolean getDoOutput() {
- return delegate.getDoOutput();
- }
-
- @Override
- public long getExpiration() {
- return delegate.getExpiration();
- }
-
- @Override
- public String getHeaderField(int pos) {
- return delegate.getHeaderField(pos);
- }
-
- @Override
- public Map<String, List<String>> getHeaderFields() {
- return delegate.getHeaderFields();
- }
-
- @Override
- public Map<String, List<String>> getRequestProperties() {
- return delegate.getRequestProperties();
- }
-
- @Override
- public void addRequestProperty(String field, String newValue) {
- delegate.addRequestProperty(field, newValue);
- }
-
- @Override
- public String getHeaderField(String key) {
- return delegate.getHeaderField(key);
- }
-
- @Override
- public long getHeaderFieldDate(String field, long defaultValue) {
- return delegate.getHeaderFieldDate(field, defaultValue);
- }
-
- @Override
- public int getHeaderFieldInt(String field, int defaultValue) {
- return delegate.getHeaderFieldInt(field, defaultValue);
- }
-
- @Override
- public String getHeaderFieldKey(int position) {
- return delegate.getHeaderFieldKey(position);
- }
-
- @Override
- public long getIfModifiedSince() {
- return delegate.getIfModifiedSince();
- }
-
- @Override
- public InputStream getInputStream() throws IOException {
- return delegate.getInputStream();
- }
-
- @Override
- public long getLastModified() {
- return delegate.getLastModified();
- }
-
- @Override
- public OutputStream getOutputStream() throws IOException {
- return delegate.getOutputStream();
- }
-
- @Override
- public Permission getPermission() throws IOException {
- return delegate.getPermission();
- }
-
- @Override
- public String getRequestProperty(String field) {
- return delegate.getRequestProperty(field);
- }
-
- @Override
- public URL getURL() {
- return delegate.getURL();
- }
-
- @Override
- public boolean getUseCaches() {
- return delegate.getUseCaches();
- }
-
- @Override
- public void setAllowUserInteraction(boolean newValue) {
- delegate.setAllowUserInteraction(newValue);
- }
-
- @Override
- public void setDefaultUseCaches(boolean newValue) {
- delegate.setDefaultUseCaches(newValue);
- }
-
- @Override
- public void setDoInput(boolean newValue) {
- delegate.setDoInput(newValue);
- }
-
- @Override
- public void setDoOutput(boolean newValue) {
- delegate.setDoOutput(newValue);
- }
-
- @Override
- public void setIfModifiedSince(long newValue) {
- delegate.setIfModifiedSince(newValue);
- }
-
- @Override
- public void setRequestProperty(String field, String newValue) {
- delegate.setRequestProperty(field, newValue);
- }
-
- @Override
- public void setUseCaches(boolean newValue) {
- delegate.setUseCaches(newValue);
- }
-
- @Override
- public void setConnectTimeout(int timeoutMillis) {
- delegate.setConnectTimeout(timeoutMillis);
- }
-
- @Override
- public int getConnectTimeout() {
- return delegate.getConnectTimeout();
- }
-
- @Override
- public void setReadTimeout(int timeoutMillis) {
- delegate.setReadTimeout(timeoutMillis);
- }
-
- @Override
- public int getReadTimeout() {
- return delegate.getReadTimeout();
- }
-
- @Override
- public String toString() {
- return delegate.toString();
- }
-
- @Override
- public void setFixedLengthStreamingMode(int contentLength) {
- delegate.setFixedLengthStreamingMode(contentLength);
- }
-
- @Override
- public void setChunkedStreamingMode(int chunkLength) {
- delegate.setChunkedStreamingMode(chunkLength);
- }
-
- @Override public void setHostnameVerifier(HostnameVerifier hostnameVerifier) {
- delegate.hostnameVerifier = hostnameVerifier;
- }
-
- @Override public HostnameVerifier getHostnameVerifier() {
- return delegate.hostnameVerifier;
- }
-
- @Override public void setSSLSocketFactory(SSLSocketFactory sslSocketFactory) {
- delegate.sslSocketFactory = sslSocketFactory;
- }
-
- @Override public SSLSocketFactory getSSLSocketFactory() {
- return delegate.sslSocketFactory;
- }
-
- private final class HttpUrlConnectionDelegate extends HttpURLConnectionImpl {
- private HttpUrlConnectionDelegate(URL url, OkHttpClient client, OkResponseCache responseCache,
- Set<Route> failedRoutes) {
- super(url, client, responseCache, failedRoutes);
- }
-
- @Override protected HttpURLConnection getHttpConnectionToCache() {
- return HttpsURLConnectionImpl.this;
- }
-
- public SecureCacheResponse getSecureCacheResponse() {
- return httpEngine instanceof HttpsEngine
- ? (SecureCacheResponse) httpEngine.getCacheResponse()
- : null;
- }
- }
-
- public static final class HttpsEngine extends HttpEngine {
- /**
- * Stash of HttpsEngine.connection.socket to implement requests like
- * {@link #getCipherSuite} even after the connection has been recycled.
- */
- private SSLSocket sslSocket;
-
- /**
- * @param policy the HttpURLConnectionImpl with connection configuration
- */
- public HttpsEngine(HttpURLConnectionImpl policy, String method, RawHeaders requestHeaders,
- Connection connection, RetryableOutputStream requestBody) throws IOException {
- super(policy, method, requestHeaders, connection, requestBody);
- this.sslSocket = connection != null ? (SSLSocket) connection.getSocket() : null;
- }
-
- @Override protected void connected(Connection connection) {
- this.sslSocket = (SSLSocket) connection.getSocket();
- }
-
- @Override protected boolean acceptCacheResponseType(CacheResponse cacheResponse) {
- return cacheResponse instanceof SecureCacheResponse;
- }
-
- @Override protected boolean includeAuthorityInRequestLine() {
- // Even if there is a proxy, it isn't involved. Always request just the file.
- return false;
- }
-
- @Override protected TunnelRequest getTunnelConfig() {
- String userAgent = requestHeaders.getUserAgent();
- if (userAgent == null) {
- userAgent = getDefaultUserAgent();
- }
-
- URL url = policy.getURL();
- return new TunnelRequest(url.getHost(), getEffectivePort(url), userAgent,
- requestHeaders.getProxyAuthorization());
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/67fa7ebb/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/OkResponseCache.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/OkResponseCache.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/OkResponseCache.java
deleted file mode 100644
index 5829f02..0000000
--- a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/OkResponseCache.java
+++ /dev/null
@@ -1,55 +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.internal.http;
-
-import com.squareup.okhttp.ResponseSource;
-import java.io.IOException;
-import java.net.CacheRequest;
-import java.net.CacheResponse;
-import java.net.HttpURLConnection;
-import java.net.URI;
-import java.net.URLConnection;
-import java.util.List;
-import java.util.Map;
-
-/**
- * An extended response cache API. Unlike {@link java.net.ResponseCache}, this
- * interface supports conditional caching and statistics.
- *
- * <p>Along with the rest of the {@code internal} package, this is not a public
- * API. Applications wishing to supply their own caches must use the more
- * limited {@link java.net.ResponseCache} interface.
- */
-public interface OkResponseCache {
- CacheResponse get(URI uri, String requestMethod, Map<String, List<String>> requestHeaders)
- throws IOException;
-
- CacheRequest put(URI uri, URLConnection urlConnection) throws IOException;
-
- /**
- * Handles a conditional request hit by updating the stored cache response
- * with the headers from {@code httpConnection}. The cached response body is
- * not updated. If the stored response has changed since {@code
- * conditionalCacheHit} was returned, this does nothing.
- */
- void update(CacheResponse conditionalCacheHit, HttpURLConnection connection) throws IOException;
-
- /** Track an conditional GET that was satisfied by this cache. */
- void trackConditionalCacheHit();
-
- /** Track an HTTP response being satisfied by {@code source}. */
- void trackResponse(ResponseSource source);
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/67fa7ebb/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/OkResponseCacheAdapter.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/OkResponseCacheAdapter.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/OkResponseCacheAdapter.java
deleted file mode 100644
index 2ac915a..0000000
--- a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/OkResponseCacheAdapter.java
+++ /dev/null
@@ -1,53 +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.internal.http;
-
-import com.squareup.okhttp.ResponseSource;
-import java.io.IOException;
-import java.net.CacheRequest;
-import java.net.CacheResponse;
-import java.net.HttpURLConnection;
-import java.net.ResponseCache;
-import java.net.URI;
-import java.net.URLConnection;
-import java.util.List;
-import java.util.Map;
-
-public final class OkResponseCacheAdapter implements OkResponseCache {
- private final ResponseCache responseCache;
- public OkResponseCacheAdapter(ResponseCache responseCache) {
- this.responseCache = responseCache;
- }
-
- @Override public CacheResponse get(URI uri, String requestMethod,
- Map<String, List<String>> requestHeaders) throws IOException {
- return responseCache.get(uri, requestMethod, requestHeaders);
- }
-
- @Override public CacheRequest put(URI uri, URLConnection urlConnection) throws IOException {
- return responseCache.put(uri, urlConnection);
- }
-
- @Override public void update(CacheResponse conditionalCacheHit, HttpURLConnection connection)
- throws IOException {
- }
-
- @Override public void trackConditionalCacheHit() {
- }
-
- @Override public void trackResponse(ResponseSource source) {
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/67fa7ebb/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RawHeaders.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RawHeaders.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RawHeaders.java
deleted file mode 100644
index eba887e..0000000
--- a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RawHeaders.java
+++ /dev/null
@@ -1,424 +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.internal.http;
-
-import com.squareup.okhttp.internal.Util;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.UnsupportedEncodingException;
-import java.net.ProtocolException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.TreeMap;
-
-/**
- * The HTTP status and unparsed header fields of a single HTTP message. Values
- * are represented as uninterpreted strings; use {@link RequestHeaders} and
- * {@link ResponseHeaders} for interpreted headers. This class maintains the
- * order of the header fields within the HTTP message.
- *
- * <p>This class tracks fields line-by-line. A field with multiple comma-
- * separated values on the same line will be treated as a field with a single
- * value by this class. It is the caller's responsibility to detect and split
- * on commas if their field permits multiple values. This simplifies use of
- * single-valued fields whose values routinely contain commas, such as cookies
- * or dates.
- *
- * <p>This class trims whitespace from values. It never returns values with
- * leading or trailing whitespace.
- */
-public final class RawHeaders {
- private static final Comparator<String> FIELD_NAME_COMPARATOR = new Comparator<String>() {
- // @FindBugsSuppressWarnings("ES_COMPARING_PARAMETER_STRING_WITH_EQ")
- @Override public int compare(String a, String b) {
- if (a == b) {
- return 0;
- } else if (a == null) {
- return -1;
- } else if (b == null) {
- return 1;
- } else {
- return String.CASE_INSENSITIVE_ORDER.compare(a, b);
- }
- }
- };
-
- private final List<String> namesAndValues = new ArrayList<String>(20);
- private String requestLine;
- private String statusLine;
- private int httpMinorVersion = 1;
- private int responseCode = -1;
- private String responseMessage;
-
- public RawHeaders() {
- }
-
- public RawHeaders(RawHeaders copyFrom) {
- namesAndValues.addAll(copyFrom.namesAndValues);
- requestLine = copyFrom.requestLine;
- statusLine = copyFrom.statusLine;
- httpMinorVersion = copyFrom.httpMinorVersion;
- responseCode = copyFrom.responseCode;
- responseMessage = copyFrom.responseMessage;
- }
-
- /** Sets the request line (like "GET / HTTP/1.1"). */
- public void setRequestLine(String requestLine) {
- requestLine = requestLine.trim();
- this.requestLine = requestLine;
- }
-
- /** Sets the response status line (like "HTTP/1.0 200 OK"). */
- public void setStatusLine(String statusLine) throws IOException {
- // H T T P / 1 . 1 2 0 0 T e m p o r a r y R e d i r e c t
- // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
- if (this.responseMessage != null) {
- throw new IllegalStateException("statusLine is already set");
- }
- // We allow empty message without leading white space since some servers
- // do not send the white space when the message is empty.
- boolean hasMessage = statusLine.length() > 13;
- if (!statusLine.startsWith("HTTP/1.")
- || statusLine.length() < 12
- || statusLine.charAt(8) != ' '
- || (hasMessage && statusLine.charAt(12) != ' ')) {
- throw new ProtocolException("Unexpected status line: " + statusLine);
- }
- int httpMinorVersion = statusLine.charAt(7) - '0';
- if (httpMinorVersion < 0 || httpMinorVersion > 9) {
- throw new ProtocolException("Unexpected status line: " + statusLine);
- }
- int responseCode;
- try {
- responseCode = Integer.parseInt(statusLine.substring(9, 12));
- } catch (NumberFormatException e) {
- throw new ProtocolException("Unexpected status line: " + statusLine);
- }
- this.responseMessage = hasMessage ? statusLine.substring(13) : "";
- this.responseCode = responseCode;
- this.statusLine = statusLine;
- this.httpMinorVersion = httpMinorVersion;
- }
-
- public void computeResponseStatusLineFromSpdyHeaders() throws IOException {
- String status = null;
- String version = null;
- for (int i = 0; i < namesAndValues.size(); i += 2) {
- String name = namesAndValues.get(i);
- if (":status".equals(name)) {
- status = namesAndValues.get(i + 1);
- } else if (":version".equals(name)) {
- version = namesAndValues.get(i + 1);
- }
- }
- if (status == null || version == null) {
- throw new ProtocolException("Expected ':status' and ':version' headers not present");
- }
- setStatusLine(version + " " + status);
- }
-
- /**
- * @param method like "GET", "POST", "HEAD", etc.
- * @param path like "/foo/bar.html"
- * @param version like "HTTP/1.1"
- * @param host like "www.android.com:1234"
- * @param scheme like "https"
- */
- public void addSpdyRequestHeaders(String method, String path, String version, String host,
- String scheme) {
- // TODO: populate the statusLine for the client's benefit?
- add(":method", method);
- add(":scheme", scheme);
- add(":path", path);
- add(":version", version);
- add(":host", host);
- }
-
- public String getStatusLine() {
- return statusLine;
- }
-
- /**
- * Returns the status line's HTTP minor version. This returns 0 for HTTP/1.0
- * and 1 for HTTP/1.1. This returns 1 if the HTTP version is unknown.
- */
- public int getHttpMinorVersion() {
- return httpMinorVersion != -1 ? httpMinorVersion : 1;
- }
-
- /** Returns the HTTP status code or -1 if it is unknown. */
- public int getResponseCode() {
- return responseCode;
- }
-
- /** Returns the HTTP status message or null if it is unknown. */
- public String getResponseMessage() {
- return responseMessage;
- }
-
- /**
- * Add an HTTP header line containing a field name, a literal colon, and a
- * value.
- */
- public void addLine(String line) {
- int index = line.indexOf(":");
- if (index == -1) {
- addLenient("", line);
- } else {
- addLenient(line.substring(0, index), line.substring(index + 1));
- }
- }
-
- /** Add a field with the specified value. */
- public void add(String fieldName, String value) {
- if (fieldName == null) throw new IllegalArgumentException("fieldname == null");
- if (value == null) throw new IllegalArgumentException("value == null");
- if (fieldName.length() == 0 || fieldName.indexOf('\0') != -1 || value.indexOf('\0') != -1) {
- throw new IllegalArgumentException("Unexpected header: " + fieldName + ": " + value);
- }
- addLenient(fieldName, value);
- }
-
- /**
- * Add a field with the specified value without any validation. Only
- * appropriate for headers from the remote peer.
- */
- private void addLenient(String fieldName, String value) {
- namesAndValues.add(fieldName);
- namesAndValues.add(value.trim());
- }
-
- public void removeAll(String fieldName) {
- for (int i = 0; i < namesAndValues.size(); i += 2) {
- if (fieldName.equalsIgnoreCase(namesAndValues.get(i))) {
- namesAndValues.remove(i); // field name
- namesAndValues.remove(i); // value
- }
- }
- }
-
- public void addAll(String fieldName, List<String> headerFields) {
- for (String value : headerFields) {
- add(fieldName, value);
- }
- }
-
- /**
- * Set a field with the specified value. If the field is not found, it is
- * added. If the field is found, the existing values are replaced.
- */
- public void set(String fieldName, String value) {
- removeAll(fieldName);
- add(fieldName, value);
- }
-
- /** Returns the number of field values. */
- public int length() {
- return namesAndValues.size() / 2;
- }
-
- /** Returns the field at {@code position} or null if that is out of range. */
- public String getFieldName(int index) {
- int fieldNameIndex = index * 2;
- if (fieldNameIndex < 0 || fieldNameIndex >= namesAndValues.size()) {
- return null;
- }
- return namesAndValues.get(fieldNameIndex);
- }
-
- /** Returns the value at {@code index} or null if that is out of range. */
- public String getValue(int index) {
- int valueIndex = index * 2 + 1;
- if (valueIndex < 0 || valueIndex >= namesAndValues.size()) {
- return null;
- }
- return namesAndValues.get(valueIndex);
- }
-
- /** Returns the last value corresponding to the specified field, or null. */
- public String get(String fieldName) {
- for (int i = namesAndValues.size() - 2; i >= 0; i -= 2) {
- if (fieldName.equalsIgnoreCase(namesAndValues.get(i))) {
- return namesAndValues.get(i + 1);
- }
- }
- return null;
- }
-
- /** @param fieldNames a case-insensitive set of HTTP header field names. */
- public RawHeaders getAll(Set<String> fieldNames) {
- RawHeaders result = new RawHeaders();
- for (int i = 0; i < namesAndValues.size(); i += 2) {
- String fieldName = namesAndValues.get(i);
- if (fieldNames.contains(fieldName)) {
- result.add(fieldName, namesAndValues.get(i + 1));
- }
- }
- return result;
- }
-
- /** Returns bytes of a request header for sending on an HTTP transport. */
- public byte[] toBytes() throws UnsupportedEncodingException {
- StringBuilder result = new StringBuilder(256);
- result.append(requestLine).append("\r\n");
- for (int i = 0; i < namesAndValues.size(); i += 2) {
- result.append(namesAndValues.get(i))
- .append(": ")
- .append(namesAndValues.get(i + 1))
- .append("\r\n");
- }
- result.append("\r\n");
- return result.toString().getBytes("ISO-8859-1");
- }
-
- /** Parses bytes of a response header from an HTTP transport. */
- public static RawHeaders fromBytes(InputStream in) throws IOException {
- RawHeaders headers;
- do {
- headers = new RawHeaders();
- headers.setStatusLine(Util.readAsciiLine(in));
- readHeaders(in, headers);
- } while (headers.getResponseCode() == HttpEngine.HTTP_CONTINUE);
- return headers;
- }
-
- /** Reads headers or trailers into {@code out}. */
- public static void readHeaders(InputStream in, RawHeaders out) throws IOException {
- // parse the result headers until the first blank line
- String line;
- while ((line = Util.readAsciiLine(in)).length() != 0) {
- out.addLine(line);
- }
- }
-
- /**
- * Returns an immutable map containing each field to its list of values. The
- * status line is mapped to null.
- */
- public Map<String, List<String>> toMultimap(boolean response) {
- Map<String, List<String>> result = new TreeMap<String, List<String>>(FIELD_NAME_COMPARATOR);
- for (int i = 0; i < namesAndValues.size(); i += 2) {
- String fieldName = namesAndValues.get(i);
- String value = namesAndValues.get(i + 1);
-
- List<String> allValues = new ArrayList<String>();
- List<String> otherValues = result.get(fieldName);
- if (otherValues != null) {
- allValues.addAll(otherValues);
- }
- allValues.add(value);
- result.put(fieldName, Collections.unmodifiableList(allValues));
- }
- if (response && statusLine != null) {
- result.put(null, Collections.unmodifiableList(Collections.singletonList(statusLine)));
- } else if (requestLine != null) {
- result.put(null, Collections.unmodifiableList(Collections.singletonList(requestLine)));
- }
- return Collections.unmodifiableMap(result);
- }
-
- /**
- * Creates a new instance from the given map of fields to values. If
- * present, the null field's last element will be used to set the status
- * line.
- */
- public static RawHeaders fromMultimap(Map<String, List<String>> map, boolean response)
- throws IOException {
- if (!response) throw new UnsupportedOperationException();
- RawHeaders result = new RawHeaders();
- for (Entry<String, List<String>> entry : map.entrySet()) {
- String fieldName = entry.getKey();
- List<String> values = entry.getValue();
- if (fieldName != null) {
- for (String value : values) {
- result.addLenient(fieldName, value);
- }
- } else if (!values.isEmpty()) {
- result.setStatusLine(values.get(values.size() - 1));
- }
- }
- return result;
- }
-
- /**
- * Returns a list of alternating names and values. Names are all lower case.
- * No names are repeated. If any name has multiple values, they are
- * concatenated using "\0" as a delimiter.
- */
- public List<String> toNameValueBlock() {
- Set<String> names = new HashSet<String>();
- List<String> result = new ArrayList<String>();
- for (int i = 0; i < namesAndValues.size(); i += 2) {
- String name = namesAndValues.get(i).toLowerCase(Locale.US);
- String value = namesAndValues.get(i + 1);
-
- // Drop headers that are forbidden when layering HTTP over SPDY.
- if (name.equals("connection")
- || name.equals("host")
- || name.equals("keep-alive")
- || name.equals("proxy-connection")
- || name.equals("transfer-encoding")) {
- continue;
- }
-
- // If we haven't seen this name before, add the pair to the end of the list...
- if (names.add(name)) {
- result.add(name);
- result.add(value);
- continue;
- }
-
- // ...otherwise concatenate the existing values and this value.
- for (int j = 0; j < result.size(); j += 2) {
- if (name.equals(result.get(j))) {
- result.set(j + 1, result.get(j + 1) + "\0" + value);
- break;
- }
- }
- }
- return result;
- }
-
- public static RawHeaders fromNameValueBlock(List<String> nameValueBlock) {
- if (nameValueBlock.size() % 2 != 0) {
- throw new IllegalArgumentException("Unexpected name value block: " + nameValueBlock);
- }
- RawHeaders result = new RawHeaders();
- for (int i = 0; i < nameValueBlock.size(); i += 2) {
- String name = nameValueBlock.get(i);
- String values = nameValueBlock.get(i + 1);
- for (int start = 0; start < values.length(); ) {
- int end = values.indexOf('\0', start);
- if (end == -1) {
- end = values.length();
- }
- result.namesAndValues.add(name);
- result.namesAndValues.add(values.substring(start, end));
- start = end + 1;
- }
- }
- return result;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/67fa7ebb/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RequestHeaders.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RequestHeaders.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RequestHeaders.java
deleted file mode 100644
index 5ec4fcc..0000000
--- a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RequestHeaders.java
+++ /dev/null
@@ -1,290 +0,0 @@
-/*
- * 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.http;
-
-import java.net.URI;
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-
-/** Parsed HTTP request headers. */
-public final class RequestHeaders {
- private final URI uri;
- private final RawHeaders headers;
-
- /** Don't use a cache to satisfy this request. */
- private boolean noCache;
- private int maxAgeSeconds = -1;
- private int maxStaleSeconds = -1;
- private int minFreshSeconds = -1;
-
- /**
- * This field's name "only-if-cached" is misleading. It actually means "do
- * not use the network". It is set by a client who only wants to make a
- * request if it can be fully satisfied by the cache. Cached responses that
- * would require validation (ie. conditional gets) are not permitted if this
- * header is set.
- */
- private boolean onlyIfCached;
-
- /**
- * True if the request contains an authorization field. Although this isn't
- * necessarily a shared cache, it follows the spec's strict requirements for
- * shared caches.
- */
- private boolean hasAuthorization;
-
- private int contentLength = -1;
- private String transferEncoding;
- private String userAgent;
- private String host;
- private String connection;
- private String acceptEncoding;
- private String contentType;
- private String ifModifiedSince;
- private String ifNoneMatch;
- private String proxyAuthorization;
-
- public RequestHeaders(URI uri, RawHeaders headers) {
- this.uri = uri;
- this.headers = headers;
-
- HeaderParser.CacheControlHandler handler = new HeaderParser.CacheControlHandler() {
- @Override public void handle(String directive, String parameter) {
- if ("no-cache".equalsIgnoreCase(directive)) {
- noCache = true;
- } else if ("max-age".equalsIgnoreCase(directive)) {
- maxAgeSeconds = HeaderParser.parseSeconds(parameter);
- } else if ("max-stale".equalsIgnoreCase(directive)) {
- maxStaleSeconds = HeaderParser.parseSeconds(parameter);
- } else if ("min-fresh".equalsIgnoreCase(directive)) {
- minFreshSeconds = HeaderParser.parseSeconds(parameter);
- } else if ("only-if-cached".equalsIgnoreCase(directive)) {
- onlyIfCached = true;
- }
- }
- };
-
- for (int i = 0; i < headers.length(); i++) {
- String fieldName = headers.getFieldName(i);
- String value = headers.getValue(i);
- if ("Cache-Control".equalsIgnoreCase(fieldName)) {
- HeaderParser.parseCacheControl(value, handler);
- } else if ("Pragma".equalsIgnoreCase(fieldName)) {
- if ("no-cache".equalsIgnoreCase(value)) {
- noCache = true;
- }
- } else if ("If-None-Match".equalsIgnoreCase(fieldName)) {
- ifNoneMatch = value;
- } else if ("If-Modified-Since".equalsIgnoreCase(fieldName)) {
- ifModifiedSince = value;
- } else if ("Authorization".equalsIgnoreCase(fieldName)) {
- hasAuthorization = true;
- } else if ("Content-Length".equalsIgnoreCase(fieldName)) {
- try {
- contentLength = Integer.parseInt(value);
- } catch (NumberFormatException ignored) {
- }
- } else if ("Transfer-Encoding".equalsIgnoreCase(fieldName)) {
- transferEncoding = value;
- } else if ("User-Agent".equalsIgnoreCase(fieldName)) {
- userAgent = value;
- } else if ("Host".equalsIgnoreCase(fieldName)) {
- host = value;
- } else if ("Connection".equalsIgnoreCase(fieldName)) {
- connection = value;
- } else if ("Accept-Encoding".equalsIgnoreCase(fieldName)) {
- acceptEncoding = value;
- } else if ("Content-Type".equalsIgnoreCase(fieldName)) {
- contentType = value;
- } else if ("Proxy-Authorization".equalsIgnoreCase(fieldName)) {
- proxyAuthorization = value;
- }
- }
- }
-
- public boolean isChunked() {
- return "chunked".equalsIgnoreCase(transferEncoding);
- }
-
- public boolean hasConnectionClose() {
- return "close".equalsIgnoreCase(connection);
- }
-
- public URI getUri() {
- return uri;
- }
-
- public RawHeaders getHeaders() {
- return headers;
- }
-
- public boolean isNoCache() {
- return noCache;
- }
-
- public int getMaxAgeSeconds() {
- return maxAgeSeconds;
- }
-
- public int getMaxStaleSeconds() {
- return maxStaleSeconds;
- }
-
- public int getMinFreshSeconds() {
- return minFreshSeconds;
- }
-
- public boolean isOnlyIfCached() {
- return onlyIfCached;
- }
-
- public boolean hasAuthorization() {
- return hasAuthorization;
- }
-
- public int getContentLength() {
- return contentLength;
- }
-
- public String getTransferEncoding() {
- return transferEncoding;
- }
-
- public String getUserAgent() {
- return userAgent;
- }
-
- public String getHost() {
- return host;
- }
-
- public String getConnection() {
- return connection;
- }
-
- public String getAcceptEncoding() {
- return acceptEncoding;
- }
-
- public String getContentType() {
- return contentType;
- }
-
- public String getIfModifiedSince() {
- return ifModifiedSince;
- }
-
- public String getIfNoneMatch() {
- return ifNoneMatch;
- }
-
- public String getProxyAuthorization() {
- return proxyAuthorization;
- }
-
- public void setChunked() {
- if (this.transferEncoding != null) {
- headers.removeAll("Transfer-Encoding");
- }
- headers.add("Transfer-Encoding", "chunked");
- this.transferEncoding = "chunked";
- }
-
- public void setContentLength(int contentLength) {
- if (this.contentLength != -1) {
- headers.removeAll("Content-Length");
- }
- headers.add("Content-Length", Integer.toString(contentLength));
- this.contentLength = contentLength;
- }
-
- public void setUserAgent(String userAgent) {
- if (this.userAgent != null) {
- headers.removeAll("User-Agent");
- }
- headers.add("User-Agent", userAgent);
- this.userAgent = userAgent;
- }
-
- public void setHost(String host) {
- if (this.host != null) {
- headers.removeAll("Host");
- }
- headers.add("Host", host);
- this.host = host;
- }
-
- public void setConnection(String connection) {
- if (this.connection != null) {
- headers.removeAll("Connection");
- }
- headers.add("Connection", connection);
- this.connection = connection;
- }
-
- public void setAcceptEncoding(String acceptEncoding) {
- if (this.acceptEncoding != null) {
- headers.removeAll("Accept-Encoding");
- }
- headers.add("Accept-Encoding", acceptEncoding);
- this.acceptEncoding = acceptEncoding;
- }
-
- public void setContentType(String contentType) {
- if (this.contentType != null) {
- headers.removeAll("Content-Type");
- }
- headers.add("Content-Type", contentType);
- this.contentType = contentType;
- }
-
- public void setIfModifiedSince(Date date) {
- if (ifModifiedSince != null) {
- headers.removeAll("If-Modified-Since");
- }
- String formattedDate = HttpDate.format(date);
- headers.add("If-Modified-Since", formattedDate);
- ifModifiedSince = formattedDate;
- }
-
- public void setIfNoneMatch(String ifNoneMatch) {
- if (this.ifNoneMatch != null) {
- headers.removeAll("If-None-Match");
- }
- headers.add("If-None-Match", ifNoneMatch);
- this.ifNoneMatch = ifNoneMatch;
- }
-
- /**
- * Returns true if the request contains conditions that save the server from
- * sending a response that the client has locally. When the caller adds
- * conditions, this cache won't participate in the request.
- */
- public boolean hasConditions() {
- return ifModifiedSince != null || ifNoneMatch != null;
- }
-
- public void addCookies(Map<String, List<String>> allCookieHeaders) {
- for (Map.Entry<String, List<String>> entry : allCookieHeaders.entrySet()) {
- String key = entry.getKey();
- if ("Cookie".equalsIgnoreCase(key) || "Cookie2".equalsIgnoreCase(key)) {
- headers.addAll(key, entry.getValue());
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/67fa7ebb/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/ResponseHeaders.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/ResponseHeaders.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/ResponseHeaders.java
deleted file mode 100644
index 2ab564d..0000000
--- a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/ResponseHeaders.java
+++ /dev/null
@@ -1,497 +0,0 @@
-/*
- * 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.http;
-
-import com.squareup.okhttp.ResponseSource;
-import java.io.IOException;
-import java.net.HttpURLConnection;
-import java.net.URI;
-import java.util.Collections;
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-import java.util.concurrent.TimeUnit;
-
-import static com.squareup.okhttp.internal.Util.equal;
-
-/** Parsed HTTP response headers. */
-public final class ResponseHeaders {
-
- /** HTTP header name for the local time when the request was sent. */
- private static final String SENT_MILLIS = "X-Android-Sent-Millis";
-
- /** HTTP header name for the local time when the response was received. */
- private static final String RECEIVED_MILLIS = "X-Android-Received-Millis";
-
- /** HTTP synthetic header with the response source. */
- static final String RESPONSE_SOURCE = "X-Android-Response-Source";
-
- private final URI uri;
- private final RawHeaders headers;
-
- /** The server's time when this response was served, if known. */
- private Date servedDate;
-
- /** The last modified date of the response, if known. */
- private Date lastModified;
-
- /**
- * The expiration date of the response, if known. If both this field and the
- * max age are set, the max age is preferred.
- */
- private Date expires;
-
- /**
- * Extension header set by HttpURLConnectionImpl specifying the timestamp
- * when the HTTP request was first initiated.
- */
- private long sentRequestMillis;
-
- /**
- * Extension header set by HttpURLConnectionImpl specifying the timestamp
- * when the HTTP response was first received.
- */
- private long receivedResponseMillis;
-
- /**
- * In the response, this field's name "no-cache" is misleading. It doesn't
- * prevent us from caching the response; it only means we have to validate
- * the response with the origin server before returning it. We can do this
- * with a conditional get.
- */
- private boolean noCache;
-
- /** If true, this response should not be cached. */
- private boolean noStore;
-
- /**
- * The duration past the response's served date that it can be served
- * without validation.
- */
- private int maxAgeSeconds = -1;
-
- /**
- * The "s-maxage" directive is the max age for shared caches. Not to be
- * confused with "max-age" for non-shared caches, As in Firefox and Chrome,
- * this directive is not honored by this cache.
- */
- private int sMaxAgeSeconds = -1;
-
- /**
- * This request header field's name "only-if-cached" is misleading. It
- * actually means "do not use the network". It is set by a client who only
- * wants to make a request if it can be fully satisfied by the cache.
- * Cached responses that would require validation (ie. conditional gets) are
- * not permitted if this header is set.
- */
- private boolean isPublic;
- private boolean mustRevalidate;
- private String etag;
- private int ageSeconds = -1;
-
- /** Case-insensitive set of field names. */
- private Set<String> varyFields = Collections.emptySet();
-
- private String contentEncoding;
- private String transferEncoding;
- private int contentLength = -1;
- private String connection;
-
- public ResponseHeaders(URI uri, RawHeaders headers) {
- this.uri = uri;
- this.headers = headers;
-
- HeaderParser.CacheControlHandler handler = new HeaderParser.CacheControlHandler() {
- @Override public void handle(String directive, String parameter) {
- if ("no-cache".equalsIgnoreCase(directive)) {
- noCache = true;
- } else if ("no-store".equalsIgnoreCase(directive)) {
- noStore = true;
- } else if ("max-age".equalsIgnoreCase(directive)) {
- maxAgeSeconds = HeaderParser.parseSeconds(parameter);
- } else if ("s-maxage".equalsIgnoreCase(directive)) {
- sMaxAgeSeconds = HeaderParser.parseSeconds(parameter);
- } else if ("public".equalsIgnoreCase(directive)) {
- isPublic = true;
- } else if ("must-revalidate".equalsIgnoreCase(directive)) {
- mustRevalidate = true;
- }
- }
- };
-
- for (int i = 0; i < headers.length(); i++) {
- String fieldName = headers.getFieldName(i);
- String value = headers.getValue(i);
- if ("Cache-Control".equalsIgnoreCase(fieldName)) {
- HeaderParser.parseCacheControl(value, handler);
- } else if ("Date".equalsIgnoreCase(fieldName)) {
- servedDate = HttpDate.parse(value);
- } else if ("Expires".equalsIgnoreCase(fieldName)) {
- expires = HttpDate.parse(value);
- } else if ("Last-Modified".equalsIgnoreCase(fieldName)) {
- lastModified = HttpDate.parse(value);
- } else if ("ETag".equalsIgnoreCase(fieldName)) {
- etag = value;
- } else if ("Pragma".equalsIgnoreCase(fieldName)) {
- if ("no-cache".equalsIgnoreCase(value)) {
- noCache = true;
- }
- } else if ("Age".equalsIgnoreCase(fieldName)) {
- ageSeconds = HeaderParser.parseSeconds(value);
- } else if ("Vary".equalsIgnoreCase(fieldName)) {
- // Replace the immutable empty set with something we can mutate.
- if (varyFields.isEmpty()) {
- varyFields = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
- }
- for (String varyField : value.split(",")) {
- varyFields.add(varyField.trim());
- }
- } else if ("Content-Encoding".equalsIgnoreCase(fieldName)) {
- contentEncoding = value;
- } else if ("Transfer-Encoding".equalsIgnoreCase(fieldName)) {
- transferEncoding = value;
- } else if ("Content-Length".equalsIgnoreCase(fieldName)) {
- try {
- contentLength = Integer.parseInt(value);
- } catch (NumberFormatException ignored) {
- }
- } else if ("Connection".equalsIgnoreCase(fieldName)) {
- connection = value;
- } else if (SENT_MILLIS.equalsIgnoreCase(fieldName)) {
- sentRequestMillis = Long.parseLong(value);
- } else if (RECEIVED_MILLIS.equalsIgnoreCase(fieldName)) {
- receivedResponseMillis = Long.parseLong(value);
- }
- }
- }
-
- public boolean isContentEncodingGzip() {
- return "gzip".equalsIgnoreCase(contentEncoding);
- }
-
- public void stripContentEncoding() {
- contentEncoding = null;
- headers.removeAll("Content-Encoding");
- }
-
- public void stripContentLength() {
- contentLength = -1;
- headers.removeAll("Content-Length");
- }
-
- public boolean isChunked() {
- return "chunked".equalsIgnoreCase(transferEncoding);
- }
-
- public boolean hasConnectionClose() {
- return "close".equalsIgnoreCase(connection);
- }
-
- public URI getUri() {
- return uri;
- }
-
- public RawHeaders getHeaders() {
- return headers;
- }
-
- public Date getServedDate() {
- return servedDate;
- }
-
- public Date getLastModified() {
- return lastModified;
- }
-
- public Date getExpires() {
- return expires;
- }
-
- public boolean isNoCache() {
- return noCache;
- }
-
- public boolean isNoStore() {
- return noStore;
- }
-
- public int getMaxAgeSeconds() {
- return maxAgeSeconds;
- }
-
- public int getSMaxAgeSeconds() {
- return sMaxAgeSeconds;
- }
-
- public boolean isPublic() {
- return isPublic;
- }
-
- public boolean isMustRevalidate() {
- return mustRevalidate;
- }
-
- public String getEtag() {
- return etag;
- }
-
- public Set<String> getVaryFields() {
- return varyFields;
- }
-
- public String getContentEncoding() {
- return contentEncoding;
- }
-
- public int getContentLength() {
- return contentLength;
- }
-
- public String getConnection() {
- return connection;
- }
-
- public void setLocalTimestamps(long sentRequestMillis, long receivedResponseMillis) {
- this.sentRequestMillis = sentRequestMillis;
- headers.add(SENT_MILLIS, Long.toString(sentRequestMillis));
- this.receivedResponseMillis = receivedResponseMillis;
- headers.add(RECEIVED_MILLIS, Long.toString(receivedResponseMillis));
- }
-
- public void setResponseSource(ResponseSource responseSource) {
- headers.set(RESPONSE_SOURCE, responseSource.toString() + " " + headers.getResponseCode());
- }
-
- /**
- * Returns the current age of the response, in milliseconds. The calculation
- * is specified by RFC 2616, 13.2.3 Age Calculations.
- */
- private long computeAge(long nowMillis) {
- long apparentReceivedAge =
- servedDate != null ? Math.max(0, receivedResponseMillis - servedDate.getTime()) : 0;
- long receivedAge =
- ageSeconds != -1 ? Math.max(apparentReceivedAge, TimeUnit.SECONDS.toMillis(ageSeconds))
- : apparentReceivedAge;
- long responseDuration = receivedResponseMillis - sentRequestMillis;
- long residentDuration = nowMillis - receivedResponseMillis;
- return receivedAge + responseDuration + residentDuration;
- }
-
- /**
- * Returns the number of milliseconds that the response was fresh for,
- * starting from the served date.
- */
- private long computeFreshnessLifetime() {
- if (maxAgeSeconds != -1) {
- return TimeUnit.SECONDS.toMillis(maxAgeSeconds);
- } else if (expires != null) {
- long servedMillis = servedDate != null ? servedDate.getTime() : receivedResponseMillis;
- long delta = expires.getTime() - servedMillis;
- return delta > 0 ? delta : 0;
- } else if (lastModified != null && uri.getRawQuery() == null) {
- // As recommended by the HTTP RFC and implemented in Firefox, the
- // max age of a document should be defaulted to 10% of the
- // document's age at the time it was served. Default expiration
- // dates aren't used for URIs containing a query.
- long servedMillis = servedDate != null ? servedDate.getTime() : sentRequestMillis;
- long delta = servedMillis - lastModified.getTime();
- return delta > 0 ? (delta / 10) : 0;
- }
- return 0;
- }
-
- /**
- * Returns true if computeFreshnessLifetime used a heuristic. If we used a
- * heuristic to serve a cached response older than 24 hours, we are required
- * to attach a warning.
- */
- private boolean isFreshnessLifetimeHeuristic() {
- return maxAgeSeconds == -1 && expires == null;
- }
-
- /**
- * Returns true if this response can be stored to later serve another
- * request.
- */
- public boolean isCacheable(RequestHeaders request) {
- // Always go to network for uncacheable response codes (RFC 2616, 13.4),
- // This implementation doesn't support caching partial content.
- int responseCode = headers.getResponseCode();
- if (responseCode != HttpURLConnection.HTTP_OK
- && responseCode != HttpURLConnection.HTTP_NOT_AUTHORITATIVE
- && responseCode != HttpURLConnection.HTTP_MULT_CHOICE
- && responseCode != HttpURLConnection.HTTP_MOVED_PERM
- && responseCode != HttpURLConnection.HTTP_GONE) {
- return false;
- }
-
- // Responses to authorized requests aren't cacheable unless they include
- // a 'public', 'must-revalidate' or 's-maxage' directive.
- if (request.hasAuthorization() && !isPublic && !mustRevalidate && sMaxAgeSeconds == -1) {
- return false;
- }
-
- if (noStore) {
- return false;
- }
-
- return true;
- }
-
- /**
- * Returns true if a Vary header contains an asterisk. Such responses cannot
- * be cached.
- */
- public boolean hasVaryAll() {
- return varyFields.contains("*");
- }
-
- /**
- * Returns true if none of the Vary headers on this response have changed
- * between {@code cachedRequest} and {@code newRequest}.
- */
- public boolean varyMatches(Map<String, List<String>> cachedRequest,
- Map<String, List<String>> newRequest) {
- for (String field : varyFields) {
- if (!equal(cachedRequest.get(field), newRequest.get(field))) {
- return false;
- }
- }
- return true;
- }
-
- /** Returns the source to satisfy {@code request} given this cached response. */
- public ResponseSource chooseResponseSource(long nowMillis, RequestHeaders request) {
- // If this response shouldn't have been stored, it should never be used
- // as a response source. This check should be redundant as long as the
- // persistence store is well-behaved and the rules are constant.
- if (!isCacheable(request)) {
- return ResponseSource.NETWORK;
- }
-
- if (request.isNoCache() || request.hasConditions()) {
- return ResponseSource.NETWORK;
- }
-
- long ageMillis = computeAge(nowMillis);
- long freshMillis = computeFreshnessLifetime();
-
- if (request.getMaxAgeSeconds() != -1) {
- freshMillis = Math.min(freshMillis, TimeUnit.SECONDS.toMillis(request.getMaxAgeSeconds()));
- }
-
- long minFreshMillis = 0;
- if (request.getMinFreshSeconds() != -1) {
- minFreshMillis = TimeUnit.SECONDS.toMillis(request.getMinFreshSeconds());
- }
-
- long maxStaleMillis = 0;
- if (!mustRevalidate && request.getMaxStaleSeconds() != -1) {
- maxStaleMillis = TimeUnit.SECONDS.toMillis(request.getMaxStaleSeconds());
- }
-
- if (!noCache && ageMillis + minFreshMillis < freshMillis + maxStaleMillis) {
- if (ageMillis + minFreshMillis >= freshMillis) {
- headers.add("Warning", "110 HttpURLConnection \"Response is stale\"");
- }
- long oneDayMillis = 24 * 60 * 60 * 1000L;
- if (ageMillis > oneDayMillis && isFreshnessLifetimeHeuristic()) {
- headers.add("Warning", "113 HttpURLConnection \"Heuristic expiration\"");
- }
- return ResponseSource.CACHE;
- }
-
- if (lastModified != null) {
- request.setIfModifiedSince(lastModified);
- } else if (servedDate != null) {
- request.setIfModifiedSince(servedDate);
- }
-
- if (etag != null) {
- request.setIfNoneMatch(etag);
- }
-
- return request.hasConditions() ? ResponseSource.CONDITIONAL_CACHE : ResponseSource.NETWORK;
- }
-
- /**
- * Returns true if this cached response should be used; false if the
- * network response should be used.
- */
- public boolean validate(ResponseHeaders networkResponse) {
- if (networkResponse.headers.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
- return true;
- }
-
- // The HTTP spec says that if the network's response is older than our
- // cached response, we may return the cache's response. Like Chrome (but
- // unlike Firefox), this client prefers to return the newer response.
- if (lastModified != null
- && networkResponse.lastModified != null
- && networkResponse.lastModified.getTime() < lastModified.getTime()) {
- return true;
- }
-
- return false;
- }
-
- /**
- * Combines this cached header with a network header as defined by RFC 2616,
- * 13.5.3.
- */
- public ResponseHeaders combine(ResponseHeaders network) throws IOException {
- RawHeaders result = new RawHeaders();
- result.setStatusLine(headers.getStatusLine());
-
- for (int i = 0; i < headers.length(); i++) {
- String fieldName = headers.getFieldName(i);
- String value = headers.getValue(i);
- if ("Warning".equals(fieldName) && value.startsWith("1")) {
- continue; // drop 100-level freshness warnings
- }
- if (!isEndToEnd(fieldName) || network.headers.get(fieldName) == null) {
- result.add(fieldName, value);
- }
- }
-
- for (int i = 0; i < network.headers.length(); i++) {
- String fieldName = network.headers.getFieldName(i);
- if (isEndToEnd(fieldName)) {
- result.add(fieldName, network.headers.getValue(i));
- }
- }
-
- return new ResponseHeaders(uri, result);
- }
-
- /**
- * Returns true if {@code fieldName} is an end-to-end HTTP header, as
- * defined by RFC 2616, 13.5.1.
- */
- private static boolean isEndToEnd(String fieldName) {
- return !"Connection".equalsIgnoreCase(fieldName)
- && !"Keep-Alive".equalsIgnoreCase(fieldName)
- && !"Proxy-Authenticate".equalsIgnoreCase(fieldName)
- && !"Proxy-Authorization".equalsIgnoreCase(fieldName)
- && !"TE".equalsIgnoreCase(fieldName)
- && !"Trailers".equalsIgnoreCase(fieldName)
- && !"Transfer-Encoding".equalsIgnoreCase(fieldName)
- && !"Upgrade".equalsIgnoreCase(fieldName);
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-cli/blob/67fa7ebb/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RetryableOutputStream.java
----------------------------------------------------------------------
diff --git a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RetryableOutputStream.java b/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RetryableOutputStream.java
deleted file mode 100644
index 5eb6b76..0000000
--- a/lib/cordova-android/framework/src/com/squareup/okhttp/internal/http/RetryableOutputStream.java
+++ /dev/null
@@ -1,75 +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.internal.http;
-
-import com.squareup.okhttp.internal.AbstractOutputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.net.ProtocolException;
-
-import static com.squareup.okhttp.internal.Util.checkOffsetAndCount;
-
-/**
- * An HTTP request body that's completely buffered in memory. This allows
- * the post body to be transparently re-sent if the HTTP request must be
- * sent multiple times.
- */
-final class RetryableOutputStream extends AbstractOutputStream {
- private final int limit;
- private final ByteArrayOutputStream content;
-
- public RetryableOutputStream(int limit) {
- this.limit = limit;
- this.content = new ByteArrayOutputStream(limit);
- }
-
- public RetryableOutputStream() {
- this.limit = -1;
- this.content = new ByteArrayOutputStream();
- }
-
- @Override public synchronized void close() throws IOException {
- if (closed) {
- return;
- }
- closed = true;
- if (content.size() < limit) {
- throw new ProtocolException(
- "content-length promised " + limit + " bytes, but received " + content.size());
- }
- }
-
- @Override public synchronized void write(byte[] buffer, int offset, int count)
- throws IOException {
- checkNotClosed();
- checkOffsetAndCount(buffer.length, offset, count);
- if (limit != -1 && content.size() > limit - count) {
- throw new ProtocolException("exceeded content-length limit of " + limit + " bytes");
- }
- content.write(buffer, offset, count);
- }
-
- public synchronized int contentLength() throws IOException {
- close();
- return content.size();
- }
-
- public void writeToSocket(OutputStream socketOut) throws IOException {
- content.writeTo(socketOut);
- }
-}