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:12 UTC
[09/12] android commit: CB-6630 Delete bundled (and outdated) copy of
OkHttp
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/c6b171ba/framework/src/com/squareup/okhttp/internal/http/HttpTransport.java
----------------------------------------------------------------------
diff --git a/framework/src/com/squareup/okhttp/internal/http/HttpTransport.java b/framework/src/com/squareup/okhttp/internal/http/HttpTransport.java
deleted file mode 100755
index c967830..0000000
--- a/framework/src/com/squareup/okhttp/internal/http/HttpTransport.java
+++ /dev/null
@@ -1,497 +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.internal.http;
-
-import com.squareup.okhttp.Connection;
-import com.squareup.okhttp.internal.AbstractOutputStream;
-import com.squareup.okhttp.internal.Util;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.CacheRequest;
-import java.net.ProtocolException;
-import java.net.Socket;
-
-import static com.squareup.okhttp.internal.Util.checkOffsetAndCount;
-
-public final class HttpTransport implements Transport {
- /**
- * The timeout to use while discarding a stream of input data. Since this is
- * used for connection reuse, this timeout should be significantly less than
- * the time it takes to establish a new connection.
- */
- private static final int DISCARD_STREAM_TIMEOUT_MILLIS = 100;
-
- public static final int DEFAULT_CHUNK_LENGTH = 1024;
-
- private final HttpEngine httpEngine;
- private final InputStream socketIn;
- private final OutputStream socketOut;
-
- /**
- * This stream buffers the request headers and the request body when their
- * combined size is less than MAX_REQUEST_BUFFER_LENGTH. By combining them
- * we can save socket writes, which in turn saves a packet transmission.
- * This is socketOut if the request size is large or unknown.
- */
- private OutputStream requestOut;
-
- public HttpTransport(HttpEngine httpEngine, OutputStream outputStream, InputStream inputStream) {
- this.httpEngine = httpEngine;
- this.socketOut = outputStream;
- this.requestOut = outputStream;
- this.socketIn = inputStream;
- }
-
- @Override public OutputStream createRequestBody() throws IOException {
- boolean chunked = httpEngine.requestHeaders.isChunked();
- if (!chunked
- && httpEngine.policy.getChunkLength() > 0
- && httpEngine.connection.getHttpMinorVersion() != 0) {
- httpEngine.requestHeaders.setChunked();
- chunked = true;
- }
-
- // Stream a request body of unknown length.
- if (chunked) {
- int chunkLength = httpEngine.policy.getChunkLength();
- if (chunkLength == -1) {
- chunkLength = DEFAULT_CHUNK_LENGTH;
- }
- writeRequestHeaders();
- return new ChunkedOutputStream(requestOut, chunkLength);
- }
-
- // Stream a request body of a known length.
- long fixedContentLength = httpEngine.policy.getFixedContentLength();
- if (fixedContentLength != -1) {
- httpEngine.requestHeaders.setContentLength(fixedContentLength);
- writeRequestHeaders();
- return new FixedLengthOutputStream(requestOut, fixedContentLength);
- }
-
- long contentLength = httpEngine.requestHeaders.getContentLength();
- if (contentLength > Integer.MAX_VALUE) {
- throw new IllegalArgumentException("Use setFixedLengthStreamingMode() or "
- + "setChunkedStreamingMode() for requests larger than 2 GiB.");
- }
-
- // Buffer a request body of a known length.
- if (contentLength != -1) {
- writeRequestHeaders();
- return new RetryableOutputStream((int) contentLength);
- }
-
- // Buffer a request body of an unknown length. Don't write request
- // headers until the entire body is ready; otherwise we can't set the
- // Content-Length header correctly.
- return new RetryableOutputStream();
- }
-
- @Override public void flushRequest() throws IOException {
- requestOut.flush();
- requestOut = socketOut;
- }
-
- @Override public void writeRequestBody(RetryableOutputStream requestBody) throws IOException {
- requestBody.writeToSocket(requestOut);
- }
-
- /**
- * Prepares the HTTP headers and sends them to the server.
- *
- * <p>For streaming requests with a body, headers must be prepared
- * <strong>before</strong> the output stream has been written to. Otherwise
- * the body would need to be buffered!
- *
- * <p>For non-streaming requests with a body, headers must be prepared
- * <strong>after</strong> the output stream has been written to and closed.
- * This ensures that the {@code Content-Length} header field receives the
- * proper value.
- */
- public void writeRequestHeaders() throws IOException {
- httpEngine.writingRequestHeaders();
- RawHeaders headersToSend = httpEngine.requestHeaders.getHeaders();
- byte[] bytes = headersToSend.toBytes();
- requestOut.write(bytes);
- }
-
- @Override public ResponseHeaders readResponseHeaders() throws IOException {
- RawHeaders rawHeaders = RawHeaders.fromBytes(socketIn);
- httpEngine.connection.setHttpMinorVersion(rawHeaders.getHttpMinorVersion());
- httpEngine.receiveHeaders(rawHeaders);
-
- ResponseHeaders headers = new ResponseHeaders(httpEngine.uri, rawHeaders);
- headers.setTransport("http/1.1");
- return headers;
- }
-
- public boolean makeReusable(boolean streamCanceled, OutputStream requestBodyOut,
- InputStream responseBodyIn) {
- if (streamCanceled) {
- return false;
- }
-
- // We cannot reuse sockets that have incomplete output.
- if (requestBodyOut != null && !((AbstractOutputStream) requestBodyOut).isClosed()) {
- return false;
- }
-
- // If the request specified that the connection shouldn't be reused, don't reuse it.
- if (httpEngine.requestHeaders.hasConnectionClose()) {
- return false;
- }
-
- // If the response specified that the connection shouldn't be reused, don't reuse it.
- if (httpEngine.responseHeaders != null && httpEngine.responseHeaders.hasConnectionClose()) {
- return false;
- }
-
- if (responseBodyIn instanceof UnknownLengthHttpInputStream) {
- return false;
- }
-
- if (responseBodyIn != null) {
- return discardStream(httpEngine, responseBodyIn);
- }
-
- return true;
- }
-
- /**
- * Discards the response body so that the connection can be reused. This
- * needs to be done judiciously, since it delays the current request in
- * order to speed up a potential future request that may never occur.
- *
- * <p>A stream may be discarded to encourage response caching (a response
- * cannot be cached unless it is consumed completely) or to enable connection
- * reuse.
- */
- private static boolean discardStream(HttpEngine httpEngine, InputStream responseBodyIn) {
- Connection connection = httpEngine.connection;
- if (connection == null) return false;
- Socket socket = connection.getSocket();
- if (socket == null) return false;
- try {
- int socketTimeout = socket.getSoTimeout();
- socket.setSoTimeout(DISCARD_STREAM_TIMEOUT_MILLIS);
- try {
- Util.skipAll(responseBodyIn);
- return true;
- } finally {
- socket.setSoTimeout(socketTimeout);
- }
- } catch (IOException e) {
- return false;
- }
- }
-
- @Override public InputStream getTransferStream(CacheRequest cacheRequest) throws IOException {
- if (!httpEngine.hasResponseBody()) {
- return new FixedLengthInputStream(socketIn, cacheRequest, httpEngine, 0);
- }
-
- if (httpEngine.responseHeaders.isChunked()) {
- return new ChunkedInputStream(socketIn, cacheRequest, this);
- }
-
- if (httpEngine.responseHeaders.getContentLength() != -1) {
- return new FixedLengthInputStream(socketIn, cacheRequest, httpEngine,
- httpEngine.responseHeaders.getContentLength());
- }
-
- // Wrap the input stream from the connection (rather than just returning
- // "socketIn" directly here), so that we can control its use after the
- // reference escapes.
- return new UnknownLengthHttpInputStream(socketIn, cacheRequest, httpEngine);
- }
-
- /** An HTTP body with a fixed length known in advance. */
- private static final class FixedLengthOutputStream extends AbstractOutputStream {
- private final OutputStream socketOut;
- private long bytesRemaining;
-
- private FixedLengthOutputStream(OutputStream socketOut, long bytesRemaining) {
- this.socketOut = socketOut;
- this.bytesRemaining = bytesRemaining;
- }
-
- @Override public void write(byte[] buffer, int offset, int count) throws IOException {
- checkNotClosed();
- checkOffsetAndCount(buffer.length, offset, count);
- if (count > bytesRemaining) {
- throw new ProtocolException("expected " + bytesRemaining + " bytes but received " + count);
- }
- socketOut.write(buffer, offset, count);
- bytesRemaining -= count;
- }
-
- @Override public void flush() throws IOException {
- if (closed) {
- return; // don't throw; this stream might have been closed on the caller's behalf
- }
- socketOut.flush();
- }
-
- @Override public void close() throws IOException {
- if (closed) {
- return;
- }
- closed = true;
- if (bytesRemaining > 0) {
- throw new ProtocolException("unexpected end of stream");
- }
- }
- }
-
- /**
- * An HTTP body with alternating chunk sizes and chunk bodies. Chunks are
- * buffered until {@code maxChunkLength} bytes are ready, at which point the
- * chunk is written and the buffer is cleared.
- */
- private static final class ChunkedOutputStream extends AbstractOutputStream {
- private static final byte[] CRLF = { '\r', '\n' };
- private static final byte[] HEX_DIGITS = {
- '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
- };
- private static final byte[] FINAL_CHUNK = new byte[] { '0', '\r', '\n', '\r', '\n' };
-
- /** Scratch space for up to 8 hex digits, and then a constant CRLF. */
- private final byte[] hex = { 0, 0, 0, 0, 0, 0, 0, 0, '\r', '\n' };
-
- private final OutputStream socketOut;
- private final int maxChunkLength;
- private final ByteArrayOutputStream bufferedChunk;
-
- private ChunkedOutputStream(OutputStream socketOut, int maxChunkLength) {
- this.socketOut = socketOut;
- this.maxChunkLength = Math.max(1, dataLength(maxChunkLength));
- this.bufferedChunk = new ByteArrayOutputStream(maxChunkLength);
- }
-
- /**
- * Returns the amount of data that can be transmitted in a chunk whose total
- * length (data+headers) is {@code dataPlusHeaderLength}. This is presumably
- * useful to match sizes with wire-protocol packets.
- */
- private int dataLength(int dataPlusHeaderLength) {
- int headerLength = 4; // "\r\n" after the size plus another "\r\n" after the data
- for (int i = dataPlusHeaderLength - headerLength; i > 0; i >>= 4) {
- headerLength++;
- }
- return dataPlusHeaderLength - headerLength;
- }
-
- @Override public synchronized void write(byte[] buffer, int offset, int count)
- throws IOException {
- checkNotClosed();
- checkOffsetAndCount(buffer.length, offset, count);
-
- while (count > 0) {
- int numBytesWritten;
-
- if (bufferedChunk.size() > 0 || count < maxChunkLength) {
- // fill the buffered chunk and then maybe write that to the stream
- numBytesWritten = Math.min(count, maxChunkLength - bufferedChunk.size());
- // TODO: skip unnecessary copies from buffer->bufferedChunk?
- bufferedChunk.write(buffer, offset, numBytesWritten);
- if (bufferedChunk.size() == maxChunkLength) {
- writeBufferedChunkToSocket();
- }
- } else {
- // write a single chunk of size maxChunkLength to the stream
- numBytesWritten = maxChunkLength;
- writeHex(numBytesWritten);
- socketOut.write(buffer, offset, numBytesWritten);
- socketOut.write(CRLF);
- }
-
- offset += numBytesWritten;
- count -= numBytesWritten;
- }
- }
-
- /**
- * Equivalent to, but cheaper than writing Integer.toHexString().getBytes()
- * followed by CRLF.
- */
- private void writeHex(int i) throws IOException {
- int cursor = 8;
- do {
- hex[--cursor] = HEX_DIGITS[i & 0xf];
- } while ((i >>>= 4) != 0);
- socketOut.write(hex, cursor, hex.length - cursor);
- }
-
- @Override public synchronized void flush() throws IOException {
- if (closed) {
- return; // don't throw; this stream might have been closed on the caller's behalf
- }
- writeBufferedChunkToSocket();
- socketOut.flush();
- }
-
- @Override public synchronized void close() throws IOException {
- if (closed) {
- return;
- }
- closed = true;
- writeBufferedChunkToSocket();
- socketOut.write(FINAL_CHUNK);
- }
-
- private void writeBufferedChunkToSocket() throws IOException {
- int size = bufferedChunk.size();
- if (size <= 0) {
- return;
- }
-
- writeHex(size);
- bufferedChunk.writeTo(socketOut);
- bufferedChunk.reset();
- socketOut.write(CRLF);
- }
- }
-
- /** An HTTP body with a fixed length specified in advance. */
- private static class FixedLengthInputStream extends AbstractHttpInputStream {
- private long bytesRemaining;
-
- public FixedLengthInputStream(InputStream is, CacheRequest cacheRequest, HttpEngine httpEngine,
- long length) throws IOException {
- super(is, httpEngine, cacheRequest);
- bytesRemaining = length;
- if (bytesRemaining == 0) {
- endOfInput();
- }
- }
-
- @Override public int read(byte[] buffer, int offset, int count) throws IOException {
- checkOffsetAndCount(buffer.length, offset, count);
- checkNotClosed();
- if (bytesRemaining == 0) {
- return -1;
- }
- int read = in.read(buffer, offset, (int) Math.min(count, bytesRemaining));
- if (read == -1) {
- unexpectedEndOfInput(); // the server didn't supply the promised content length
- throw new ProtocolException("unexpected end of stream");
- }
- bytesRemaining -= read;
- cacheWrite(buffer, offset, read);
- if (bytesRemaining == 0) {
- endOfInput();
- }
- return read;
- }
-
- @Override public int available() throws IOException {
- checkNotClosed();
- return bytesRemaining == 0 ? 0 : (int) Math.min(in.available(), bytesRemaining);
- }
-
- @Override public void close() throws IOException {
- if (closed) {
- return;
- }
- if (bytesRemaining != 0 && !discardStream(httpEngine, this)) {
- unexpectedEndOfInput();
- }
- closed = true;
- }
- }
-
- /** An HTTP body with alternating chunk sizes and chunk bodies. */
- private static class ChunkedInputStream extends AbstractHttpInputStream {
- private static final int NO_CHUNK_YET = -1;
- private final HttpTransport transport;
- private int bytesRemainingInChunk = NO_CHUNK_YET;
- private boolean hasMoreChunks = true;
-
- ChunkedInputStream(InputStream is, CacheRequest cacheRequest, HttpTransport transport)
- throws IOException {
- super(is, transport.httpEngine, cacheRequest);
- this.transport = transport;
- }
-
- @Override public int read(byte[] buffer, int offset, int count) throws IOException {
- checkOffsetAndCount(buffer.length, offset, count);
- checkNotClosed();
-
- if (!hasMoreChunks) {
- return -1;
- }
- if (bytesRemainingInChunk == 0 || bytesRemainingInChunk == NO_CHUNK_YET) {
- readChunkSize();
- if (!hasMoreChunks) {
- return -1;
- }
- }
- int read = in.read(buffer, offset, Math.min(count, bytesRemainingInChunk));
- if (read == -1) {
- unexpectedEndOfInput(); // the server didn't supply the promised chunk length
- throw new IOException("unexpected end of stream");
- }
- bytesRemainingInChunk -= read;
- cacheWrite(buffer, offset, read);
- return read;
- }
-
- private void readChunkSize() throws IOException {
- // read the suffix of the previous chunk
- if (bytesRemainingInChunk != NO_CHUNK_YET) {
- Util.readAsciiLine(in);
- }
- String chunkSizeString = Util.readAsciiLine(in);
- int index = chunkSizeString.indexOf(";");
- if (index != -1) {
- chunkSizeString = chunkSizeString.substring(0, index);
- }
- try {
- bytesRemainingInChunk = Integer.parseInt(chunkSizeString.trim(), 16);
- } catch (NumberFormatException e) {
- throw new ProtocolException("Expected a hex chunk size but was " + chunkSizeString);
- }
- if (bytesRemainingInChunk == 0) {
- hasMoreChunks = false;
- RawHeaders rawResponseHeaders = httpEngine.responseHeaders.getHeaders();
- RawHeaders.readHeaders(transport.socketIn, rawResponseHeaders);
- httpEngine.receiveHeaders(rawResponseHeaders);
- endOfInput();
- }
- }
-
- @Override public int available() throws IOException {
- checkNotClosed();
- if (!hasMoreChunks || bytesRemainingInChunk == NO_CHUNK_YET) {
- return 0;
- }
- return Math.min(in.available(), bytesRemainingInChunk);
- }
-
- @Override public void close() throws IOException {
- if (closed) {
- return;
- }
- if (hasMoreChunks && !discardStream(httpEngine, this)) {
- unexpectedEndOfInput();
- }
- closed = true;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/c6b171ba/framework/src/com/squareup/okhttp/internal/http/HttpURLConnectionImpl.java
----------------------------------------------------------------------
diff --git a/framework/src/com/squareup/okhttp/internal/http/HttpURLConnectionImpl.java b/framework/src/com/squareup/okhttp/internal/http/HttpURLConnectionImpl.java
deleted file mode 100755
index fb4a704..0000000
--- a/framework/src/com/squareup/okhttp/internal/http/HttpURLConnectionImpl.java
+++ /dev/null
@@ -1,590 +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.internal.Platform;
-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.HttpRetryException;
-import java.net.HttpURLConnection;
-import java.net.InetSocketAddress;
-import java.net.ProtocolException;
-import java.net.Proxy;
-import java.net.SocketPermission;
-import java.net.URL;
-import java.security.Permission;
-import java.security.cert.CertificateException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.TimeUnit;
-import javax.net.ssl.SSLHandshakeException;
-
-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 implements Policy {
-
- /** Numeric status code, 307: Temporary Redirect. */
- public 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;
-
- final OkHttpClient client;
-
- private final RawHeaders rawRequestHeaders = new RawHeaders();
- /** Like the superclass field of the same name, but a long and available on all platforms. */
- private long fixedContentLength = -1;
- private int redirectionCount;
- protected IOException httpEngineFailure;
- protected HttpEngine httpEngine;
- private Proxy selectedProxy;
-
- public HttpURLConnectionImpl(URL url, OkHttpClient client) {
- super(url);
- this.client = client;
- }
-
- @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 Collections.emptyMap();
- }
- }
-
- @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");
- }
-
- return out;
- }
-
- @Override public final Permission getPermission() throws IOException {
- String hostName = getURL().getHost();
- int hostPort = Util.getEffectivePort(getURL());
- if (usingProxy()) {
- InetSocketAddress proxyAddress = (InetSocketAddress) client.getProxy().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);
- }
-
- @Override public void setConnectTimeout(int timeoutMillis) {
- client.setConnectTimeout(timeoutMillis, TimeUnit.MILLISECONDS);
- }
-
- @Override public int getConnectTimeout() {
- return client.getConnectTimeout();
- }
-
- @Override public void setReadTimeout(int timeoutMillis) {
- client.setReadTimeout(timeoutMillis, TimeUnit.MILLISECONDS);
- }
-
- @Override public int getReadTimeout() {
- return client.getReadTimeout();
- }
-
- 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") && !method.equals("PATCH")) {
- // If the request method is neither POST nor PUT nor PATCH, 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;
- }
- }
-
- @Override public 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(client, this, method, requestHeaders, connection, requestBody);
- } else if (url.getProtocol().equals("https")) {
- return new HttpsEngine(client, 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 = httpEngine.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", responseCode);
- }
-
- if (retry == Retry.DIFFERENT_CONNECTION) {
- httpEngine.automaticallyReleaseConnectionToPool();
- }
-
- httpEngine.release(false);
-
- httpEngine = newHttpEngine(retryMethod, rawRequestHeaders, httpEngine.getConnection(),
- (RetryableOutputStream) requestBody);
-
- if (requestBody == null) {
- // Drop the Content-Length header when redirected from POST to GET.
- httpEngine.getRequestHeaders().removeContentLength();
- }
- }
- }
-
- /**
- * 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;
- 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 = (RetryableOutputStream) requestBody;
- httpEngine = newHttpEngine(method, rawRequestHeaders, null, retryableOutputStream);
- httpEngine.routeSelector = routeSelector; // Keep the same routeSelector.
- 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 for 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()
- : client.getProxy();
- 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(client.getAuthenticator(),
- 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 && !client.getFollowProtocolRedirects()) {
- 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) */
- @Override public final long getFixedContentLength() {
- return fixedContentLength;
- }
-
- @Override public final int getChunkLength() {
- return chunkLength;
- }
-
- @Override public final boolean usingProxy() {
- if (selectedProxy != null) {
- return isValidNonDirectProxy(selectedProxy);
- }
-
- // This behavior is a bit odd (but is probably justified by the
- // oddness of the APIs involved). Before a connection is established,
- // this method will return true only if this connection was explicitly
- // opened with a Proxy. We don't attempt to query the ProxySelector
- // at all.
- return isValidNonDirectProxy(client.getProxy());
- }
-
- private static boolean isValidNonDirectProxy(Proxy proxy) {
- return proxy != null && proxy.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");
- }
- if (newValue == null) {
- // Silently ignore null header values for backwards compatibility with older
- // android versions as well as with other URLConnection implementations.
- //
- // Some implementations send a malformed HTTP header when faced with
- // such requests, we respect the spec and ignore the header.
- Platform.get().logW("Ignoring header " + field + " because its value was null.");
- return;
- }
-
- if ("X-Android-Transports".equals(field)) {
- setTransports(newValue, false /* append */);
- } else {
- 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");
- }
- if (value == null) {
- // Silently ignore null header values for backwards compatibility with older
- // android versions as well as with other URLConnection implementations.
- //
- // Some implementations send a malformed HTTP header when faced with
- // such requests, we respect the spec and ignore the header.
- Platform.get().logW("Ignoring header " + field + " because its value was null.");
- return;
- }
-
- if ("X-Android-Transports".equals(field)) {
- setTransports(value, true /* append */);
- } else {
- rawRequestHeaders.add(field, value);
- }
- }
-
- /*
- * Splits and validates a comma-separated string of transports.
- * When append == false, we require that the transport list contains "http/1.1".
- */
- private void setTransports(String transportsString, boolean append) {
- List<String> transportsList = new ArrayList<String>();
- if (append) {
- transportsList.addAll(client.getTransports());
- }
- for (String transport : transportsString.split(",", -1)) {
- transportsList.add(transport);
- }
- client.setTransports(transportsList);
- }
-
- @Override public void setFixedLengthStreamingMode(int contentLength) {
- setFixedLengthStreamingMode((long) contentLength);
- }
-
- // @Override Don't override: this overload method doesn't exist prior to Java 1.7.
- public void setFixedLengthStreamingMode(long contentLength) {
- if (super.connected) throw new IllegalStateException("Already connected");
- if (chunkLength > 0) throw new IllegalStateException("Already in chunked mode");
- if (contentLength < 0) throw new IllegalArgumentException("contentLength < 0");
- this.fixedContentLength = contentLength;
- super.fixedContentLength = (int) Math.min(contentLength, Integer.MAX_VALUE);
- }
-
- @Override public final void setSelectedProxy(Proxy proxy) {
- this.selectedProxy = proxy;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/c6b171ba/framework/src/com/squareup/okhttp/internal/http/HttpsEngine.java
----------------------------------------------------------------------
diff --git a/framework/src/com/squareup/okhttp/internal/http/HttpsEngine.java b/framework/src/com/squareup/okhttp/internal/http/HttpsEngine.java
deleted file mode 100755
index 2bc1d68..0000000
--- a/framework/src/com/squareup/okhttp/internal/http/HttpsEngine.java
+++ /dev/null
@@ -1,72 +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.TunnelRequest;
-import java.io.IOException;
-import java.net.CacheResponse;
-import java.net.SecureCacheResponse;
-import java.net.URL;
-import javax.net.ssl.SSLSocket;
-
-import static com.squareup.okhttp.internal.Util.getEffectivePort;
-
-public final class HttpsEngine extends HttpEngine {
- /**
- * Stash of HttpsEngine.connection.socket to implement requests like {@code
- * HttpsURLConnection#getCipherSuite} even after the connection has been
- * recycled.
- */
- private SSLSocket sslSocket;
-
- public HttpsEngine(OkHttpClient client, Policy policy, String method, RawHeaders requestHeaders,
- Connection connection, RetryableOutputStream requestBody) throws IOException {
- super(client, policy, method, requestHeaders, connection, requestBody);
- this.sslSocket = connection != null ? (SSLSocket) connection.getSocket() : null;
- }
-
- @Override protected void connected(Connection connection) {
- this.sslSocket = (SSLSocket) connection.getSocket();
- super.connected(connection);
- }
-
- @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 path.
- return false;
- }
-
- public SSLSocket getSslSocket() {
- return sslSocket;
- }
-
- @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-android/blob/c6b171ba/framework/src/com/squareup/okhttp/internal/http/HttpsURLConnectionImpl.java
----------------------------------------------------------------------
diff --git a/framework/src/com/squareup/okhttp/internal/http/HttpsURLConnectionImpl.java b/framework/src/com/squareup/okhttp/internal/http/HttpsURLConnectionImpl.java
deleted file mode 100755
index e64fb98..0000000
--- a/framework/src/com/squareup/okhttp/internal/http/HttpsURLConnectionImpl.java
+++ /dev/null
@@ -1,366 +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 android.annotation.SuppressLint;
-import com.squareup.okhttp.OkHttpClient;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-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 javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.HttpsURLConnection;
-import javax.net.ssl.SSLPeerUnverifiedException;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.SSLSocketFactory;
-
-public final class HttpsURLConnectionImpl extends HttpsURLConnection {
-
- /** HttpUrlConnectionDelegate allows reuse of HttpURLConnectionImpl. */
- private final HttpUrlConnectionDelegate delegate;
-
- public HttpsURLConnectionImpl(URL url, OkHttpClient client) {
- super(url);
- delegate = new HttpUrlConnectionDelegate(url, client);
- }
-
- @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.connected) {
- throw new IllegalStateException("Connection has not yet been established");
- }
- return delegate.httpEngine instanceof HttpsEngine
- ? ((HttpsEngine) delegate.httpEngine).getSslSocket()
- : 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.client.setHostnameVerifier(hostnameVerifier);
- }
-
- @Override public HostnameVerifier getHostnameVerifier() {
- return delegate.client.getHostnameVerifier();
- }
-
- @Override public void setSSLSocketFactory(SSLSocketFactory sslSocketFactory) {
- delegate.client.setSslSocketFactory(sslSocketFactory);
- }
-
- @Override public SSLSocketFactory getSSLSocketFactory() {
- return delegate.client.getSslSocketFactory();
- }
-
- @SuppressLint("NewApi")
- @Override public void setFixedLengthStreamingMode(long contentLength) {
- delegate.setFixedLengthStreamingMode(contentLength);
- }
-
- private final class HttpUrlConnectionDelegate extends HttpURLConnectionImpl {
- private HttpUrlConnectionDelegate(URL url, OkHttpClient client) {
- super(url, client);
- }
-
- @Override public HttpURLConnection getHttpConnectionToCache() {
- return HttpsURLConnectionImpl.this;
- }
-
- public SecureCacheResponse getSecureCacheResponse() {
- return httpEngine instanceof HttpsEngine
- ? (SecureCacheResponse) httpEngine.getCacheResponse()
- : null;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/c6b171ba/framework/src/com/squareup/okhttp/internal/http/OkResponseCacheAdapter.java
----------------------------------------------------------------------
diff --git a/framework/src/com/squareup/okhttp/internal/http/OkResponseCacheAdapter.java b/framework/src/com/squareup/okhttp/internal/http/OkResponseCacheAdapter.java
deleted file mode 100755
index 5335c2b..0000000
--- a/framework/src/com/squareup/okhttp/internal/http/OkResponseCacheAdapter.java
+++ /dev/null
@@ -1,57 +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.OkResponseCache;
-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 maybeRemove(String requestMethod, URI uri) throws IOException {
- }
-
- @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-android/blob/c6b171ba/framework/src/com/squareup/okhttp/internal/http/Policy.java
----------------------------------------------------------------------
diff --git a/framework/src/com/squareup/okhttp/internal/http/Policy.java b/framework/src/com/squareup/okhttp/internal/http/Policy.java
deleted file mode 100755
index 0a29d4b..0000000
--- a/framework/src/com/squareup/okhttp/internal/http/Policy.java
+++ /dev/null
@@ -1,49 +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 java.net.HttpURLConnection;
-import java.net.Proxy;
-import java.net.URL;
-
-public interface Policy {
- /** Returns true if HTTP response caches should be used. */
- boolean getUseCaches();
-
- /** Returns the HttpURLConnection instance to store in the cache. */
- HttpURLConnection getHttpConnectionToCache();
-
- /** Returns the current destination URL, possibly a redirect. */
- URL getURL();
-
- /** Returns the If-Modified-Since timestamp, or 0 if none is set. */
- long getIfModifiedSince();
-
- /** Returns true if a non-direct proxy is specified. */
- boolean usingProxy();
-
- /** @see java.net.HttpURLConnection#setChunkedStreamingMode(int) */
- int getChunkLength();
-
- /** @see java.net.HttpURLConnection#setFixedLengthStreamingMode(int) */
- long getFixedContentLength();
-
- /**
- * Sets the current proxy that this connection is using.
- * @see java.net.HttpURLConnection#usingProxy
- */
- void setSelectedProxy(Proxy proxy);
-}
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/c6b171ba/framework/src/com/squareup/okhttp/internal/http/RawHeaders.java
----------------------------------------------------------------------
diff --git a/framework/src/com/squareup/okhttp/internal/http/RawHeaders.java b/framework/src/com/squareup/okhttp/internal/http/RawHeaders.java
deleted file mode 100755
index 8b45320..0000000
--- a/framework/src/com/squareup/okhttp/internal/http/RawHeaders.java
+++ /dev/null
@@ -1,447 +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;
-import java.util.TreeSet;
-
-/**
- * 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;
- }
-
- /**
- * @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. This works around empty header names and header names that start
- * with a colon (created by old broken SPDY versions of the response cache).
- */
- public void addLine(String line) {
- int index = line.indexOf(":", 1);
- if (index != -1) {
- addLenient(line.substring(0, index), line.substring(index + 1));
- } else if (line.startsWith(":")) {
- addLenient("", line.substring(1)); // Empty header name.
- } else {
- addLenient("", line); // No header name.
- }
- }
-
- /** 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 an immutable case-insensitive set of header names. */
- public Set<String> names() {
- TreeSet<String> result = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
- for (int i = 0; i < length(); i++) {
- result.add(getFieldName(i));
- }
- return Collections.unmodifiableSet(result);
- }
-
- /** 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;
- }
-
- /** Returns an immutable list of the header values for {@code name}. */
- public List<String> values(String name) {
- List<String> result = null;
- for (int i = 0; i < length(); i++) {
- if (name.equalsIgnoreCase(getFieldName(i))) {
- if (result == null) result = new ArrayList<String>(2);
- result.add(getValue(i));
- }
- }
- return result != null
- ? Collections.unmodifiableList(result)
- : Collections.<String>emptyList();
- }
-
- /** @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;
- }
-
- /** Returns headers for a name value block containing a SPDY response. */
- public static RawHeaders fromNameValueBlock(List<String> nameValueBlock) throws IOException {
- if (nameValueBlock.size() % 2 != 0) {
- throw new IllegalArgumentException("Unexpected name value block: " + nameValueBlock);
- }
- String status = null;
- String version = null;
- 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();
- }
- String value = values.substring(start, end);
- if (":status".equals(name)) {
- status = value;
- } else if (":version".equals(name)) {
- version = value;
- } else {
- result.namesAndValues.add(name);
- result.namesAndValues.add(value);
- }
- start = end + 1;
- }
- }
- if (status == null) throw new ProtocolException("Expected ':status' header not present");
- if (version == null) throw new ProtocolException("Expected ':version' header not present");
- result.setStatusLine(version + " " + status);
- return result;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-android/blob/c6b171ba/framework/src/com/squareup/okhttp/internal/http/RequestHeaders.java
----------------------------------------------------------------------
diff --git a/framework/src/com/squareup/okhttp/internal/http/RequestHeaders.java b/framework/src/com/squareup/okhttp/internal/http/RequestHeaders.java
deleted file mode 100755
index 71c3cd0..0000000
--- a/framework/src/com/squareup/okhttp/internal/http/RequestHeaders.java
+++ /dev/null
@@ -1,317 +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 long 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 long 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(long contentLength) {
- if (this.contentLength != -1) {
- headers.removeAll("Content-Length");
- }
- headers.add("Content-Length", Long.toString(contentLength));
- this.contentLength = contentLength;
- }
-
- /**
- * Remove the Content-Length headers. Call this when dropping the body on a
- * request or response, such as when a redirect changes the method from POST
- * to GET.
- */
- public void removeContentLength() {
- if (contentLength != -1) {
- headers.removeAll("Content-Length");
- contentLength = -1;
- }
- }
-
- 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))
- && !entry.getValue().isEmpty()) {
- headers.add(key, buildCookieHeader(entry.getValue()));
- }
- }
- }
-
- /**
- * Send all cookies in one big header, as recommended by
- * <a href="http://tools.ietf.org/html/rfc6265#section-4.2.1">RFC 6265</a>.
- */
- private String buildCookieHeader(List<String> cookies) {
- if (cookies.size() == 1) return cookies.get(0);
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < cookies.size(); i++) {
- if (i > 0) sb.append("; ");
- sb.append(cookies.get(i));
- }
- return sb.toString();
- }
-}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cordova.apache.org
For additional commands, e-mail: commits-help@cordova.apache.org